From b99fb59c125fe4a71867af733bf27466415e6ac7 Mon Sep 17 00:00:00 2001 From: Maddo Date: Sat, 26 Sep 2026 19:20:20 +0200 Subject: [PATCH] Enhance item handling and collision detection in remorse - Introduced new functionality for staging and managing fixed map items, including the ability to build block chains and find candidates for item interactions. - Updated the main application logic to utilize staged item block chains for improved item finding and grabbing mechanics. - Added weight attribute to shape type information, allowing for more nuanced item interactions based on weight. - Enhanced collision tests to cover new item handling scenarios, including gravity sweeps and item grabbing. - Implemented additional tests for entity dispatch entries and fixed map items to ensure robustness of item spawning and movement logic. - Improved type flags loading to validate weight against binary data, ensuring consistency in item attributes. --- docs/remorse-windows-rebuild-roadmap.md | 34 ++- rebuild/remorse/include/remorse/collision.h | 14 + .../include/remorse/entity_dispatch_entry.h | 18 ++ rebuild/remorse/include/remorse/fixed_map.h | 58 ++++ rebuild/remorse/include/remorse/type_flags.h | 1 + rebuild/remorse/src/collision.cpp | 29 ++ rebuild/remorse/src/entity_dispatch_entry.cpp | 133 ++++++++- rebuild/remorse/src/fixed_map.cpp | 263 ++++++++++++++++++ rebuild/remorse/src/main.cpp | 21 ++ rebuild/remorse/src/type_flags.cpp | 1 + rebuild/remorse/src/windowed_game_main.cpp | 12 +- rebuild/remorse/tests/collision_tests.cpp | 18 ++ .../tests/entity_dispatch_entry_tests.cpp | 172 ++++++++++++ rebuild/remorse/tests/fixed_map_tests.cpp | 200 +++++++++++++ rebuild/remorse/tests/type_flags_tests.cpp | 5 + 15 files changed, 961 insertions(+), 18 deletions(-) diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 75bc7f1..71349c9 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -316,18 +316,32 @@ The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, a `FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host now compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. The original infinite loop, interval wait, DOS interrupt delivery, and live group-transition trace remain unported. -The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; block-chain traversal, loop-script evaluation, and live item state are absent, so the classifier is not yet used to select a window item. +The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a complete port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; live item state and general loop-script evaluation remain absent, and the classifier is not used to select a window item. -The area-search setup now translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). Tests cover a four-block crossing and a staged retail origin; the harness computes four candidate blocks for its first staged map-1 item. These are block indices only, not block heads, item-next chains, or script-filtered search results. +The area-search setup translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). `ItemCache_10a8_00a0` (`10a8:00a0`) inserts directly placed records at the head of each block's `g_itemNext` chain, and the `10c0:1637` iterator follows that chain before advancing blocks. The staged host now reconstructs those heads/links from non-contained item records, rejects duplicate/out-of-range IDs and coordinates, and visits candidates in source block order. Synthetic tests distinguish chain order from record order; retail map 1 yields eight staged candidates in four search blocks around the first item. + +A separate diagnostic applies the exported Z/footprint classifier in chain order, yielding one script-free match for the retail origin with both Z flags enabled. Live `Item_Grab` (`10a0:2970`) pushes script pointer `DS:102d`, script length **1**, and Z flags **3**; callee `10c0:0f73` reads the flags at `[BP+0x12]`, correcting misleading export parameter names. The byte at `DS:102d` is `$`, which selects the `0x5000` fast iterator in `ItemFind_AreaSearch2` (`10c0:1099`). Live `10c8:0385` walks item-next links and X-first blocks, accepting only candidates whose X/Y coordinates lie inside the inclusive search rectangle, before the Z classifier. The host's bounded `Item_Grab` search applies these gates to staged, directly placed items; a test excludes an out-of-rectangle item whose footprint would otherwise pass. Retail map 1 yields one candidate for its first staged item. + +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 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 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. + +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. Next source-port checks, in call-chain order: -1. Check the live allocator/process pair at the `0x23ff/0x2400` item boundary before widening process lookup tables or changing the guard. -2. Compare timed scheduler snapshots, post-scan callbacks, and active-group transitions with a live runtime trace; port the interval wait only behind a host timing boundary. -3. Reconstruct block heads and `g_itemNext` chains for staged retail items, including insertion order and contained-item handling, before consuming the computed search blocks. -4. Recover the `Item_Grab` loop-script predicate and the `10c0:1637` iterator before connecting the isolated Z/footprint classifier to item search. -5. Trace and port `Item_Fall` (`1038:1334`) for search-result type 1, keeping it separate from process creation. -6. Wire `Item_Grab` (`10a0:2970`) to the recovered search and per-item status check, then compare requested process IDs against a live trace. +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. +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. ## First Interactive Windows Game Shell @@ -350,11 +364,11 @@ The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at The Phase 4 diagnostic now stages directly placed, nonzero-shape `FIXED.DAT` records into item-numbered state using the initial free-list head `0x100` and capacity `0x2700` from `ItemCache_InitAndLoadFixedDat` (`10a8:163a`). It skips zero-shape records, accounts for contained records consuming an ID without staging them as world items, and clears the status low bit for directly placed records as `ItemCache_10a8_00a0` does. Map 1 has 7,547 source records; the harness constructs an `ItemProcess` for the first eligible staged record (shape 16, diagnostic ID 256), advances a scheduler tick, records the `UC_Release` request, and verifies the process is removed. The window waits for `F` near a staged item before scheduling the one-shot path and showing its result on a separate diagnostic HUD row. Retail-data and two-tick regression tests check shape/record provenance, release-request count, process removal, and item-presence/group-count cleanup. -This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement cache block chains, contained-item placement, shape-flag cache-out, or verified live item IDs. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs. +This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement live contained-item placement, shape-flag cache-out, or verified runtime item IDs. The staged direct-placement block chains and separate contained-parent diagnostic are read-only, not a live item cache. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs. The Windows diagnostic no longer schedules the first staged item on scene load. `F` now selects a staged fixed-map record within 48 world units of the host-controlled actor (nearest in X/Y, using the fixed-record display scale), then runs the existing `ItemProcess` release callback on the next scheduler tick. The HUD reports the candidate and callback result; a synthetic proximity test and the MSVC/CTest gate cover selection and the existing process lifecycle. This is a one-shot diagnostic with no item-type filtering, vertical reach, USECODE event execution, or visible item-state change. Exported `Item_Grab` (`10a0:2970`) uses `ItemFind` search and an item-cache status guard before creating item processes; exported `Item_Release` (`10a0:2a06`) calls `Usecode_ItemCallEvent` with `UC_Release`. Neither original trigger nor the event executor is ported, so this change does not meet the playable-game milestone. -The `Item_Grab` creation branch now applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before queuing a diagnostic process. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall` instead, which is not ported. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The host still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or falling items, and must not treat process-presence bookkeeping as the checked item flag. +The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before a type-2 process request. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall`, whose hurl request now creates or merges a sleeping gravity entry in the host. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The window still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or gravity movement, and must not treat process-presence bookkeeping as the checked item flag. The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). The harness resolves and reports the `EVENT` body (8,150 bytes). `Item_GetUsecodeClassId` selects a class from item identity and startup class bases; `Usecode_ItemCallEvent` gates on the owner row. Map-1 tests cover both its classless first staged item and at least one actual staged item with an eligible release body. The window applies both checks to the nearest staged item's release request and labels eligible bytes NOT RUN. This remains lookup, not bytecode interpretation or a live owner-loaded item system. The next original call is `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`, mode 2, selected class/slot and a four-byte parameter), which initializes an interpreter through `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). No context, interpreter dispatch, or item side effect is ported. Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; an isolated opcode stub would not complete that call chain. diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h index a8abd2b..16bed27 100644 --- a/rebuild/remorse/include/remorse/collision.h +++ b/rebuild/remorse/include/remorse/collision.h @@ -16,6 +16,20 @@ struct CollisionBody { s32 extentZ = 0; }; +struct GravitySweepPlan { + WorldPoint destination{}; + s16 nextZSpeed = 0; +}; + +struct SweepBoundsResult { + WorldPoint destination{}; + u8 failedDirections = 0; + bool failed = false; +}; + +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); bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); bool canMoveCollisionBody( diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index e43e059..d4a1ef1 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -8,6 +8,10 @@ namespace remorse { +class LiveFixedMapItems; +struct ShapeTypeInfo; +struct WorldPoint; + CR_PACK_PUSH_1 struct EntityDispatchEntryBase { u8 bytes[0x32]; @@ -18,6 +22,11 @@ struct StandProcessEntry { u8 extra[0x10]; } CR_PACKED; +struct GravityProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x10]; +} CR_PACKED; + struct SystemTimerProcessEntry { EntityDispatchEntryBase base; u8 extra[0x18]; @@ -51,6 +60,7 @@ CR_PACK_POP static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence"); static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence"); +static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size must match allocation evidence"); static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); @@ -71,6 +81,12 @@ public: EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]); StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]); EntityDispatchEntryBase* createItemProcess(u8 activeGroup, u16 itemNumber, u16 (&groupCounts)[32]); + u16 hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, + u32 timerTick, u16 (&groupCounts)[32]); + bool runUnobstructedGravity(u16 processId, LiveFixedMapItems& items, u32 timeScale, u32 timerTick, + bool (*approveSweep)(u16 itemNumber, const WorldPoint& from, const WorldPoint& to, void* context), + void* context, const std::vector* shapes = nullptr, + u16 (*groupCounts)[32] = nullptr); SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -93,6 +109,7 @@ public: u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, void (*afterScan)(void*) = nullptr, void* afterContext = nullptr); EntityDispatchEntryBase* processAt(u16 id) const; + EntityDispatchEntryBase* findProcessForItemAndType(u16 itemNumber, u16 eventType) const; u16 allocationSizeAt(u16 id) const; const char* processNameAt(u16 id) const; bool itemHasProcess(u16 itemNumber) const; @@ -111,6 +128,7 @@ private: std::vector processNames_; std::vector> ownedProcesses_; std::vector> ownedStandProcesses_; + std::vector> ownedGravityProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index e3ae718..37ac7a7 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; +class ProcessKernel; struct FixedMapEntry { u16 x = 0; @@ -34,6 +35,12 @@ struct StagedFixedMapItem { FixedMapEntry data; }; +struct StagedContainedFixedMapItem { + u16 itemNumber = 0; + u16 parentItemNumber = 0; + std::size_t recordIndex = 0; +}; + struct ItemFindArea { u16 minX = 0; u16 minY = 0; @@ -41,6 +48,26 @@ struct ItemFindArea { u16 maxY = 0; }; +struct StagedItemBlockChains { + std::vector heads; + std::vector next; +}; + +struct ItemFindZCandidate { + u16 itemNumber = 0; + u8 matchType = 0; +}; + +enum class ItemGrabActionKind { + Hurl, + CreateProcess +}; + +struct ItemGrabAction { + u16 itemNumber = 0; + ItemGrabActionKind kind = ItemGrabActionKind::Hurl; +}; + struct FixedMapArchive { u32 mapCount = 0; std::vector bytes; @@ -49,12 +76,43 @@ struct FixedMapArchive { std::optional loadFixedMapArchive(const std::filesystem::path& path); std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); std::optional> stageFixedMapItems(const FixedMap& map); +std::optional> stageContainedFixedMapItems( + const FixedMap& map, const std::vector& shapes); std::optional nearestStagedFixedMapItem( const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance); bool itemGrabCanCreateProcess(const StagedFixedMapItem& item); +bool itemFallStartsHurl(const ShapeTypeInfo& shape); u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags); ItemFindArea itemFindAreaAroundItem(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape); std::vector itemFindBlockOrder(const ItemFindArea& area); +std::optional buildStagedItemBlockChains(const std::vector& items); +std::vector itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains); +std::optional> itemFindZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, u8 zMatchFlags); +std::optional> itemGrabSearchCandidates(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes); +std::optional> planItemGrabActions(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes); +std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick); + +class LiveFixedMapItems { +public: + explicit LiveFixedMapItems(std::vector items); + const StagedFixedMapItem* findItem(u16 itemNumber) const; + std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; + bool insertItem(StagedFixedMapItem item); + bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); + std::optional> grabItem(u16 itemNumber, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; + std::optional> moveApprovedItem(u16 itemNumber, u16 x, u16 y, u8 z, + const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick); + +private: + std::vector items_; +}; } // namespace remorse diff --git a/rebuild/remorse/include/remorse/type_flags.h b/rebuild/remorse/include/remorse/type_flags.h index 9abd84a..f73698a 100644 --- a/rebuild/remorse/include/remorse/type_flags.h +++ b/rebuild/remorse/include/remorse/type_flags.h @@ -15,6 +15,7 @@ struct ShapeTypeInfo { u8 y = 0; u8 z = 0; u8 animationType = 0; + u8 weight = 0; }; std::optional> loadTypeFlags(const std::filesystem::path& path); diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp index b4cc809..68f44b4 100644 --- a/rebuild/remorse/src/collision.cpp +++ b/rebuild/remorse/src/collision.cpp @@ -77,6 +77,35 @@ void appendSolidBody(std::vector& bodies, const std::vector 0x7fff) { + result.destination.x = destination.x < from.x ? 0 : 0x7fff; + result.failedDirections |= 1; + result.failed = true; + } + if (destination.y < 0 || destination.y > 0x7fff) { + result.destination.y = destination.y < from.y ? 0 : 0x7fff; + result.failedDirections |= 2; + result.failed = true; + } + if (destination.z < 0 || destination.z > 0xfa) { + result.destination.z = std::clamp(destination.z, 0, 0xfa); + result.failedDirections |= 4; + } + return result; +} + +GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed, + s16 gravity, u32 timeScale) +{ + const s32 multiplier = static_cast(std::clamp(timeScale, 1u, 4u)); + return {{location.x + xSpeed * multiplier, location.y + ySpeed * multiplier, + static_cast(location.z + zSpeed * multiplier)}, + static_cast(zSpeed - gravity * multiplier)}; +} + CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped) { const s32 extentX = static_cast(flipped ? shapeInfo.y : shapeInfo.x) * shapeDimensionScale; diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index a41b9a2..904b439 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -1,4 +1,6 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/collision.h" +#include "remorse/fixed_map.h" #include #include @@ -122,11 +124,115 @@ EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 it setLastAllocationSize(sizeof(EntityDispatchEntryBase)); const u16 id = addProcess(*process); processNames_[id] = "ItemProcess"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->bytes[0x16] |= 0x40; + } + } EntityDispatchEntryBase* result = process.get(); ownedProcesses_.push_back(std::move(process)); return result; } +u16 ProcessKernel::hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, + u32 timerTick, u16 (&groupCounts)[32]) +{ + if (itemNumber == 0 || itemNumber > maxTrackedItemNumber) { + throw std::out_of_range("gravity item number exceeds process lookup tables"); + } + if (auto* existing = findProcessForItemAndType(itemNumber, 0x203)) { + const u16 processId = readLe16(*existing, 0x02); + if (allocationSizeAt(processId) != sizeof(GravityProcessEntry) || + std::none_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [existing](const auto& process) { return &process->base == existing; })) { + throw std::logic_error("gravity process ownership is not ported"); + } + writeLe16(*existing, 0x32, static_cast(readLe16(*existing, 0x32) + xs)); + writeLe16(*existing, 0x34, static_cast(readLe16(*existing, 0x34) + ys)); + writeLe16(*existing, 0x36, static_cast(readLe16(*existing, 0x36) + zs)); + return processId; + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + ownedGravityProcesses_.reserve(ownedGravityProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x0610); + setProcessSourceType(process->base, itemNumber); + setProcessEventTypeChecked(process->base, 0x203); + writeLe16(process->base, 0x32, static_cast(xs)); + writeLe16(process->base, 0x34, static_cast(ys)); + writeLe16(process->base, 0x36, static_cast(zs)); + writeLe16(process->base, 0x38, static_cast(gravity)); + writeLe16(process->base, 0x3b, 200); + process->base.bytes[0x3a] = 1; + process->base.bytes[0x3d] = 1; + setLastAllocationSize(sizeof(GravityProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Gravity"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->base.bytes[0x16] |= 0x40; + } + } + EntityDispatchEntry::sleep(process->base, timerTick, 0x14); + ownedGravityProcesses_.push_back(std::move(process)); + return id; +} + +bool ProcessKernel::runUnobstructedGravity(u16 processId, LiveFixedMapItems& items, + u32 timeScale, u32 timerTick, + bool (*approveSweep)(u16, const WorldPoint&, const WorldPoint&, void*), void* context, + const std::vector* shapes, u16 (*groupCounts)[32]) +{ + const auto* process = processAt(processId); + if (process == nullptr || approveSweep == nullptr || allocationSizeAt(processId) != sizeof(GravityProcessEntry) || + (process->bytes[0x16] & 0x08) != 0 || (process->bytes[0x19] & 0x10) != 0 || + std::none_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; })) { + return false; + } + const u16 itemNumber = readLe16(*process, 0x04); + const auto* item = items.findItem(itemNumber); + const auto zSpeed = static_cast(readLe16(*process, 0x36)); + if (item == nullptr || item->data.z > 250) { + return false; + } + if (zSpeed == 0) { + if (shapes == nullptr || groupCounts == nullptr || + (readLe16(*process, 0x32) == 0 && readLe16(*process, 0x34) == 0) || + !items.grabItem(itemNumber, *shapes, *this, *groupCounts, timerTick)) { + return false; + } + } + const WorldPoint from{item->data.x, item->data.y, item->data.z}; + const auto step = planGravitySweep(from, static_cast(readLe16(*process, 0x32)), + static_cast(readLe16(*process, 0x34)), zSpeed, + static_cast(readLe16(*process, 0x38)), timeScale); + if (step.destination.x < 0 || step.destination.x > 0x7fff || + step.destination.y < 0 || step.destination.y > 0x7fff || step.destination.z > 250 || + !approveSweep(itemNumber, from, step.destination, context)) { + return false; + } + if (!items.moveItem(itemNumber, static_cast(step.destination.x), + static_cast(step.destination.y), static_cast(step.destination.z))) { + return false; + } + auto* mutableProcess = processAt(processId); + writeLe16(*mutableProcess, 0x36, static_cast(step.nextZSpeed)); + EntityDispatchEntry::sleep(*mutableProcess, timerTick, 4 * std::clamp(timeScale, 1u, 4u)); + return true; +} + SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]) { if (systemTimerProcess_ != nullptr) { @@ -312,6 +418,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedStandProcesses_.erase(stand); return; } + const auto gravity = std::find_if(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (gravity != ownedGravityProcesses_.end()) { + ownedGravityProcesses_.erase(gravity); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -336,15 +448,19 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) } const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); + const bool ownedGravityProcess = readLe16(*entry, 0x00) == 0x0610 && + std::any_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); - if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess || id < 3 || + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } - if (stand == ownedStandProcesses_.end() && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), + if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && + std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); } @@ -533,6 +649,19 @@ EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const return id < processes_.size() ? processes_[id] : nullptr; } +EntityDispatchEntryBase* ProcessKernel::findProcessForItemAndType(u16 itemNumber, u16 eventType) const +{ + for (std::size_t id = 3; id < processes_.size(); ++id) { + EntityDispatchEntryBase* process = processes_[id]; + if (process != nullptr && (itemNumber == 0 || readLe16(*process, 0x04) == itemNumber) && + (eventType == 0x0c || readLe16(*process, 0x06) == eventType) && + (readLe16(*process, 0x16) & 0x08) == 0) { + return process; + } + } + return nullptr; +} + u16 ProcessKernel::allocationSizeAt(u16 id) const { return id < allocationSizes_.size() ? allocationSizes_[id] : 0; diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 33222ff..140a84d 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -1,8 +1,13 @@ #include "remorse/fixed_map.h" +#include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/type_flags.h" +#include +#include +#include + namespace remorse { namespace { @@ -147,6 +152,54 @@ std::optional> stageFixedMapItems(const FixedMap return items; } +std::optional> stageContainedFixedMapItems( + const FixedMap& map, const std::vector& shapes) +{ + if (map.index == 0) { + return std::nullopt; + } + std::vector contained; + std::vector parentById(0x2800); + std::vector shapeById(0x2800); + u16 previousItemNumber = 0; + u16 currentParent = 0; + u16 currentDepth = 0; + std::size_t allocated = 0; + for (std::size_t index = 0; index < map.entries.size(); ++index) { + const auto& record = map.entries[index]; + if (record.shape == 0) { + continue; + } + if (allocated == 0x2700 || record.shape >= shapes.size()) { + return std::nullopt; + } + const auto itemNumber = static_cast(0x100 + allocated++); + shapeById[itemNumber] = record.shape; + if ((record.flags & 8) != 0) { + const u16 depth = record.x / crusaderCoordinateScale; + if (depth > currentDepth) { + currentParent = previousItemNumber; + currentDepth = depth; + } + while (depth < currentDepth) { + currentParent = parentById[currentParent]; + --currentDepth; + } + if (currentParent == 0 || (shapes[shapeById[currentParent]].family != 6 && + shapes[shapeById[currentParent]].family != 7)) { + return std::nullopt; + } + parentById[itemNumber] = currentParent; + contained.push_back({itemNumber, currentParent, index}); + } else { + currentParent = 0; + currentDepth = 0; + } + previousItemNumber = itemNumber; + } + return contained; +} + std::optional nearestStagedFixedMapItem( const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance) { @@ -173,6 +226,11 @@ bool itemGrabCanCreateProcess(const StagedFixedMapItem& item) return (item.data.flags & 0x02) == 0; } +bool itemFallStartsHurl(const ShapeTypeInfo& shape) +{ + return (shape.flags & 1) == 0 && shape.weight != 0; +} + u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags) { @@ -224,4 +282,209 @@ std::vector itemFindBlockOrder(const ItemFindArea& area) return blocks; } +std::optional buildStagedItemBlockChains(const std::vector& items) +{ + StagedItemBlockChains chains; + chains.heads.resize(0x1000); + chains.next.resize(0x2800); + std::vector seen(chains.next.size()); + for (const auto& item : items) { + if (item.itemNumber < 0x100 || item.itemNumber >= chains.next.size() || seen[item.itemNumber] || + item.data.x > 0x7fff || item.data.y > 0x7fff) { + return std::nullopt; + } + seen[item.itemNumber] = true; + const auto block = (item.data.x >> 9) * 0x40 + (item.data.y >> 9); + chains.next[item.itemNumber] = chains.heads[block]; + chains.heads[block] = item.itemNumber; + } + return chains; +} + +std::vector itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains) +{ + std::vector candidates; + for (const auto block : itemFindBlockOrder(area)) { + for (u16 itemNumber = chains.heads[block]; itemNumber != 0; itemNumber = chains.next[itemNumber]) { + candidates.push_back(itemNumber); + } + } + return candidates; +} + +namespace { + +std::optional> collectZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + u8 zMatchFlags, bool checkRectangle) +{ + if (origin.data.shape >= shapes.size()) { + return std::nullopt; + } + const auto chains = buildStagedItemBlockChains(items); + if (!chains) { + return std::nullopt; + } + std::vector byId(chains->next.size()); + for (const auto& item : items) { + if (item.data.shape >= shapes.size()) { + return std::nullopt; + } + byId[item.itemNumber] = &item; + } + std::vector matches; + const auto area = itemFindAreaAroundItem(origin, shapes[origin.data.shape]); + for (const auto itemNumber : itemFindCandidateOrder(area, *chains)) { + const auto& candidate = *byId[itemNumber]; + if (checkRectangle && (candidate.data.x < area.minX || candidate.data.x > area.maxX || + candidate.data.y < area.minY || candidate.data.y > area.maxY)) { + continue; + } + const auto matchType = classifyItemFindZMatch(origin, shapes[origin.data.shape], + candidate, shapes[candidate.data.shape], zMatchFlags); + if (matchType != 0) { + matches.push_back({itemNumber, matchType}); + } + } + return matches; +} + +} // namespace + +std::optional> itemFindZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, u8 zMatchFlags) +{ + return collectZMatches(origin, items, shapes, zMatchFlags, false); +} + +std::optional> itemGrabSearchCandidates(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes) +{ + return collectZMatches(origin, items, shapes, 3, true); +} + +std::optional> planItemGrabActions(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes) +{ + const auto candidates = itemGrabSearchCandidates(origin, items, shapes); + if (!candidates) { + return std::nullopt; + } + std::vector byId(0x2800); + for (const auto& item : items) { + byId[item.itemNumber] = &item; + } + std::vector actions; + for (const auto& candidate : *candidates) { + const auto& item = *byId[candidate.itemNumber]; + if (candidate.matchType == 1 && itemFallStartsHurl(shapes[item.data.shape])) { + actions.push_back({candidate.itemNumber, ItemGrabActionKind::Hurl}); + } else if (candidate.matchType == 2 && itemGrabCanCreateProcess(item)) { + actions.push_back({candidate.itemNumber, ItemGrabActionKind::CreateProcess}); + } + } + return actions; +} + +std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) +{ + const auto actions = planItemGrabActions(origin, items, shapes); + if (!actions) { + return std::nullopt; + } + for (const auto& action : *actions) { + if (action.itemNumber > ProcessKernel::maxTrackedItemNumber) { + return std::nullopt; + } + } + std::vector processIds; + for (const auto& action : *actions) { + if (action.kind == ItemGrabActionKind::Hurl) { + processIds.push_back(kernel.hurlItem(kernel.activeGroup(), action.itemNumber, 0, 0, 0, 2, + timerTick, groupCounts)); + } else { + auto* process = kernel.createItemProcess(kernel.activeGroup(), action.itemNumber, groupCounts); + processIds.push_back(static_cast(process->bytes[2] | (static_cast(process->bytes[3]) << 8))); + } + } + return processIds; +} + +LiveFixedMapItems::LiveFixedMapItems(std::vector items) : items_(std::move(items)) +{ + if (!buildStagedItemBlockChains(items_)) { + throw std::invalid_argument("invalid live item IDs or coordinates"); + } +} + +const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const +{ + for (const auto& item : items_) { + if (item.itemNumber == itemNumber) { + return &item; + } + } + return nullptr; +} + +std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, + s32 maxDistance) const +{ + return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance); +} + +bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) +{ + if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || + item.data.y > 0x7fff || findItem(item.itemNumber)) { + return false; + } + item.data.z = std::min(item.data.z, 0xfa); + items_.push_back(item); + return true; +} + +bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) +{ + if (x > 0x7fff || y > 0x7fff) { + return false; + } + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + item->data.x = x; + item->data.y = y; + item->data.z = std::min(z, 0xfa); + std::rotate(item, item + 1, items_.end()); + return true; +} + +std::optional> LiveFixedMapItems::grabItem(u16 itemNumber, + const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick) const +{ + const auto* origin = findItem(itemNumber); + return origin == nullptr ? std::nullopt : dispatchStagedItemGrab(*origin, items_, shapes, + kernel, groupCounts, timerTick); +} + +std::optional> LiveFixedMapItems::moveApprovedItem(u16 itemNumber, u16 x, u16 y, + u8 z, const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick) +{ + if (x > 0x7fff || y > 0x7fff || !findItem(itemNumber)) { + return std::nullopt; + } + auto processIds = grabItem(itemNumber, shapes, kernel, groupCounts, timerTick); + if (processIds) { + moveItem(itemNumber, x, y, z); + } + return processIds; +} + } // namespace remorse diff --git a/rebuild/remorse/src/main.cpp b/rebuild/remorse/src/main.cpp index a269199..2691154 100644 --- a/rebuild/remorse/src/main.cpp +++ b/rebuild/remorse/src/main.cpp @@ -77,6 +77,8 @@ int main(int argc, char** argv) std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n'; if (gameDataRoot) { std::optional firstStagedItem; + std::optional stagedBlockChains; + std::optional> stagedMapItems; const auto palettePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); const auto paletteBytes = palettePath ? remorse::readBinaryFile(*palettePath) : std::nullopt; std::cout << "GAMEPAL.PAL bytes: " << (paletteBytes ? paletteBytes->size() : 0) << '\n'; @@ -101,6 +103,8 @@ int main(int argc, char** argv) const auto items = remorse::stageFixedMapItems(*map); if (items && !items->empty()) { firstStagedItem = items->front(); + stagedBlockChains = remorse::buildStagedItemBlockChains(*items); + stagedMapItems = *items; struct ItemScanContext { remorse::ProcessKernel* kernel; remorse::u16 (*groups)[32]; @@ -141,6 +145,23 @@ int main(int argc, char** argv) const auto area = remorse::itemFindAreaAroundItem( *firstStagedItem, (*typeFlags)[firstStagedItem->data.shape]); std::cout << "Staged item ItemFind blocks: " << remorse::itemFindBlockOrder(area).size() << '\n'; + if (stagedBlockChains) { + std::cout << "Staged item ItemFind candidates: " << + remorse::itemFindCandidateOrder(area, *stagedBlockChains).size() << '\n'; + } + if (stagedMapItems) { + const auto matches = remorse::itemFindZMatches(*firstStagedItem, *stagedMapItems, *typeFlags, 3); + std::cout << "Staged item ItemFind Z matches (script-free): " << + (matches ? matches->size() : 0) << '\n'; + const auto grabCandidates = remorse::itemGrabSearchCandidates( + *firstStagedItem, *stagedMapItems, *typeFlags); + const auto grabActions = remorse::planItemGrabActions( + *firstStagedItem, *stagedMapItems, *typeFlags); + std::cout << "Staged item Item_Grab candidates: " << + (grabCandidates ? grabCandidates->size() : 0) << '\n'; + std::cout << "Staged item Item_Grab planned actions: " << + (grabActions ? grabActions->size() : 0) << '\n'; + } } const auto usecodePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("USECODE") / "EUSECODE.FLX"); diff --git a/rebuild/remorse/src/type_flags.cpp b/rebuild/remorse/src/type_flags.cpp index abe64fd..853a234 100644 --- a/rebuild/remorse/src/type_flags.cpp +++ b/rebuild/remorse/src/type_flags.cpp @@ -29,6 +29,7 @@ std::optional> loadTypeFlags(const std::filesystem::p info.y = static_cast((byte3 >> 2) & 0x1f); info.z = static_cast(((byte4 << 1) | (byte3 >> 7)) & 0x1f); info.animationType = static_cast(byte4 >> 4); + info.weight = (*bytes)[offset + 7]; infos.push_back(info); } diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index c3ba213..becb72f 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -47,7 +47,7 @@ struct AppState { remorse::u16 diagnosticGroupCounts[32]{}; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; - std::vector stagedItems; + std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; @@ -281,7 +281,7 @@ void loadSceneAsync(HWND window, AppState& state) state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; if (stagedItems) { - state.stagedItems = std::move(*stagedItems); + state.liveItems.emplace(std::move(*stagedItems)); } state.sceneLoaded = true; } @@ -557,8 +557,8 @@ void paintWindow(HWND window, AppState& state) RECT diagnosticsBounds{20, 30, viewWidth - 12, 54}; SetTextColor(device, RGB(74, 207, 184)); DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto nearbyItem = remorse::nearestStagedFixedMapItem( - state.stagedItems, state.playerWorld.x, state.playerWorld.y, diagnosticItemRange); + const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem( + state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; std::wostringstream itemStatus; @@ -729,8 +729,8 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { - state->diagnosticItem = remorse::nearestStagedFixedMapItem( - state->stagedItems, state->playerWorld.x, state->playerWorld.y, diagnosticItemRange); + state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( + state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt; } if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp index d8fe5c7..b3b06e6 100644 --- a/rebuild/remorse/tests/collision_tests.cpp +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -4,6 +4,24 @@ int main() { + 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 && + outsideBounds.failed); + const auto belowFloor = remorse::clampAreaSweepBounds({10, 20, 10}, {10, 20, -3}); + assert(belowFloor.destination.z == 0 && belowFloor.failedDirections == 4 && !belowFloor.failed); + const auto withinBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {12, 23, 11}); + assert(withinBounds.failedDirections == 0 && !withinBounds.failed); + const auto gravityStep = remorse::planGravitySweep({100, 200, 250}, 3, -2, 4, 2, 3); + assert(gravityStep.destination.x == 109 && gravityStep.destination.y == 194); + assert(gravityStep.destination.z == 6 && gravityStep.nextZSpeed == -2); + const auto slowStep = remorse::planGravitySweep({100, 200, 0}, 3, -2, -4, 2, 0); + assert(slowStep.destination.x == 103 && slowStep.destination.y == 198); + assert(slowStep.destination.z == 252 && slowStep.nextZSpeed == -6); + const auto cappedStep = remorse::planGravitySweep({100, 200, 0}, 3, -2, 4, 2, 5); + assert(cappedStep.destination.x == 112 && cappedStep.destination.y == 192); + assert(cappedStep.destination.z == 16 && cappedStep.nextZSpeed == -4); + const remorse::CollisionBody actor{{100, 100, 0}, 96, 96, 80}; const remorse::CollisionBody wall{{300, 100, 0}, 64, 96, 128}; assert(!remorse::collisionBodiesOverlap(actor, wall)); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 0e24243..0978576 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,4 +1,7 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/fixed_map.h" +#include "remorse/map_renderer.h" +#include "remorse/type_flags.h" #include #include @@ -285,6 +288,33 @@ int main() assert(spawnContext.runs == 1 && spawnContext.spawned == spawningKernel.processAt(2)); assert(spawningProcess->bytes[0x18] == 0x07 && spawnContext.spawned->bytes[0x16] == 0); + remorse::ProcessKernel itemSpawnKernel; + remorse::u16 itemSpawnGroups[32]{}; + for (int index = 0; index < 3; ++index) { + itemSpawnKernel.createProcess(1, itemSpawnGroups); + } + auto* itemSpawner = itemSpawnKernel.createProcess(2, itemSpawnGroups); + itemSpawner->bytes[0x18] |= 0x02; + struct ItemSpawnContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::EntityDispatchEntryBase* spawned = nullptr; + int spawnedRuns = 0; + } itemSpawnContext{&itemSpawnKernel, &itemSpawnGroups}; + auto spawnItemRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& state = *static_cast(context); + if (process.bytes[0] == remorse::ItemProcess::vtableOffset % 256) { + ++state.spawnedRuns; + } else if (state.spawned == nullptr && process.bytes[2] == 3) { + state.spawned = state.kernel->createItemProcess(2, 0x100, *state.groups); + } + }; + itemSpawnKernel.scanRunnableProcesses(2, spawnItemRun, &itemSpawnContext); + assert(itemSpawnContext.spawned && itemSpawnContext.spawnedRuns == 0 && + (itemSpawnContext.spawned->bytes[0x16] & 0x40) == 0); + itemSpawnKernel.scanRunnableProcesses(2, spawnItemRun, &itemSpawnContext); + assert(itemSpawnContext.spawnedRuns == 1); + remorse::ProcessKernel retiringKernel; remorse::u16 retiringGroups[32]{}; for (int index = 0; index < 3; ++index) { @@ -372,7 +402,11 @@ int main() assert(itemProcess->bytes[6] == 0xf1 && itemProcess->bytes[7] == 0); assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemProcessTypes(0x100) == 2); assert(cachedItemGroups[1] == 4); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == itemProcess); + assert(cachedItemKernel.findProcessForItemAndType(0, 0x0c) == itemProcess); + assert(cachedItemKernel.findProcessForItemAndType(0x101, 0xf1) == nullptr); auto* sharedItemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == itemProcess); assert(cachedItemKernel.itemProcessTypes(0x100) == 2); cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x101); assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemHasProcess(0x101)); @@ -422,6 +456,7 @@ int main() } }, &itemRunContext); assert(releasedItem == 0x100 && !cachedItemKernel.itemHasProcess(0x100)); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == nullptr); assert(cachedItemKernel.itemProcessTypes(0x100) == 0); assert(cachedItemKernel.processAt(3) == nullptr && cachedItemGroups[1] == 3); bool itemTeardownRejected = false; @@ -431,6 +466,143 @@ int main() itemTeardownRejected = true; } assert(itemTeardownRejected && standGroups[2] == 2 && standKernel.processAt(1) == standing); + remorse::ProcessKernel gravityKernel; + remorse::u16 gravityGroups[32]{}; + for (int index = 0; index < 3; ++index) { + gravityKernel.createProcess(1, gravityGroups); + } + const auto gravityId = gravityKernel.hurlItem(1, 0x100, 2, -3, 4, 2, 10, gravityGroups); + auto* gravityEntry = gravityKernel.processAt(gravityId); + assert(gravityEntry && gravityKernel.allocationSizeAt(gravityId) == 0x42); + assert(std::strcmp(gravityKernel.processNameAt(gravityId), "Gravity") == 0); + assert(gravityKernel.findProcessForItemAndType(0x100, 0x203) == gravityEntry); + assert(gravityEntry->bytes[0] == 0x10 && gravityEntry->bytes[1] == 0x06); + assert(gravityEntry->bytes[0x32] == 2 && gravityEntry->bytes[0x34] == 0xfd && + gravityEntry->bytes[0x35] == 0xff && gravityEntry->bytes[0x36] == 4); + assert(gravityEntry->bytes[0x38] == 2 && gravityEntry->bytes[0x3b] == 200); + assert((gravityEntry->bytes[0x19] & 0x10) != 0 && gravityEntry->bytes[0x0a] == 10 && + gravityEntry->bytes[0x0e] == 20 && gravityGroups[1] == 4); + assert(gravityKernel.hurlItem(1, 0x100, -4, 5, -2, 99, 11, gravityGroups) == gravityId); + assert(gravityEntry->bytes[0x32] == 0xfe && gravityEntry->bytes[0x33] == 0xff && + gravityEntry->bytes[0x34] == 2 && gravityEntry->bytes[0x36] == 2 && + gravityEntry->bytes[0x38] == 2 && gravityGroups[1] == 4); + bool invalidHurlRejected = false; + try { + gravityKernel.hurlItem(1, 0x2400, 0, 0, 0, 2, 10, gravityGroups); + } catch (const std::out_of_range&) { + invalidHurlRejected = true; + } + assert(invalidHurlRejected && gravityGroups[1] == 4); + int gravityRuns = 0; + auto countGravityRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + if (process.bytes[0] == 0x10 && process.bytes[1] == 0x06) { + ++*static_cast(context); + } + }; + gravityKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 30); + assert(gravityRuns == 0); + gravityKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 31); + assert(gravityRuns == 1 && gravityKernel.itemHasProcess(0x100)); + remorse::StagedFixedMapItem fallingItem{}; + fallingItem.itemNumber = 0x100; + fallingItem.data.x = 100; + fallingItem.data.y = 100; + fallingItem.data.z = 10; + remorse::LiveFixedMapItems fallingItems({fallingItem}); + auto approveGravity = [](remorse::u16 itemNumber, const remorse::WorldPoint& from, + const remorse::WorldPoint& to, void* context) { + ++*static_cast(context); + return itemNumber == 0x100 && from.x == 100 && from.y == 100 && from.z == 10 && + to.x == 98 && to.y == 102 && to.z == 12; + }; + int sweepCalls = 0; + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, nullptr, nullptr)); + assert(sweepCalls == 0 && fallingItems.findItem(0x100)->data.x == 100); + auto rejectGravity = [](remorse::u16, const remorse::WorldPoint&, const remorse::WorldPoint&, + void* context) { + ++*static_cast(context); + return false; + }; + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, + rejectGravity, &sweepCalls)); + assert(sweepCalls == 1 && fallingItems.findItem(0x100)->data.x == 100 && + gravityEntry->bytes[0x36] == 2 && (gravityEntry->bytes[0x19] & 0x10) == 0); + assert(gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, + approveGravity, &sweepCalls)); + assert(sweepCalls == 2 && fallingItems.findItem(0x100)->data.x == 98 && + fallingItems.findItem(0x100)->data.y == 102 && fallingItems.findItem(0x100)->data.z == 12); + assert(gravityEntry->bytes[0x36] == 0 && gravityEntry->bytes[0x37] == 0 && + (gravityEntry->bytes[0x19] & 0x10) != 0 && gravityEntry->bytes[0x0e] == 4); + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 32, + approveGravity, &sweepCalls) && sweepCalls == 2); + remorse::ProcessKernel horizontalKernel; + remorse::u16 horizontalGroups[32]{}; + for (int index = 0; index < 3; ++index) { + horizontalKernel.createProcess(1, horizontalGroups); + } + const auto horizontalId = horizontalKernel.hurlItem(1, 0x100, 2, 0, 0, 2, 0, horizontalGroups); + remorse::StagedFixedMapItem supportedItem = fallingItem; + supportedItem.data.shape = 1; + supportedItem.data.z = 72; + supportedItem.itemNumber = 0x101; + fallingItem.data.shape = 1; + fallingItem.data.z = 80; + remorse::LiveFixedMapItems horizontalItems({fallingItem, supportedItem}); + std::vector horizontalShapes(2); + horizontalShapes[1].x = 1; + horizontalShapes[1].y = 1; + horizontalShapes[1].z = 1; + horizontalKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 21); + struct HorizontalSweep { + remorse::ProcessKernel* kernel; + int calls = 0; + } horizontalSweep{&horizontalKernel}; + auto approveHorizontal = [](remorse::u16 itemNumber, const remorse::WorldPoint& from, + const remorse::WorldPoint& to, void* context) { + auto& state = *static_cast(context); + ++state.calls; + return itemNumber == 0x100 && from.x == 100 && from.z == 80 && to.x == 102 && + to.z == 80 && state.kernel->findProcessForItemAndType(0x101, 0xf1) != nullptr; + }; + assert(!horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + approveHorizontal, &horizontalSweep)); + assert(horizontalSweep.calls == 0 && horizontalKernel.processCount() == 4); + auto rejectHorizontal = [](remorse::u16, const remorse::WorldPoint&, + const remorse::WorldPoint&, void* context) { + ++static_cast(context)->calls; + return false; + }; + assert(!horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + rejectHorizontal, &horizontalSweep, &horizontalShapes, &horizontalGroups)); + assert(horizontalSweep.calls == 1 && horizontalItems.findItem(0x100)->data.x == 100 && + horizontalKernel.findProcessForItemAndType(0x101, 0xf1) != nullptr && + horizontalKernel.processCount() == 5); + assert(horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + approveHorizontal, &horizontalSweep, &horizontalShapes, &horizontalGroups)); + assert(horizontalSweep.calls == 2 && horizontalItems.findItem(0x100)->data.x == 102 && + horizontalKernel.processCount() == 6); + assert(horizontalKernel.processAt(horizontalId)->bytes[0x36] == 0xfe && + horizontalKernel.processAt(horizontalId)->bytes[0x37] == 0xff); + gravityKernel.terminateProcess(gravityId, gravityGroups); + assert(gravityKernel.findProcessForItemAndType(0x100, 0x203) == nullptr); + gravityKernel.clearTerminatedProcesses(); + assert(gravityKernel.processAt(gravityId) == nullptr && !gravityKernel.itemHasProcess(0x100)); + assert(gravityKernel.hurlItem(1, 0x100, 0, 0, 0, 2, 31, gravityGroups) == gravityId); + remorse::ProcessKernel externalGravityKernel; + remorse::u16 externalGravityGroups[32]{}; + for (int index = 0; index < 3; ++index) { + externalGravityKernel.createProcess(1, externalGravityGroups); + } + auto* externalGravity = externalGravityKernel.createProcess(1, externalGravityGroups); + externalGravityKernel.setProcessSourceType(*externalGravity, 0x101); + externalGravityKernel.setProcessEventTypeChecked(*externalGravity, 0x203); + bool unownedGravityRejected = false; + try { + externalGravityKernel.hurlItem(1, 0x101, 1, 0, 0, 2, 0, externalGravityGroups); + } catch (const std::logic_error&) { + unownedGravityRejected = true; + } + assert(unownedGravityRejected && externalGravityGroups[1] == 4); struct StandContext { remorse::u32 tick; bool visible; diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 37f5f37..5a043da 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -42,6 +42,8 @@ int main() const auto typeFlagPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt; assert(typeFlags && cachedItems->front().data.shape < typeFlags->size()); + const auto retailContained = remorse::stageContainedFixedMapItems(*retailMap, *typeFlags); + assert(retailContained && retailContained->empty()); const auto& originShape = (*typeFlags)[cachedItems->front().data.shape]; auto origin = cachedItems->front(); origin.data.z = 80; @@ -49,6 +51,12 @@ int main() candidate.itemNumber = static_cast(origin.itemNumber + 1); candidate.data.z = static_cast(origin.data.z + (originShape.z == 0 && (originShape.flags & 1) == 0 ? 1 : originShape.z * 8)); remorse::ShapeTypeInfo footprint{0, 0, 1, 1, 0, 0}; + assert(!remorse::itemFallStartsHurl(footprint)); + footprint.weight = 2; + assert(remorse::itemFallStartsHurl(footprint)); + footprint.flags = 1; + assert(!remorse::itemFallStartsHurl(footprint)); + footprint.flags = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 1); assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 2) == 0); candidate.data.z = 79; @@ -62,6 +70,23 @@ int main() const auto retailSearchBlocks = remorse::itemFindBlockOrder(retailSearchArea); assert(!retailSearchBlocks.empty() && retailSearchBlocks.front() == (retailSearchArea.minX >> 9) * 0x40 + (retailSearchArea.minY >> 9)); + const auto retailChains = remorse::buildStagedItemBlockChains(*cachedItems); + assert(retailChains); + const auto retailCandidates = remorse::itemFindCandidateOrder(retailSearchArea, *retailChains); + std::size_t stagedItemsInAreaBlocks = 0; + for (const auto& item : *cachedItems) { + const auto block = (item.data.x >> 9) * 0x40 + (item.data.y >> 9); + for (const auto searchBlock : retailSearchBlocks) { + if (block == searchBlock) { + ++stagedItemsInAreaBlocks; + } + } + } + assert(!retailCandidates.empty() && retailCandidates.size() == stagedItemsInAreaBlocks); + const auto retailGrabCandidates = remorse::itemGrabSearchCandidates(cachedItems->front(), *cachedItems, *typeFlags); + const auto retailGrabActions = remorse::planItemGrabActions(cachedItems->front(), *cachedItems, *typeFlags); + assert(retailGrabCandidates && retailGrabCandidates->size() == 1); + assert(retailGrabActions && retailGrabActions->empty()); origin.data.x = 511; origin.data.y = 511; const auto crossingArea = remorse::itemFindAreaAroundItem(origin, footprint); @@ -73,9 +98,163 @@ int main() const auto edgeArea = remorse::itemFindAreaAroundItem(origin, footprint); assert(edgeArea.minX == 0 && edgeArea.minY == 0); assert((remorse::itemFindBlockOrder(edgeArea) == std::vector{0})); + std::vector blockItems(4); + blockItems[0].itemNumber = 0x100; + blockItems[0].data.x = 511; + blockItems[0].data.y = 511; + blockItems[1].itemNumber = 0x102; + blockItems[1].data.x = 512; + blockItems[1].data.y = 511; + blockItems[2].itemNumber = 0x103; + blockItems[2].data.x = 511; + blockItems[2].data.y = 511; + blockItems[3].itemNumber = 0x104; + blockItems[3].data.x = 512; + blockItems[3].data.y = 512; + const auto chains = remorse::buildStagedItemBlockChains(blockItems); + assert(chains && chains->heads[0] == 0x103 && chains->next[0x103] == 0x100); + assert((remorse::itemFindCandidateOrder(crossingArea, *chains) == + std::vector{0x103, 0x100, 0x102, 0x104})); + blockItems[3].itemNumber = 0x103; + assert(!remorse::buildStagedItemBlockChains(blockItems)); + blockItems[3].itemNumber = 0x104; + blockItems[3].data.x = 0x8000; + assert(!remorse::buildStagedItemBlockChains(blockItems)); + blockItems[3].data.x = 512; + std::vector searchShapes(2, footprint); + auto searchOrigin = origin; + searchOrigin.itemNumber = 0x105; + searchOrigin.data.x = 511; + searchOrigin.data.y = 511; + searchOrigin.data.z = 80; + searchOrigin.data.shape = 1; + for (auto& item : blockItems) { + item.data.shape = 1; + } + blockItems[0].data.z = 81; + blockItems[1].data.z = 0; + blockItems[2].data.z = 79; + blockItems[3].data.z = 81; + blockItems.push_back(searchOrigin); + const auto zMatches = remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 3); + assert(zMatches && zMatches->size() == 3); + assert((*zMatches)[0].itemNumber == 0x103 && (*zMatches)[0].matchType == 2); + assert((*zMatches)[1].itemNumber == 0x100 && (*zMatches)[1].matchType == 1); + assert((*zMatches)[2].itemNumber == 0x104 && (*zMatches)[2].matchType == 1); + const auto topMatches = remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 1); + assert(topMatches && topMatches->size() == 2); + blockItems[3].data.x = 768; + searchShapes[1].x = 17; + assert(remorse::classifyItemFindZMatch(searchOrigin, searchShapes[1], + blockItems[3], searchShapes[1], 1) == 1); + const auto grabCandidates = remorse::itemGrabSearchCandidates(searchOrigin, blockItems, searchShapes); + assert(grabCandidates && grabCandidates->size() == 2); + assert((*grabCandidates)[0].itemNumber == 0x103 && (*grabCandidates)[0].matchType == 2); + assert((*grabCandidates)[1].itemNumber == 0x100 && (*grabCandidates)[1].matchType == 1); + const auto grabActions = remorse::planItemGrabActions(searchOrigin, blockItems, searchShapes); + assert(grabActions && grabActions->size() == 2); + assert((*grabActions)[0].itemNumber == 0x103 && + (*grabActions)[0].kind == remorse::ItemGrabActionKind::CreateProcess); + assert((*grabActions)[1].itemNumber == 0x100 && + (*grabActions)[1].kind == remorse::ItemGrabActionKind::Hurl); + remorse::ProcessKernel grabKernel; + remorse::u16 grabGroups[32]{}; + for (int index = 0; index < 3; ++index) { + grabKernel.createProcess(1, grabGroups); + } + const auto dispatched = remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 12); + assert(dispatched && dispatched->size() == 2 && (*dispatched)[0] == 3 && (*dispatched)[1] == 4); + assert(grabKernel.findProcessForItemAndType(0x103, 0xf1) == grabKernel.processAt(3)); + assert(grabKernel.findProcessForItemAndType(0x100, 0x203) == grabKernel.processAt(4)); + const auto repeated = remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 13); + assert(repeated && repeated->size() == 2 && (*repeated)[0] == 5 && (*repeated)[1] == 4); + assert(grabGroups[1] == 6); + remorse::LiveFixedMapItems liveItems(blockItems); + remorse::ProcessKernel liveKernel; + remorse::u16 liveGroups[32]{}; + for (int index = 0; index < 3; ++index) { + liveKernel.createProcess(1, liveGroups); + } + assert(!liveItems.findItem(0x106) && !liveItems.moveItem(0x106, 0, 0, 0)); + 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); + 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)); + const auto liveDispatched = liveItems.grabItem(0x105, searchShapes, liveKernel, liveGroups, 14); + assert(liveDispatched && liveDispatched->size() == 1 && (*liveDispatched)[0] == 3); + assert(liveKernel.findProcessForItemAndType(0x103, 0xf1) == liveKernel.processAt(3)); + assert(liveKernel.findProcessForItemAndType(0x100, 0x203) == nullptr); + assert(liveItems.moveItem(0x100, 768, 511, 255)); + assert(liveItems.findItem(0x100)->data.z == 250); + remorse::LiveFixedMapItems reorderedItems(blockItems); + remorse::ProcessKernel reorderedKernel; + remorse::u16 reorderedGroups[32]{}; + for (int index = 0; index < 3; ++index) { + reorderedKernel.createProcess(1, reorderedGroups); + } + assert(reorderedItems.moveItem(0x100, 511, 511, 81)); + const auto reorderedGrab = reorderedItems.grabItem(0x105, searchShapes, + reorderedKernel, reorderedGroups, 14); + assert(reorderedGrab && reorderedGrab->size() == 2 && (*reorderedGrab)[0] == 3 && + (*reorderedGrab)[1] == 4); + assert(reorderedKernel.findProcessForItemAndType(0x100, 0x203) == reorderedKernel.processAt(3)); + assert(reorderedKernel.findProcessForItemAndType(0x103, 0xf1) == reorderedKernel.processAt(4)); + remorse::LiveFixedMapItems insertedItems(blockItems); + remorse::StagedFixedMapItem newItem = blockItems[2]; + newItem.itemNumber = 0x106; + assert(!insertedItems.insertItem(blockItems[2])); + newItem.data.x = 0x8000; + assert(!insertedItems.insertItem(newItem)); + newItem.data.x = 511; + assert(insertedItems.insertItem(newItem)); + assert(insertedItems.findItem(0x106)->data.x == 511); + remorse::ProcessKernel insertedKernel; + remorse::u16 insertedGroups[32]{}; + for (int index = 0; index < 3; ++index) { + insertedKernel.createProcess(1, insertedGroups); + } + const auto insertedGrab = insertedItems.grabItem(0x105, searchShapes, + insertedKernel, insertedGroups, 14); + assert(insertedGrab && insertedGrab->size() == 3 && (*insertedGrab)[0] == 3); + assert(insertedKernel.findProcessForItemAndType(0x106, 0xf1) == insertedKernel.processAt(3)); + remorse::LiveFixedMapItems movingItems(blockItems); + remorse::ProcessKernel movingKernel; + remorse::u16 movingGroups[32]{}; + for (int index = 0; index < 3; ++index) { + movingKernel.createProcess(1, movingGroups); + } + const auto rejectedMove = movingItems.moveApprovedItem(0x105, 0x8000, 0, 0, + searchShapes, movingKernel, movingGroups, 14); + assert(!rejectedMove && movingItems.findItem(0x105)->data.x == 511 && movingKernel.processCount() == 3); + const auto approvedMove = movingItems.moveApprovedItem(0x105, 768, 768, 80, + searchShapes, movingKernel, movingGroups, 14); + assert(approvedMove && approvedMove->size() == 2 && (*approvedMove)[0] == 3 && (*approvedMove)[1] == 4); + assert(movingItems.findItem(0x105)->data.x == 768 && movingItems.findItem(0x105)->data.y == 768); + const auto afterMoveGrab = movingItems.grabItem(0x105, searchShapes, movingKernel, movingGroups, 15); + assert(afterMoveGrab && afterMoveGrab->empty()); + blockItems[0].itemNumber = 0x2400; + const auto priorProcessCount = grabKernel.processCount(); + assert(!remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 14)); + assert(grabKernel.processCount() == priorProcessCount); + blockItems[0].itemNumber = 0x100; + blockItems[2].data.flags |= 2; + searchShapes[1].weight = 0; + const auto blockedActions = remorse::planItemGrabActions(searchOrigin, blockItems, searchShapes); + assert(blockedActions && blockedActions->empty()); + searchShapes[1].x = 1; + searchOrigin.data.shape = 2; + assert(!remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 3)); candidate.itemNumber = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); assert(cachedItems->front().recordIndex < retailMap->entries.size()); + const remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + assert(retailLiveItems.findItem(cachedItems->front().itemNumber)->recordIndex == + cachedItems->front().recordIndex); for (const auto& item : *cachedItems) { const auto& record = retailMap->entries[item.recordIndex]; assert(record.shape != 0 && (record.flags & 8) == 0); @@ -128,6 +307,27 @@ int main() assert((*stagedItems)[0].recordIndex == 1 && (*stagedItems)[0].itemNumber == 0x100); assert((*stagedItems)[1].recordIndex == 3 && (*stagedItems)[1].itemNumber == 0x102); assert((*stagedItems)[1].data.flags == 0); + remorse::FixedMap containedMap; + containedMap.index = 1; + containedMap.entries.resize(5); + for (auto& record : containedMap.entries) { + record.shape = 1; + } + containedMap.entries[1].flags = 8; + containedMap.entries[1].x = 2; + containedMap.entries[2].flags = 8; + containedMap.entries[2].x = 4; + containedMap.entries[3].flags = 8; + containedMap.entries[3].x = 2; + std::vector containerShapes(2); + containerShapes[1].family = 6; + const auto contained = remorse::stageContainedFixedMapItems(containedMap, containerShapes); + assert(contained && contained->size() == 3); + 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); + containerShapes[1].family = 0; + assert(!remorse::stageContainedFixedMapItems(containedMap, containerShapes)); assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0])); (*stagedItems)[0].data.flags |= 0x02; assert(!remorse::itemGrabCanCreateProcess((*stagedItems)[0])); diff --git a/rebuild/remorse/tests/type_flags_tests.cpp b/rebuild/remorse/tests/type_flags_tests.cpp index 10cc562..ae30680 100644 --- a/rebuild/remorse/tests/type_flags_tests.cpp +++ b/rebuild/remorse/tests/type_flags_tests.cpp @@ -15,6 +15,11 @@ int main() const auto infos = remorse::loadTypeFlags(*typeFlagPath); assert(infos.has_value()); assert(infos->size() == 2048); + const auto bytes = remorse::readBinaryFile(*typeFlagPath); + assert(bytes && bytes->size() == infos->size() * 9); + for (std::size_t index = 0; index < infos->size(); ++index) { + assert((*infos)[index].weight == (*bytes)[index * 9 + 7]); + } bool foundGlobFamily = false; for (const remorse::ShapeTypeInfo& info : *infos) {