diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 71349c9..f5a7f43 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -324,13 +324,13 @@ A separate diagnostic applies the exported Z/footprint classifier in chain order Contained placement has a separate source-derived diagnostic: for nonzero maps, nonempty contained records consume free IDs, encode nesting depth in the fixed-record X field, ascend the parent link when depth falls, and append children only to container/monster-egg families (`10a8:05e3`, `10a8:2533`, `10a0:0e32`). Synthetic nested/sibling and invalid-parent tests pass; retail map 1 contains no nonzero-shape contained records, so it cannot verify those links. The stage is not a live container cache or a runtime ID-order trace. The shape loader exposes TYPEFLAG row byte 7 as weight, and the `Item_Fall` (`1038:1334`) gate requires a drawable, nonzero-weight shape. The action planner preserves `Item_Grab`'s type-1 fall versus type-2 flag-checked process decision in source order; the first retail origin produces zero actions. -The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include contained items. `runUnobstructedGravity` now moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation; tests cover both paths. This does not execute the zero-speed fall/`Item_Grab` branch, process collision responses, map fast-area gate, or an automatic scheduler tick. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`), which requires fast-area map blocks, item iteration, and resolved collision points absent from the host's boolean-only sweep. DOSBox-X is now installed at `C:\DOSBox-X`, but its interactive debugger has not produced a retail map-load or ItemFind trace; runtime IDs, parents, and first/next search behavior still lack original-execution trace parity. +The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate. -The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied, newly allocated item IDs can also be inserted at a block head with duplicate and placement guards. Focused tests verify process request order for moved and inserted items and the Z value; the host still lacks free-ID allocation, fast-area, viewport, and contained-item side effects. +The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects. The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. The stationary zero-speed fall search, collision response, and automatic scheduler dispatch are still unported; a caller must provide shapes, group counts, and the sweep decision for this host-only branch. -The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. Tests cover combined and Z-only out-of-range targets. It is not yet the sweep's fast-area, item-iteration, or collision-resolution stage, and the gravity runner still requires an explicit approved sweep callback. +The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are now testable with an explicit fast-area range. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags, and an explicit fast-area range. The host now selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts; a live entry point returns the resulting point and first colliding item. Synthetic tests cover both directions on all axes, self-exclusion, non-solid items, chain order, flipped shapes, and candidate selection. It does not handle damaging-only or floor contacts, maintain live fast-area state, or drive gravity movement. The gravity runner still requires an explicit approved sweep callback. Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. @@ -338,8 +338,8 @@ Next source-port checks, in call-chain order: 1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. 2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. -3. Port original free-ID allocation and contained-item ownership, and connect the caller-supplied live insert path to those allocation events. -4. Port the area sweep's fast-area and item-collision resolution, including failed directions and resolved points, before enabling collision-driven movement. +3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership. +4. Add damaging-only and mode-dependent floor contacts, then combine the solid-hit result with bounds and fast-area failures before enabling collision-driven movement. 5. Port the `GravityProcess_Run` area sweep, collision responses, and item-cache position/status writes to make created gravity entries move real items after their sleep. 6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. 7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h index 16bed27..9fc32d9 100644 --- a/rebuild/remorse/include/remorse/collision.h +++ b/rebuild/remorse/include/remorse/collision.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include "remorse\fixed_map.h" @@ -27,10 +28,48 @@ struct SweepBoundsResult { bool failed = false; }; +struct SweepItemImpact { + WorldPoint resolved{}; + u8 failedDirections = 0; +}; + +struct SweepCandidateImpact { + u16 itemNumber = 0; + SweepItemImpact impact{}; +}; + +struct SweepCollisionResult { + WorldPoint destination{}; + u16 firstCollision = 0; + u8 failedDirections = 0; +}; + +struct FastAreaRange { + s32 minSum = 0; + s32 maxSum = 0; + s32 minDifference = 0; + s32 maxDifference = 0; +}; + +bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range); +bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination, + s32 extentX, s32 extentY, const FastAreaRange& range); +WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY); SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination); GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed, s16 gravity, u32 timeScale); CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); +CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); +std::optional sweepSolidItemImpact( + const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle); +std::optional> collectSolidSweepImpacts( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea); +SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination, + const std::vector& impacts); +std::optional resolveSolidLiveSweep( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea); bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); bool canMoveCollisionBody( const CollisionBody& body, diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 37ac7a7..184964c 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -9,6 +9,7 @@ namespace remorse { struct ShapeTypeInfo; +struct WorldRect; class ProcessKernel; struct FixedMapEntry { @@ -100,9 +101,13 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& class LiveFixedMapItems { public: - explicit LiveFixedMapItems(std::vector items); + explicit LiveFixedMapItems(std::vector items, + std::vector containedItems = {}); const StagedFixedMapItem* findItem(u16 itemNumber) const; + u16 containedParent(u16 itemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; + std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; + std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, @@ -113,6 +118,9 @@ public: private: std::vector items_; + std::vector allocatedIds_; + std::vector parentById_; + u16 nextFreeItemNumber_ = 0x100; }; } // namespace remorse diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp index 68f44b4..b14a01b 100644 --- a/rebuild/remorse/src/collision.cpp +++ b/rebuild/remorse/src/collision.cpp @@ -1,6 +1,7 @@ #include "remorse/collision.h" #include +#include #include namespace remorse { @@ -77,6 +78,40 @@ void appendSolidBody(std::vector& bodies, const std::vector 0x7fff || y < 0 || y > 0x7fff) { + return false; + } + const s32 blockX = x >> 9; + const s32 blockY = y >> 9; + return range.minSum <= blockX + blockY && blockX + blockY <= range.maxSum && + range.minDifference <= blockX - blockY && blockX - blockY <= range.maxDifference; +} + +bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination, + s32 extentX, s32 extentY, const FastAreaRange& range) +{ + for (const WorldPoint point : {from, destination}) { + for (const s32 x : {point.x - extentX + 1, point.x}) { + for (const s32 y : {point.y - extentY + 1, point.y}) { + if (!isWorldPointInFastArea(x, y, range)) { + return false; + } + } + } + } + return true; +} + +WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY) +{ + return {std::max(0, std::min(from.x, destination.x) - extentX), + std::max(0, std::min(from.y, destination.y) - extentY), + std::min(0x7fff, std::max(from.x, destination.x) + 0x100), + std::min(0x7fff, std::max(from.y, destination.y) + 0x100)}; +} + SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination) { SweepBoundsResult result{destination}; @@ -117,6 +152,152 @@ CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeI static_cast(shapeInfo.z) * shapeHeightScale}; } +CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped) +{ + const s32 extentX = static_cast(flipped ? shapeInfo.y : shapeInfo.x) * 16; + const s32 extentY = static_cast(flipped ? shapeInfo.x : shapeInfo.y) * 16; + const s32 extentZ = shapeInfo.z == 0 && (shapeInfo.flags & 1) == 0 ? 1 : + static_cast(shapeInfo.z) * shapeHeightScale; + return {location, extentX, extentY, extentZ}; +} + +std::optional sweepSolidItemImpact( + const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle) +{ + if (moving.extentX <= 0 || moving.extentY <= 0 || moving.extentZ <= 0 || + obstacle.extentX <= 0 || obstacle.extentY <= 0 || obstacle.extentZ <= 0) { + return std::nullopt; + } + const std::array origin{moving.location.x, moving.location.y, moving.location.z}; + const std::array delta{ + static_cast(destination.x) - origin[0], + static_cast(destination.y) - origin[1], + static_cast(destination.z) - origin[2]}; + const std::array obstaclePosition{ + obstacle.location.x, obstacle.location.y, obstacle.location.z}; + const std::array movingExtent{moving.extentX, moving.extentY, moving.extentZ}; + const std::array obstacleExtent{obstacle.extentX, obstacle.extentY, obstacle.extentZ}; + std::array lower{}; + std::array upper{}; + for (std::size_t axis = 0; axis < 3; ++axis) { + lower[axis] = obstaclePosition[axis] - obstacleExtent[axis] + 1 - origin[axis]; + upper[axis] = obstaclePosition[axis] + movingExtent[axis] - 1 - origin[axis]; + } + lower[2] = obstaclePosition[2] - movingExtent[2] + 1 - origin[2]; + upper[2] = obstaclePosition[2] + obstacleExtent[2] - 1 - origin[2]; + + for (const int direction : {1, -1}) { + for (std::size_t axis = 0; axis < 3; ++axis) { + const std::int64_t distance = direction > 0 ? lower[axis] : -upper[axis]; + const std::int64_t extent = delta[axis] * direction; + if (distance <= 0 || distance > extent) { + continue; + } + bool withinOtherAxes = true; + for (std::size_t other = 0; other < 3; ++other) { + if (other == axis) { + continue; + } + const std::int64_t progress = delta[other] * distance; + if (progress < lower[other] * extent || progress > upper[other] * extent) { + withinOtherAxes = false; + break; + } + } + if (withinOtherAxes) { + const std::int64_t beforeContact = distance - 1; + std::array resolved{}; + for (std::size_t coordinate = 0; coordinate < 3; ++coordinate) { + resolved[coordinate] = static_cast(origin[coordinate] + + delta[coordinate] * beforeContact / extent); + } + return SweepItemImpact{{resolved[0], resolved[1], resolved[2]}, + static_cast(1u << axis)}; + } + } + } + return std::nullopt; +} + +std::optional> collectSolidSweepImpacts( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + const auto* movingItem = items.findItem(movingItemNumber); + if (movingItem == nullptr || movingItem->data.shape >= shapes.size() || + destination.x < 0 || destination.x > 0x7fff || destination.y < 0 || + destination.y > 0x7fff || destination.z < 0 || destination.z > 0xfa) { + return std::nullopt; + } + const WorldPoint from{movingItem->data.x, movingItem->data.y, movingItem->data.z}; + const auto movingBody = makeSweepItemBody(from, shapes[movingItem->data.shape], + (movingItem->data.flags & flippedFlag) != 0); + if (!isSweepFootprintInFastArea(from, destination, movingBody.extentX, + movingBody.extentY, fastArea)) { + return std::nullopt; + } + const auto candidates = items.sweepCandidateIds(areaSweepCandidateBounds(from, destination, + movingBody.extentX, movingBody.extentY), movingItemNumber); + if (!candidates) { + return std::nullopt; + } + std::vector impacts; + for (const u16 itemNumber : *candidates) { + const auto* item = items.findItem(itemNumber); + if (item == nullptr || item->data.shape >= shapes.size()) { + return std::nullopt; + } + const auto& shape = shapes[item->data.shape]; + if ((shape.flags & solidFlag) == 0) { + continue; + } + const auto obstacle = makeSweepItemBody({item->data.x, item->data.y, item->data.z}, + shape, (item->data.flags & flippedFlag) != 0); + if (const auto impact = sweepSolidItemImpact(movingBody, destination, obstacle)) { + impacts.push_back({itemNumber, *impact}); + } + } + return impacts; +} + +SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination, + const std::vector& impacts) +{ + SweepCollisionResult result{destination}; + for (const auto& candidate : impacts) { + result.failedDirections |= candidate.impact.failedDirections; + const auto& point = candidate.impact.resolved; + if (candidate.itemNumber != 0 && + (std::abs(static_cast(point.x) - from.x) < + std::abs(static_cast(result.destination.x) - from.x) || + std::abs(static_cast(point.y) - from.y) < + std::abs(static_cast(result.destination.y) - from.y) || + std::abs(static_cast(point.z) - from.z) < + std::abs(static_cast(result.destination.z) - from.z))) { + result.destination = point; + result.firstCollision = candidate.itemNumber; + } + } + return result; +} + +std::optional resolveSolidLiveSweep( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + const auto* movingItem = items.findItem(movingItemNumber); + if (movingItem == nullptr) { + return std::nullopt; + } + const auto impacts = collectSolidSweepImpacts(items, movingItemNumber, destination, + shapes, fastArea); + if (!impacts) { + return std::nullopt; + } + return selectSolidSweepImpact({movingItem->data.x, movingItem->data.y, movingItem->data.z}, + destination, *impacts); +} + bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right) { return overlapsAt(left, left.location, right); diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 140a84d..79d4fa5 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -2,6 +2,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include @@ -412,11 +413,30 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& return processIds; } -LiveFixedMapItems::LiveFixedMapItems(std::vector items) : items_(std::move(items)) +LiveFixedMapItems::LiveFixedMapItems(std::vector items, + std::vector containedItems) + : items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800) { if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); } + for (const auto& item : items_) { + allocatedIds_[item.itemNumber] = true; + } + for (const auto& contained : containedItems) { + const u16 itemNumber = contained.itemNumber; + if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || allocatedIds_[itemNumber]) { + throw std::invalid_argument("invalid contained item ID"); + } + allocatedIds_[itemNumber] = true; + } + for (const auto& contained : containedItems) { + if (contained.parentItemNumber < 0x100 || contained.parentItemNumber >= contained.itemNumber || + !allocatedIds_[contained.parentItemNumber]) { + throw std::invalid_argument("invalid contained parent ID"); + } + parentById_[contained.itemNumber] = contained.parentItemNumber; + } } const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const @@ -429,12 +449,61 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const return nullptr; } +u16 LiveFixedMapItems::containedParent(u16 itemNumber) const +{ + return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; +} + std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const { return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance); } +std::optional> LiveFixedMapItems::sweepCandidateIds(const WorldRect& area, + u16 excludedItemNumber) const +{ + if (area.minX < 0 || area.minY < 0 || area.maxX > 0x7fff || area.maxY > 0x7fff || + area.minX > area.maxX || area.minY > area.maxY) { + return std::nullopt; + } + const auto chains = buildStagedItemBlockChains(items_); + if (!chains) { + return std::nullopt; + } + std::vector byId(chains->next.size()); + for (const auto& item : items_) { + byId[item.itemNumber] = &item; + } + const ItemFindArea itemArea{static_cast(area.minX), static_cast(area.minY), + static_cast(area.maxX), static_cast(area.maxY)}; + std::vector candidates; + for (const u16 itemNumber : itemFindCandidateOrder(itemArea, *chains)) { + const auto& item = *byId[itemNumber]; + if (itemNumber != excludedItemNumber && item.data.x >= area.minX && item.data.x <= area.maxX && + item.data.y >= area.minY && item.data.y <= area.maxY) { + candidates.push_back(itemNumber); + } + } + return candidates; +} + +std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) +{ + if (item.data.x > 0x7fff || item.data.y > 0x7fff) { + return std::nullopt; + } + while (nextFreeItemNumber_ < allocatedIds_.size() && allocatedIds_[nextFreeItemNumber_]) { + ++nextFreeItemNumber_; + } + if (nextFreeItemNumber_ == allocatedIds_.size()) { + return std::nullopt; + } + item.itemNumber = nextFreeItemNumber_; + insertItem(item); + return item.itemNumber; +} + bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) { if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || @@ -443,6 +512,8 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) } item.data.z = std::min(item.data.z, 0xfa); items_.push_back(item); + allocatedIds_[item.itemNumber] = true; + parentById_[item.itemNumber] = 0; return true; } diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index becb72f..fa3712d 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -160,6 +160,16 @@ void loadSceneAsync(HWND window, AppState& state) PostMessageW(window, sceneReadyMessage, 0, 0); return; } + std::vector containedItems; + if (map->index != 0) { + const auto contained = remorse::stageContainedFixedMapItems(*map, *shapeTypes); + if (!contained) { + setLoadFailure(state, L"Contained map items could not be staged."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + containedItems = std::move(*contained); + } auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects); const auto usecodePath = remorse::resolveGameDataPath( state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); @@ -281,7 +291,7 @@ void loadSceneAsync(HWND window, AppState& state) state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; if (stagedItems) { - state.liveItems.emplace(std::move(*stagedItems)); + state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems)); } state.sceneLoaded = true; } diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp index b3b06e6..bde848a 100644 --- a/rebuild/remorse/tests/collision_tests.cpp +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -4,6 +4,24 @@ int main() { + const remorse::FastAreaRange fastArea{2, 4, 0, 2}; + assert(remorse::isWorldPointInFastArea(512, 512, fastArea)); + assert(!remorse::isWorldPointInFastArea(-1, 512, fastArea)); + assert(!remorse::isWorldPointInFastArea(0x8000, 512, fastArea)); + assert(remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, fastArea)); + assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, {2, 3, 0, 2})); + assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, {2, 4, 1, 2})); + const auto sweepArea = remorse::areaSweepCandidateBounds({511, 512, 0}, {1024, 1536, 0}, 32, 64); + assert(sweepArea.minX == 479 && sweepArea.minY == 448 && + sweepArea.maxX == 1280 && sweepArea.maxY == 1792); + const auto reverseArea = remorse::areaSweepCandidateBounds({1024, 1536, 0}, {511, 512, 0}, 32, 64); + assert(reverseArea.minX == sweepArea.minX && reverseArea.maxY == sweepArea.maxY); + const auto edgeSweepArea = remorse::areaSweepCandidateBounds({10, 10, 0}, {0x7fff, 0x7fff, 0}, 32, 64); + assert(edgeSweepArea.minX == 0 && edgeSweepArea.minY == 0 && + edgeSweepArea.maxX == 0x7fff && edgeSweepArea.maxY == 0x7fff); const auto outsideBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {-3, 0x8000, 252}); assert(outsideBounds.destination.x == 0 && outsideBounds.destination.y == 0x7fff && outsideBounds.destination.z == 250 && outsideBounds.failedDirections == 7 && @@ -56,6 +74,105 @@ int main() assert(flipped.extentX == 128); assert(flipped.extentY == 64); + const auto sweepItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo, true); + assert(sweepItem.extentX == 64 && sweepItem.extentY == 32 && sweepItem.extentZ == 64); + obstacleInfo.z = 0; + const auto zeroHeightItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo); + assert(zeroHeightItem.extentZ == 1); + obstacleInfo.flags = 1; + assert(remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo).extentZ == 0); + obstacleInfo.z = 8; + obstacleInfo.flags = 0; + + const remorse::CollisionBody sweepActor{{100, 100, 0}, 32, 32, 16}; + const remorse::CollisionBody sweepWall{{200, 100, 0}, 32, 32, 16}; + const auto rightHit = remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0}, sweepWall); + assert(rightHit && rightHit->failedDirections == 1 && rightHit->resolved.x == 168); + const auto leftHit = remorse::sweepSolidItemImpact({{300, 100, 0}, 32, 32, 16}, + {150, 100, 0}, sweepWall); + assert(leftHit && leftHit->failedDirections == 1 && leftHit->resolved.x == 232); + const auto upHit = remorse::sweepSolidItemImpact(sweepActor, {100, 250, 0}, + {{100, 200, 0}, 32, 32, 16}); + assert(upHit && upHit->failedDirections == 2 && upHit->resolved.y == 168); + const auto downHit = remorse::sweepSolidItemImpact({{100, 300, 0}, 32, 32, 16}, + {100, 150, 0}, {{100, 200, 0}, 32, 32, 16}); + assert(downHit && downHit->failedDirections == 2 && downHit->resolved.y == 232); + const auto ascendingHit = remorse::sweepSolidItemImpact(sweepActor, {100, 100, 30}, + {{100, 100, 20}, 32, 32, 16}); + assert(ascendingHit && ascendingHit->failedDirections == 4 && ascendingHit->resolved.z == 4); + const auto descendingHit = remorse::sweepSolidItemImpact({{100, 100, 40}, 32, 32, 16}, + {100, 100, 0}, {{100, 100, 20}, 32, 32, 16}); + assert(descendingHit && descendingHit->failedDirections == 4 && descendingHit->resolved.z == 36); + assert(!remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0}, + {{200, 200, 0}, 32, 32, 16})); + + remorse::StagedFixedMapItem movingItem; + movingItem.itemNumber = 0x100; + movingItem.data.x = 512; + movingItem.data.y = 512; + movingItem.data.shape = 1; + auto wallItem = movingItem; + wallItem.itemNumber = 0x101; + wallItem.data.x = 640; + wallItem.data.shape = 2; + auto harmlessItem = wallItem; + harmlessItem.itemNumber = 0x102; + harmlessItem.data.x = 600; + harmlessItem.data.shape = 3; + remorse::LiveFixedMapItems liveSweepItems({movingItem, wallItem, harmlessItem}); + std::vector sweepShapes(4); + sweepShapes[1].x = sweepShapes[1].y = sweepShapes[1].z = 2; + sweepShapes[2] = sweepShapes[1]; + sweepShapes[2].flags = 2; + sweepShapes[3] = sweepShapes[1]; + const remorse::FastAreaRange allBlocks{-128, 128, -128, 128}; + const auto liveImpacts = remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(liveImpacts && liveImpacts->size() == 1); + assert((*liveImpacts)[0].itemNumber == 0x101 && + (*liveImpacts)[0].impact.failedDirections == 1 && + (*liveImpacts)[0].impact.resolved.x == 608); + auto nextWall = wallItem; + nextWall.itemNumber = 0x103; + nextWall.data.x = 670; + sweepShapes[2].x = 1; + sweepShapes[2].y = 4; + wallItem.data.flags = 0x20; + remorse::LiveFixedMapItems flippedSweepItems({movingItem, wallItem, nextWall, harmlessItem}); + const auto flippedImpacts = remorse::collectSolidSweepImpacts(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(flippedImpacts && flippedImpacts->size() == 2); + assert((*flippedImpacts)[0].itemNumber == 0x103 && (*flippedImpacts)[0].impact.resolved.x == 654); + assert((*flippedImpacts)[1].itemNumber == 0x101 && (*flippedImpacts)[1].impact.resolved.x == 576); + const auto nearestImpact = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 512, 0}, *flippedImpacts); + assert(nearestImpact.firstCollision == 0x101 && nearestImpact.destination.x == 576 && + nearestImpact.failedDirections == 1); + const auto resolvedLive = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(resolvedLive && resolvedLive->firstCollision == 0x101 && + resolvedLive->destination.x == 576 && resolvedLive->failedDirections == 1); + assert(!remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); + const auto noImpact = remorse::selectSolidSweepImpact({512, 512, 0}, {700, 512, 0}, {}); + assert(noImpact.firstCollision == 0 && noImpact.destination.x == 700 && + noImpact.failedDirections == 0); + const std::vector tiedImpacts{ + {0x101, {{576, 512, 0}, 1}}, {0x103, {{576, 512, 0}, 2}}}; + const auto tiedImpact = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 512, 0}, tiedImpacts); + assert(tiedImpact.firstCollision == 0x101 && tiedImpact.failedDirections == 3); + const std::vector mixedAxisImpacts{ + {0x101, {{540, 590, 0}, 1}}, {0x103, {{550, 550, 0}, 2}}}; + const auto mixedAxis = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 700, 0}, mixedAxisImpacts); + assert(mixedAxis.firstCollision == 0x103 && mixedAxis.destination.x == 550 && + mixedAxis.destination.y == 550 && mixedAxis.failedDirections == 3); + assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); + assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x105, + {700, 512, 0}, sweepShapes, allBlocks)); + remorse::FixedMap map; remorse::FixedMapEntry solid; solid.x = 500; diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 5a043da..bd81532 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -1,6 +1,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include @@ -181,6 +182,9 @@ int main() assert(!liveItems.moveItem(0x100, 0x8000, 0, 0)); assert(liveItems.moveItem(0x100, 768, 511, 81)); assert(liveItems.findItem(0x100)->data.x == 768 && blockItems[0].data.x == 511); + const auto sweepBefore = liveItems.sweepCandidateIds({511, 511, 512, 512}, 0x105); + assert(sweepBefore && (*sweepBefore == std::vector{0x103, 0x102})); + assert(!liveItems.sweepCandidateIds({-1, 0, 512, 512}, 0x105)); assert(liveItems.nearestItem(768 * 2, 511 * 2, 0)->itemNumber == 0x100); assert(!liveItems.nearestItem(511 * 2, 511 * 2, -1)); assert(!liveItems.grabItem(0x106, searchShapes, liveKernel, liveGroups, 14)); @@ -197,6 +201,8 @@ int main() reorderedKernel.createProcess(1, reorderedGroups); } assert(reorderedItems.moveItem(0x100, 511, 511, 81)); + const auto sweepAfter = reorderedItems.sweepCandidateIds({511, 511, 512, 512}, 0x105); + assert(sweepAfter && (*sweepAfter == std::vector{0x100, 0x103, 0x102})); const auto reorderedGrab = reorderedItems.grabItem(0x105, searchShapes, reorderedKernel, reorderedGroups, 14); assert(reorderedGrab && reorderedGrab->size() == 2 && (*reorderedGrab)[0] == 3 && @@ -221,6 +227,14 @@ int main() insertedKernel, insertedGroups, 14); assert(insertedGrab && insertedGrab->size() == 3 && (*insertedGrab)[0] == 3); assert(insertedKernel.findProcessForItemAndType(0x106, 0xf1) == insertedKernel.processAt(3)); + remorse::LiveFixedMapItems allocatedItems(blockItems, {{0x101, 0x100, 0}}); + newItem.itemNumber = 0; + assert(!allocatedItems.findItem(0x101)); + assert(allocatedItems.allocateItem(newItem) == 0x106); + assert(allocatedItems.findItem(0x106)->data.x == 511); + assert(allocatedItems.allocateItem(newItem) == 0x107); + newItem.data.x = 0x8000; + assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -326,6 +340,25 @@ int main() assert((*contained)[0].itemNumber == 0x101 && (*contained)[0].parentItemNumber == 0x100); assert((*contained)[1].itemNumber == 0x102 && (*contained)[1].parentItemNumber == 0x101); assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100); + const auto directContainerItems = remorse::stageFixedMapItems(containedMap); + assert(directContainerItems && directContainerItems->size() == 2); + remorse::LiveFixedMapItems nestedItems(*directContainerItems, *contained); + assert(nestedItems.containedParent(0x101) == 0x100 && + nestedItems.containedParent(0x102) == 0x101 && nestedItems.containedParent(0x103) == 0x100); + remorse::StagedFixedMapItem nestedNewItem = directContainerItems->front(); + assert(nestedItems.allocateItem(nestedNewItem) == 0x105); + assert(!nestedItems.findItem(0x101) && !nestedItems.findItem(0x102) && + !nestedItems.findItem(0x103) && nestedItems.findItem(0x105)); + nestedNewItem.itemNumber = 0x101; + assert(nestedItems.insertItem(nestedNewItem)); + assert(nestedItems.containedParent(0x101) == 0 && nestedItems.containedParent(0x102) == 0x101); + std::vector fullItemRange; + for (remorse::u16 itemNumber = 0x101; itemNumber < 0x2800; ++itemNumber) { + fullItemRange.push_back({itemNumber, 0x100, 0}); + } + remorse::LiveFixedMapItems exhaustedItems({directContainerItems->front()}, fullItemRange); + assert(!exhaustedItems.allocateItem(nestedNewItem)); + assert(!exhaustedItems.findItem(0x101) && exhaustedItems.containedParent(0x101) == 0x100); containerShapes[1].family = 0; assert(!remorse::stageContainedFixedMapItems(containedMap, containerShapes)); assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0]));