Add comprehensive tests for entity dispatch, file system, fixed map, flex archive, isometric controls, and crash setup

- Enhance `entity_dispatch_entry_tests.cpp` with additional assertions for event type checks, group ID increments, and error handling.
- Refactor `file_system_tests.cpp` to streamline probe execution and enhance output validation.
- Extend `fixed_map_tests.cpp` to cover retail map loading, item classification, and process creation scenarios.
- Introduce new checks in `flex_archive_tests.cpp` for usecode loading and event handling, ensuring robust validation of game data.
- Add tests in `isometric_controls_tests.cpp` for controller direction mapping based on scan codes.
- Implement `test_crash_setup.cpp` to initialize crash diagnostics for improved error handling during tests.
This commit is contained in:
Maddo 2026-09-26 15:36:11 +02:00
commit c346b0e1a7
17 changed files with 1207 additions and 92 deletions

View file

@ -2,9 +2,9 @@
## Purpose
This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and eventually run on Windows, including modern Windows.
This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and run on modern hosts. Windows is the current development and acceptance target, not the only intended platform: keep recovered game logic and data formats host-independent, isolate Win32 presentation and diagnostics behind replaceable platform boundaries, and plan a portable window/input/timing/audio host when the original runtime call chains require it. Other platforms are a future goal, not a claim of current support.
The deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion.
The first deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code, with a path to multi-platform builds. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion.
The exported files are evidence, not directly compilable game source. Keep them unchanged and move verified, subsystem-sized function bodies into the rebuild tree, recording each original address and any corrections to decompiler artifacts. Do not substitute a newly designed gameplay implementation for an unported function and call that function complete.
@ -50,7 +50,7 @@ Current scaffold files:
- `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder.
- `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries.
- `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them.
- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), and a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`). The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, keyboard lane, and complete game tick remain unported.
- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported.
- `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`.
- `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives.
- `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates.
@ -78,7 +78,7 @@ Current scaffold files:
- `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records.
- `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review.
This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, timer interrupt registration, or game loop.
This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan/group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop.
## Why The Export Does Not Compile Yet
@ -282,13 +282,15 @@ Exit criteria: a clean checkout/build can run against a retail data directory wi
The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic.
First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. `IncrementGroupId`, `SetSourceType`, and `SetEventTypeChecked` remain stand-ins; runtime binary parity is not established.
First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. Kernel-owned source/type transitions and active-group increment now have focused coverage, but the static source/type setters still lack item-cache context; runtime binary parity is not established.
### Process Source-Port Ledger
| Exported function | Compiled status | Evidence and remaining boundary |
|---|---|---|
| `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. |
| `IncrementGroupId@11e0_0405.c` | Group increment, current-active-group assertion, and 29-to-30 rejection translated; harness and CTest invoke it | Live `11e0:040b-0466` masks the group byte to five bits, checks next group `< 30` and `DS:39c9 == old group`, then calls `SetGroupId` and `Kernel_11d0_19b5`. The host passes the owning kernel and group counts explicitly; assertions become exceptions, without a DOS runtime trace. |
| `SetSourceType@11e0_01b6.c`, `SetEventTypeChecked@11e0_0227.c` | Kernel-owned item source and event-type transitions compiled and exercised by the item-process constructor, CTest reassignment/teardown | Source change stamps `+0x04`, marks the new item's presence bit, refreshes the old bit by searching unterminated processes from slot 3, and moves the type bit when `+0x06` is `0xf0..0xf7`. Type change stamps `+0x06`, sets the new type bit and refreshes the old type; values above `0x0fff` assert after the write. Per-item presence bits (`DS:3a04`) and per-item process-type bytes (`DS:3a08`) are separate host-owned tables. Static setters without kernel context remain partial; other item-cache mutations and binary parity are unverified. |
| `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. |
| `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. |
| `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. |
@ -296,15 +298,38 @@ First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a
| `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. |
| `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. |
| `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. |
| `Kernel_11d0_19b5` (`11d0:19b5`), `Kernel_11d0_0445` (`11d0:0445`) | Active-group writer and empty-group highest-ordinary-group selection translated; invoked after diagnostic scans in harness/window, CTest checks change flag and groups 30/31 exclusion | Exported globals initialize active group `DS:39c9` to 1 and pending byte `DS:39a2` to 0. Writer marks pending only when group changes; selector scans all occupied process slots (including terminated entries until cleanup), ignores groups 30/31 for the maximum, then clears pending. Host rejects invalid group IDs and uses explicit group counters; original group-table allocation, mid-scan early stop, and runtime traces remain unported. |
| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release-request/termination/presence cleanup checked over two ticks, harness/window invoke the same path | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The compiled release boundary now passes mask `0x200` and `UC_Release` ordinal `9` to the host callback, both asserted by CTest. It still does not execute the USECODE event. Instance is a diagnostic, not an original `Item_Grab` trigger; original item process child teardown and general vtable dispatch remain unported. |
| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness and window release-request lookup | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The window retains TYPEFLAG families and EUSECODE data to check release eligibility and report body availability, without creating a VM context or executing the body. Classless map items are normal; the first staged map-1 item (shape 16) has no matching class. |
| `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. |
| `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. |
| `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. |
| `SystemTimerProcess_CreateProcess` (`11c0:0000`), `Process_RegisterForTimerEvents` (`11e0:19ba`), `Kernel_RegisterProcForTimerEvents` (`11d0:2dd8`), `SystemTimerProcess_Increment` (`11c0:00f8`) | Partial 0x4a-byte owned constructor and registered counter linked to harness and Windows diagnostic scheduler; zero initialization, 16-bit carry, uniqueness, process flags, registration gate, and strict Stand wake boundary tested | Exported `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) sets interrupt/realtime flags and zeros the periodic tail; constructor stores period `0x3c` at `+0x36`, tail bit `2` at `+0x32`, and waiting/daemon/active-counter flags. Registration sets `Proc_GetTimerEvents` (`0x400`) and records the process ID; host delivery requires both. Increment carries from `+0x40` to `+0x42`. Original randomized reschedule, event type, active-counter globals, general timer list/dispatch, DOS interrupt source, and general timer teardown remain unported. |
| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, `KeyDaemon`, event queue, modifier state, and player-input routing remain unported. |
| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, key event queue, modifier state, and player-input routing remain unported. |
| `KeyDaemon_CreateProcess` (`11b8:0000`) | Partial owned 0x40-byte constructor invoked after keyboard registration in harness and window; layout, singleton, and teardown refusal tested | Inherits `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) interrupt/realtime flags `0x300`, sets `Proc_Daemon|Proc_Waiting` (`0x3`), `Proc_ImmediateTimer` (`0x2000`), timer-event bit `0x400`, derived tail `+0x32 |= 2`, and period `0x2d` at `+0x36`. The randomized schedule, timer list dispatch, held-key repeat callback, and DOS input state are not linked. |
Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, scheduler gates, and call order, not runtime state parity. Do not promote the Stand harness trace to gameplay behavior until its host-supplied NPC services and remaining tick services can be checked against execution.
`Kernel_InitProcessTables` (`11d0:1aae`) allocates and clears the separate `DS:3a04` presence bitmap (`0x480` bytes) and `DS:3a08` process-type bytes (`0x2400` bytes), as confirmed in the live NE decompilation. These lookup tables index item IDs through `0x23ff`, even though the item cache initialized by `ItemCache_InitAndLoadFixedDat` (`10a8:163a`) has a wider free-item range. The host kernel now rejects source/NPC item IDs above the lookup-table limit before changing process state; the Windows diagnostic reports an out-of-range candidate rather than queuing it. This is a bound for the modeled process tables, not an assertion that the whole item cache stops there. Tests cover `0x23ff` and `0x2400`. `Kernel_Init` (`11d0:000c`) calls the table initializer before registering timer and keyboard processes, but its DOS interrupt, real-segment, and mouse setup remain unported.
The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, and a staged synthetic map reaches that ID; retail map 1 remains inside the kernel lookup limit. Exported `SetSourceType` (`11e0:01b6`) calls the presence/type-table writers without a visible range guard. This does not prove how a live run handles such an ID: preserve the host guard and investigate the original allocation/use path before allowing out-of-range process ownership.
`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 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.
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.
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
`rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255.
@ -321,11 +346,23 @@ The application builds the selected retail map scene and player assets on a work
The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate.
The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input.
The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. Win32 supplies modifier bits; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions.
### First Map-Derived Item/Process Tick
On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. Debug CRT assertions do not open Abort/Retry/Ignore windows; the terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. A timeout-bounded CTest child process exercises the terminate reporter without a modal prompt. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers.
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 the first interactive gameplay slice, not yet a playable game: movement has no actor collision response, and there are no enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation.
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.
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 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.
The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions.
On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. All CTest binaries now link a test-only startup initializer for the same diagnostics, so an assertion before `main` cannot open an Abort/Retry/Debug modal that blocks the build terminal. The timeout-bounded child probes exercise both a Debug CRT assertion and C++ termination, verifying prompt-free nonzero exits. The terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers.
This is the first interactive gameplay slice, not yet a playable game: movement uses approximate host collision rather than the original actor response, and there are no live enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation.
## Import-Slice Tool
@ -630,14 +667,14 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat
## Near-Term Next Actions
1. Verify the live `Process` group-table allocation/initialization and the active-group writer `11d0:19b5`; compare `11e0:02a8` side effects with an execution trace (including counter ownership and error paths).
1. Verify the live `Process` group-table allocation/initialization and compare the compiled active-group writer/selector (`11d0:19b5/0445`) and `11e0:02a8` side effects with an execution trace (including counter ownership and error paths).
2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots.
3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; verify Stand's ported presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state.
3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; compare the staged map-item/ItemProcess IDs and Stand's presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state.
4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window.
5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence.
6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code.
7. Feed original item/draw-list output into the existing renderer, then lift USECODE dispatch, save/load, audio, and frontend chains as required for playable mission progression.
7. Port `CreateFromSlotIndex` and the `Inter_1418_0244`/`Interpreter_1418_00e8` initialization path with checked stack, parameter, and program-counter state, then execute one selected retail event through original opcode handlers and verify its item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression.
## Current Bottom Line
The project has a buildable diagnostic host, retail resource loaders, a tested process lifecycle for host-owned base and zero-child-state Stand entries, a partial original scheduler scan, and an owned 0x42-byte Stand entry executing recovered NPC-decision and `Run` branches against a source-backed timer counter (`StandProcess Run sleep ticks: 60`, three other host callbacks). Creation and termination update the per-item presence bit, but this is **not** a game milestone: real NPC item ownership, nonempty-child teardown, visibility/activity service implementations, timer-process construction and interrupts, the complete tick, startup, player, renderer, and interaction chains remain unported; `remorse_game.exe` is not connected to this registry. The next measure of progress is a real item-linked Stand/NPC instance running on the original call chain with state trace parity.
The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry now runs an item process bound to a staged retail map record, selects any eligible release-script bytes, and runs a Stand entry under the host tick. This is a map-derived process integration checkpoint, **not** a complete Phase 4 or gameplay milestone: original item cache/block IDs, actual release USECODE execution, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, renderer item output, and interactions remain unported. The next measures of gameplay progress are an executed retail event with a verified live item mutation and a real item-linked Stand/NPC instance on the original call chain with state trace parity.

View file

@ -17,6 +17,7 @@ add_library(remorse_core
src/runtime.cpp
src/shape_archive.cpp
src/type_flags.cpp
src/usecode_archive.cpp
)
target_compile_features(remorse_core PUBLIC cxx_std_17)
@ -155,6 +156,16 @@ target_link_libraries(combat_tactics_tests PRIVATE remorse_core)
add_test(NAME combat_tactics_tests COMMAND combat_tactics_tests)
add_library(remorse_test_crash_setup OBJECT tests/test_crash_setup.cpp)
target_link_libraries(remorse_test_crash_setup PRIVATE remorse_core)
foreach(test_target IN ITEMS
entity_dispatch_entry_tests file_system_tests palette_tests flex_archive_tests
fixed_map_tests glob_archive_tests type_flags_tests shape_archive_tests
map_renderer_tests map_sorter_tests isometric_controls_tests
animation_archive_tests collision_tests combat_tactics_tests)
target_sources(${test_target} PRIVATE $<TARGET_OBJECTS:remorse_test_crash_setup>)
endforeach()
if(MSVC)
target_compile_options(remorse_core PRIVATE /W4 /permissive-)
target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-)

View file

@ -67,8 +67,10 @@ struct NpcBehaviorServices {
class ProcessKernel {
public:
static constexpr u16 maxTrackedItemNumber = 0x23ff;
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]);
SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]);
KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]);
@ -76,16 +78,25 @@ public:
u32 systemTimerTick() const;
void setSyncContext(bool enabled, u16 currentProcessId);
void setMarkNewProcesses(bool enabled);
void setActiveGroup(u8 groupId);
u8 activeGroup() const;
bool groupSelectionPending() const;
void refreshActiveGroup(const u16 (&groupCounts)[32]);
void setLastAllocationSize(u16 size);
u16 addProcess(EntityDispatchEntryBase& entry);
void clearProcessSlot(u16 id);
void terminateProcess(u16 id, u16 (&groupCounts)[32]);
void clearTerminatedProcesses();
void setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber);
void setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType);
void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0);
u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context,
void (*afterScan)(void*) = nullptr, void* afterContext = nullptr);
EntityDispatchEntryBase* processAt(u16 id) const;
u16 allocationSizeAt(u16 id) const;
const char* processNameAt(u16 id) const;
bool itemHasProcess(u16 itemNumber) const;
u8 itemProcessTypes(u16 itemNumber) const;
u16 processCount() const;
u16 terminatedProcessCount() const;
u16 newlyCreatedCount() const;
@ -93,6 +104,8 @@ public:
private:
void releaseOwnedProcess(u16 id);
void refreshItemPresence(u16 itemNumber);
void refreshItemProcessType(u16 itemNumber, u16 eventType);
std::vector<EntityDispatchEntryBase*> processes_;
std::vector<u16> allocationSizes_;
std::vector<const char*> processNames_;
@ -103,11 +116,14 @@ private:
std::unique_ptr<KeyDaemonProcessEntry> keyDaemonProcess_;
u16 systemTimerProcessId_ = 0xffff;
std::vector<u8> itemProcessPresence_;
std::vector<u8> itemProcessTypes_;
u16 lastAllocationSize_ = 0;
u16 processCount_ = 0;
u16 terminatedProcessCount_ = 0;
u16 newlyCreatedCount_ = 0;
u16 currentProcessId_ = 0;
u8 activeGroup_ = 1;
bool groupSelectionPending_ = false;
bool syncEnabled_ = false;
bool markNewProcesses_ = false;
};
@ -119,7 +135,7 @@ public:
static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]);
static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]);
static void incrementGroupId(EntityDispatchEntryBase& entry);
static void incrementGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32]);
static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType);
static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType);
static void sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration);
@ -136,6 +152,15 @@ public:
static void run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick);
};
class ItemProcess {
public:
static constexpr u16 runOffset = 0x0078;
static constexpr u16 vtableOffset = 0x102f;
static void run(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32],
void (*release)(u16 itemNumber, u32 eventMask, u16 eventId, void*), void* context);
};
class SystemTimerProcess {
public:
static u32 tick(const SystemTimerProcessEntry& entry);

View file

@ -8,6 +8,8 @@
namespace remorse {
struct ShapeTypeInfo;
struct FixedMapEntry {
u16 x = 0;
u16 y = 0;
@ -26,6 +28,19 @@ struct FixedMap {
std::vector<FixedMapEntry> entries;
};
struct StagedFixedMapItem {
u16 itemNumber = 0;
std::size_t recordIndex = 0;
FixedMapEntry data;
};
struct ItemFindArea {
u16 minX = 0;
u16 minY = 0;
u16 maxX = 0;
u16 maxY = 0;
};
struct FixedMapArchive {
u32 mapCount = 0;
std::vector<u8> bytes;
@ -33,5 +48,13 @@ struct FixedMapArchive {
std::optional<FixedMapArchive> loadFixedMapArchive(const std::filesystem::path& path);
std::optional<FixedMap> loadFixedMap(const FixedMapArchive& archive, u32 mapIndex);
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map);
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(
const std::vector<StagedFixedMapItem>& items, s32 worldX, s32 worldY, s32 maxDistance);
bool itemGrabCanCreateProcess(const StagedFixedMapItem& item);
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<u16> itemFindBlockOrder(const ItemFindArea& area);
} // namespace remorse

View file

@ -17,6 +17,22 @@ inline bool controllerWalkRequested(u16 modifiers)
return shiftDown == capsLockOn;
}
inline std::optional<u8> controllerDirectionFromScan(u8 scanCode)
{
// Controller_PickNextAnimByKeyevent (1130:12d6), directional keys with Num Lock off.
switch (scanCode) {
case 0x47: return u8{12};
case 0x48: return u8{14};
case 0x49: return u8{0};
case 0x4b: return u8{10};
case 0x4d: return u8{2};
case 0x4f: return u8{8};
case 0x50: return u8{6};
case 0x51: return u8{4};
default: return std::nullopt;
}
}
inline std::optional<AnimationDisplacement> hostMovementStep(
const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection)
{

View file

@ -0,0 +1,54 @@
#pragma once
#include "remorse/flex_archive.h"
#include <optional>
#include <string>
#include <vector>
namespace remorse {
struct UsecodeClass {
u32 classId = 0;
std::string name;
u32 codeBase = 0;
std::vector<u8> bytes;
};
struct UsecodeEventBody {
u16 length = 0;
u32 relativeOffset = 0;
std::vector<u8> bytes;
};
struct UsecodeClassBases {
u16 regularShape = 0;
u16 npc = 0;
u16 unknownEgg = 0;
};
struct UsecodeItemIdentity {
u16 itemNumber = 0;
u16 shape = 0;
u16 status = 0;
u16 quality = 0;
u8 family = 0;
bool isNpc = false;
};
struct EligibleUsecodeEvent {
u16 classId = 0;
std::string className;
UsecodeEventBody body;
};
u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases);
std::optional<std::vector<u8>> loadUsecodeOwnerRows(const FlexArchive& archive);
bool ownerRowAllowsEvent(const std::vector<u8>& ownerRows, u16 classId, u32 eventMask);
std::optional<UsecodeClass> loadUsecodeClass(const FlexArchive& archive, u32 classId);
std::optional<UsecodeEventBody> readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId);
std::optional<EligibleUsecodeEvent> selectEligibleUsecodeEvent(const FlexArchive& archive,
const std::vector<u8>& ownerRows, const UsecodeItemIdentity& item,
const UsecodeClassBases& bases, u32 eventMask, u16 eventId);
} // namespace remorse

View file

@ -61,6 +61,9 @@ EntityDispatchEntryBase* ProcessKernel::createProcess(u8 activeGroup, u16 (&grou
StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32])
{
if (npcNumber > maxTrackedItemNumber) {
throw std::out_of_range("NPC item number exceeds process lookup tables");
}
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
throw std::overflow_error("process table exhausted");
}
@ -102,6 +105,28 @@ StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumb
return result;
}
EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 itemNumber, u16 (&groupCounts)[32])
{
if (itemNumber == 0) {
throw std::invalid_argument("item process needs an item number");
}
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
throw std::overflow_error("process table exhausted");
}
ownedProcesses_.reserve(ownedProcesses_.size() + 1);
auto process = std::make_unique<EntityDispatchEntryBase>();
EntityDispatchEntry::initBase(process.get(), activeGroup, groupCounts);
writeLe16(*process, 0x00, ItemProcess::vtableOffset);
setProcessSourceType(*process, itemNumber);
setProcessEventTypeChecked(*process, 0xf1);
setLastAllocationSize(sizeof(EntityDispatchEntryBase));
const u16 id = addProcess(*process);
processNames_[id] = "ItemProcess";
EntityDispatchEntryBase* result = process.get();
ownedProcesses_.push_back(std::move(process));
return result;
}
SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32])
{
if (systemTimerProcess_ != nullptr) {
@ -195,6 +220,45 @@ void ProcessKernel::setMarkNewProcesses(bool enabled)
markNewProcesses_ = enabled;
}
void ProcessKernel::setActiveGroup(u8 groupId)
{
if (groupId == 0 || groupId > 31) {
throw std::invalid_argument("active process group must be in 1..31");
}
if (activeGroup_ != groupId) {
activeGroup_ = groupId;
groupSelectionPending_ = true;
}
}
u8 ProcessKernel::activeGroup() const
{
return activeGroup_;
}
bool ProcessKernel::groupSelectionPending() const
{
return groupSelectionPending_;
}
void ProcessKernel::refreshActiveGroup(const u16 (&groupCounts)[32])
{
if (groupCounts[activeGroup_] != 0) {
return;
}
u8 highestGroup = 1;
for (const EntityDispatchEntryBase* entry : processes_) {
if (entry != nullptr) {
const u8 groupId = entry->bytes[0x08] & 0x1f;
if (groupId > highestGroup && groupId != 30 && groupId != 31) {
highestGroup = groupId;
}
}
}
setActiveGroup(highestGroup);
groupSelectionPending_ = false;
}
void ProcessKernel::setLastAllocationSize(u16 size)
{
lastAllocationSize_ = size;
@ -260,6 +324,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
throw std::out_of_range("process ID is not addressable");
}
const u16 itemNumber = readLe16(*entry, 0x04);
const u16 eventType = readLe16(*entry, 0x06);
if (systemTimerProcess_ != nullptr && entry == &systemTimerProcess_->base) {
throw std::logic_error("system timer teardown is not ported");
}
@ -271,7 +336,10 @@ 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; });
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() || id < 3 ||
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 ||
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");
@ -292,15 +360,92 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
++terminatedProcessCount_;
}
--processCount_;
refreshItemPresence(itemNumber);
refreshItemProcessType(itemNumber, eventType);
}
void ProcessKernel::refreshItemPresence(u16 itemNumber)
{
if (itemNumber == 0) {
return;
}
const bool present = processes_.size() > 3 && std::any_of(processes_.begin() + 3, processes_.end(),
[itemNumber](const EntityDispatchEntryBase* process) {
return process != nullptr && readLe16(*process, 0x04) == itemNumber &&
(readLe16(*process, 0x16) & 0x08) == 0;
});
const std::size_t itemByte = itemNumber >> 3;
if (itemProcessPresence_.size() <= itemByte) {
itemProcessPresence_.resize(itemByte + 1, 0);
}
if (present) {
itemProcessPresence_[itemByte] |= static_cast<u8>(1u << (itemNumber & 7));
} else {
itemProcessPresence_[itemByte] &= static_cast<u8>(~(1u << (itemNumber & 7)));
}
}
void ProcessKernel::refreshItemProcessType(u16 itemNumber, u16 eventType)
{
if (itemNumber == 0 || eventType < 0xf0 || eventType > 0xf7) {
return;
}
const bool present = processes_.size() > 3 && std::any_of(processes_.begin() + 3, processes_.end(),
[itemNumber, eventType](const EntityDispatchEntryBase* process) {
return process != nullptr && readLe16(*process, 0x04) == itemNumber &&
readLe16(*process, 0x06) == eventType && (readLe16(*process, 0x16) & 0x08) == 0;
});
if (itemProcessTypes_.size() <= itemNumber) {
itemProcessTypes_.resize(static_cast<std::size_t>(itemNumber) + 1, 0);
}
const u8 bit = static_cast<u8>(1u << (eventType - 0xf0));
if (present) {
itemProcessTypes_[itemNumber] |= bit;
} else {
itemProcessTypes_[itemNumber] &= static_cast<u8>(~bit);
}
}
void ProcessKernel::setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber)
{
if (itemNumber > maxTrackedItemNumber) {
throw std::out_of_range("item number exceeds process lookup tables");
}
const u16 previousItem = readLe16(entry, 0x04);
const u16 eventType = readLe16(entry, 0x06);
EntityDispatchEntry::setSourceType(entry, itemNumber);
if (itemNumber != 0) {
const bool stillPresent = std::any_of(processes_.begin() + 3, processes_.end(),
[itemNumber](const EntityDispatchEntryBase* process) {
return process != nullptr && readLe16(*process, 0x04) == itemNumber &&
(readLe16(*process, 0x16) & 0x08) == 0;
});
if (!stillPresent) {
itemProcessPresence_[itemNumber >> 3] &= static_cast<u8>(~(1u << (itemNumber & 7)));
const std::size_t itemByte = itemNumber >> 3;
if (itemProcessPresence_.size() <= itemByte) {
itemProcessPresence_.resize(itemByte + 1, 0);
}
itemProcessPresence_[itemByte] |= static_cast<u8>(1u << (itemNumber & 7));
if (eventType >= 0xf0 && eventType <= 0xf7) {
if (itemProcessTypes_.size() <= itemNumber) {
itemProcessTypes_.resize(static_cast<std::size_t>(itemNumber) + 1, 0);
}
itemProcessTypes_[itemNumber] |= static_cast<u8>(1u << (eventType - 0xf0));
}
}
if (previousItem != 0 && previousItem != itemNumber) {
refreshItemPresence(previousItem);
refreshItemProcessType(previousItem, eventType);
}
}
void ProcessKernel::setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType)
{
const u16 previousType = readLe16(entry, 0x06);
const u16 itemNumber = readLe16(entry, 0x04);
EntityDispatchEntry::setEventTypeChecked(entry, eventType);
if (itemNumber != 0 && eventType >= 0xf0 && eventType <= 0xf7) {
if (itemProcessTypes_.size() <= itemNumber) {
itemProcessTypes_.resize(static_cast<std::size_t>(itemNumber) + 1, 0);
}
itemProcessTypes_[itemNumber] |= static_cast<u8>(1u << (eventType - 0xf0));
}
if (previousType != eventType) {
refreshItemProcessType(itemNumber, previousType);
}
}
@ -324,6 +469,7 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp
if (run == nullptr) {
throw std::invalid_argument("process run slot is required");
}
setActiveGroup(activeGroup);
const bool priorSyncEnabled = syncEnabled_;
const u16 priorProcessId = currentProcessId_;
syncEnabled_ = true;
@ -353,7 +499,7 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp
const u16 flags = readLe16(*entry, 0x16);
if ((readLe16(*entry, 0x18) & 0x1000) == 0 && readLe16(*entry, 0x24) == 0 &&
readLe16(*entry, 0x26) == 0 && (flags & 1) == 0 &&
((flags & 2) != 0 || groupId == activeGroup || groupId == 30 || groupId == 31)) {
((flags & 2) != 0 || groupId == activeGroup_ || groupId == 30 || groupId == 31)) {
currentProcessId_ = static_cast<u16>(id);
run(*entry, context);
currentProcessId_ = 0;
@ -371,6 +517,17 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp
currentProcessId_ = priorProcessId;
}
u32 ProcessKernel::runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context,
void (*afterScan)(void*), void* afterContext)
{
const u32 startTick = systemTimerTick();
scanRunnableProcesses(activeGroup, run, context, startTick);
if (afterScan != nullptr) {
afterScan(afterContext);
}
return systemTimerTick() - startTick;
}
EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const
{
return id < processes_.size() ? processes_[id] : nullptr;
@ -393,6 +550,11 @@ bool ProcessKernel::itemHasProcess(u16 itemNumber) const
(itemProcessPresence_[itemByte] & (1u << (itemNumber & 7))) != 0;
}
u8 ProcessKernel::itemProcessTypes(u16 itemNumber) const
{
return itemNumber < itemProcessTypes_.size() ? itemProcessTypes_[itemNumber] : 0;
}
u16 ProcessKernel::processCount() const
{
return processCount_;
@ -449,9 +611,15 @@ void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId,
++groupCounts[groupId];
}
void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry)
void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32])
{
++entry.bytes[groupIdOffset];
const u8 previousGroup = entry.bytes[groupIdOffset] & 0x1f;
const u8 nextGroup = static_cast<u8>(previousGroup + 1);
if (nextGroup >= 30 || kernel.activeGroup() != previousGroup) {
throw std::invalid_argument("process group cannot advance from the current active group");
}
setGroupId(entry, nextGroup, groupCounts);
kernel.setActiveGroup(nextGroup);
}
void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sourceType)
@ -462,6 +630,9 @@ void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sour
void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType)
{
writeLe16(entry, eventTypeOffset, eventType);
if (eventType > 0x0fff) {
throw std::invalid_argument("process event type exceeds 0x0fff");
}
}
void EntityDispatchEntry::sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration)
@ -511,6 +682,17 @@ void StandProcess::run(StandProcessEntry& entry, const NpcBehaviorServices& serv
}, &started, timerTick);
}
void ItemProcess::run(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32],
void (*release)(u16 itemNumber, u32 eventMask, u16 eventId, void*), void* context)
{
if (release == nullptr) {
throw std::invalid_argument("item release boundary is required");
}
const u16 itemNumber = readLe16(entry, 0x04);
release(itemNumber, 0x200, 9, context);
kernel.terminateProcess(readLe16(entry, 0x02), groupCounts);
}
u32 SystemTimerProcess::tick(const SystemTimerProcessEntry& entry)
{
return static_cast<u32>(entry.extra[0x0e] | (static_cast<u16>(entry.extra[0x0f]) << 8)) |

View file

@ -1,6 +1,7 @@
#include "remorse/fixed_map.h"
#include "remorse/file_system.h"
#include "remorse/type_flags.h"
namespace remorse {
namespace {
@ -116,4 +117,111 @@ std::optional<FixedMap> loadFixedMap(const FixedMapArchive& archive, u32 mapInde
return map;
}
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map)
{
constexpr std::size_t firstFreeItemNumber = 0x100;
constexpr std::size_t freeItemCount = 0x2700;
std::vector<StagedFixedMapItem> items;
items.reserve(map.entries.size());
std::size_t allocated = 0;
for (std::size_t index = 0; index < map.entries.size(); ++index) {
if (map.entries[index].shape == 0) {
continue;
}
if (allocated == freeItemCount) {
return std::nullopt;
}
const u16 itemNumber = static_cast<u16>(firstFreeItemNumber + allocated++);
if ((map.entries[index].flags & 8) != 0) {
continue;
}
StagedFixedMapItem item;
item.itemNumber = itemNumber;
item.recordIndex = index;
item.data = map.entries[index];
item.data.x = static_cast<u16>(item.data.x / crusaderCoordinateScale);
item.data.y = static_cast<u16>(item.data.y / crusaderCoordinateScale);
item.data.flags &= static_cast<u16>(~1u);
items.push_back(item);
}
return items;
}
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(
const std::vector<StagedFixedMapItem>& items, s32 worldX, s32 worldY, s32 maxDistance)
{
if (maxDistance < 0) {
return std::nullopt;
}
const auto limit = static_cast<std::int64_t>(maxDistance) * maxDistance;
auto bestDistance = limit + 1;
const StagedFixedMapItem* best = nullptr;
for (const auto& item : items) {
const auto deltaX = static_cast<std::int64_t>(item.data.x) * crusaderCoordinateScale - worldX;
const auto deltaY = static_cast<std::int64_t>(item.data.y) * crusaderCoordinateScale - worldY;
const auto distance = deltaX * deltaX + deltaY * deltaY;
if (distance <= limit && distance < bestDistance) {
bestDistance = distance;
best = &item;
}
}
return best == nullptr ? std::nullopt : std::optional<StagedFixedMapItem>(*best);
}
bool itemGrabCanCreateProcess(const StagedFixedMapItem& item)
{
return (item.data.flags & 0x02) == 0;
}
u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape,
const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags)
{
if (candidate.itemNumber == 0) {
return 0;
}
const auto height = [](const ShapeTypeInfo& shape) {
return shape.z == 0 && (shape.flags & 1) == 0 ? 1 : static_cast<int>(shape.z) * 8;
};
const int minimumX = static_cast<int>(candidate.data.x) - static_cast<int>(candidateShape.x) * 16 + 1;
const int minimumY = static_cast<int>(candidate.data.y) - static_cast<int>(candidateShape.y) * 16 + 1;
if (minimumX > origin.data.x || minimumY > origin.data.y) {
return 0;
}
const u8 originTop = static_cast<u8>(static_cast<int>(origin.data.z) + height(originShape));
if ((zMatchFlags & 1) != 0 && candidate.data.z == originTop) {
return 1;
}
if ((zMatchFlags & 2) != 0 && origin.data.z == static_cast<int>(candidate.data.z) + height(candidateShape)) {
return 2;
}
return 0;
}
ItemFindArea itemFindAreaAroundItem(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape)
{
const auto normalize = [](u16 value, u16 negativeValue) {
return static_cast<s16>(value) < 0 ? negativeValue : value;
};
const u16 minX = static_cast<u16>(static_cast<int>(origin.data.x) - originShape.x * 16 + 1);
const u16 minY = static_cast<u16>(static_cast<int>(origin.data.y) - originShape.y * 16 + 1);
const u16 maxX = static_cast<u16>(origin.data.x + 0x100);
const u16 maxY = static_cast<u16>(origin.data.y + 0x100);
return {normalize(minX, 0), normalize(minY, 0),
normalize(maxX, 0x7fff), normalize(maxY, 0x7fff)};
}
std::vector<u16> itemFindBlockOrder(const ItemFindArea& area)
{
std::vector<u16> blocks;
if (area.minX > area.maxX || area.minY > area.maxY) {
return blocks;
}
for (u16 blockY = area.minY >> 9; blockY <= (area.maxY >> 9); ++blockY) {
for (u16 blockX = area.minX >> 9; blockX <= (area.maxX >> 9); ++blockX) {
blocks.push_back(static_cast<u16>(blockX * 0x40 + blockY));
}
}
return blocks;
}
} // namespace remorse

View file

@ -7,6 +7,7 @@
#include "remorse/palette.h"
#include "remorse/runtime.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include <filesystem>
#include <iostream>
@ -27,7 +28,7 @@ int main(int argc, char** argv)
remorse::printStartupReport(*manifest);
remorse::ProcessKernel kernel;
remorse::u16 groupCounts[32]{};
const auto* entry = kernel.createProcess(1, groupCounts);
auto* entry = kernel.createProcess(1, groupCounts);
std::cout << "Registered process ID: " << (entry ? entry->bytes[0x02] : 0) << '\n';
for (int index = 0; index < 3; ++index) {
kernel.createProcess(1, groupCounts);
@ -57,20 +58,25 @@ int main(int argc, char** argv)
kernel.deliverSystemTimerEvent();
}
scanContext.timerTick = kernel.systemTimerTick();
kernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
const remorse::u32 schedulerElapsed = kernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& scan = *static_cast<ScanContext*>(context);
if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) {
remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick);
} else {
++scan.hostCallbacks;
}
}, &scanContext, scanContext.timerTick);
}, &scanContext);
kernel.refreshActiveGroup(groupCounts);
remorse::EntityDispatchEntry::incrementGroupId(*entry, kernel, groupCounts);
std::cout << "Advanced process group: " << static_cast<int>(kernel.activeGroup()) << '\n';
std::cout << "Scheduler scan host callbacks: " << scanContext.hostCallbacks << '\n';
std::cout << "Scheduler pass elapsed ticks: " << schedulerElapsed << '\n';
std::cout << "StandProcess Run sleep ticks: " << static_cast<int>(reused->base.bytes[0x0e]) << '\n';
const auto gameDataRoot = remorse::findGameDataRoot(std::filesystem::current_path());
std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n';
if (gameDataRoot) {
std::optional<remorse::StagedFixedMapItem> firstStagedItem;
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';
@ -92,6 +98,33 @@ int main(int argc, char** argv)
if (map && !map->entries.empty()) {
std::cout << "FIXED.DAT first non-empty map: " << index << '\n';
std::cout << "FIXED.DAT first non-empty entries: " << map->entries.size() << '\n';
const auto items = remorse::stageFixedMapItems(*map);
if (items && !items->empty()) {
firstStagedItem = items->front();
struct ItemScanContext {
remorse::ProcessKernel* kernel;
remorse::u16 (*groups)[32];
remorse::u16 releaseEventItem = 0;
} itemScan{&kernel, &groupCounts};
auto* itemProcess = kernel.createItemProcess(kernel.activeGroup(), items->front().itemNumber, groupCounts);
const remorse::u16 itemProcessId = static_cast<remorse::u16>(
itemProcess->bytes[2] | (static_cast<remorse::u16>(itemProcess->bytes[3]) << 8));
kernel.scanRunnableProcesses(kernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& scan = *static_cast<ItemScanContext*>(context);
if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) {
remorse::ItemProcess::run(process, *scan.kernel, *scan.groups,
[](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) {
if (eventMask == 0x200 && eventId == 9) {
static_cast<ItemScanContext*>(releaseContext)->releaseEventItem = itemNumber;
}
}, &scan);
}
}, &itemScan, kernel.systemTimerTick());
kernel.refreshActiveGroup(groupCounts);
std::cout << "Staged retail item shape: " << items->front().data.shape << '\n';
std::cout << "ItemProcess release event boundary item: " << itemScan.releaseEventItem << '\n';
std::cout << "ItemProcess terminated: " << (kernel.processAt(itemProcessId) == nullptr) << '\n';
}
break;
}
}
@ -104,6 +137,26 @@ int main(int argc, char** argv)
const auto typeFlagPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt;
std::cout << "TYPEFLAG.DAT shapes: " << (typeFlags ? typeFlags->size() : 0) << '\n';
if (firstStagedItem && typeFlags && firstStagedItem->data.shape < typeFlags->size()) {
const auto area = remorse::itemFindAreaAroundItem(
*firstStagedItem, (*typeFlags)[firstStagedItem->data.shape]);
std::cout << "Staged item ItemFind blocks: " << remorse::itemFindBlockOrder(area).size() << '\n';
}
const auto usecodePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("USECODE") / "EUSECODE.FLX");
const auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt;
const auto eventClass = usecodeArchive ? remorse::loadUsecodeClass(*usecodeArchive, 0x361) : std::nullopt;
const auto eventBody = eventClass ? remorse::readUsecodeEventBody(*eventClass, 0x0a) : std::nullopt;
std::cout << "EUSECODE EVENT slot 0x0a body bytes: " << (eventBody ? eventBody->bytes.size() : 0) << '\n';
if (firstStagedItem && typeFlags && usecodeArchive && firstStagedItem->data.shape < typeFlags->size()) {
const auto& item = *firstStagedItem;
const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false};
const remorse::UsecodeClassBases bases{0, 0x800, 0x900};
const auto itemClass = remorse::loadUsecodeClass(*usecodeArchive,
remorse::selectUsecodeClassId(identity, bases));
std::cout << "Staged item USECODE class: " << (itemClass ? itemClass->name : "not present") << '\n';
}
}
return 0;
}

View file

@ -0,0 +1,109 @@
#include "remorse/usecode_archive.h"
#include <utility>
namespace remorse {
namespace {
u16 readWord(const std::vector<u8>& bytes, std::size_t offset)
{
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
u32 readDword(const std::vector<u8>& bytes, std::size_t offset)
{
return static_cast<u32>(bytes[offset]) | (static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) | (static_cast<u32>(bytes[offset + 3]) << 24);
}
} // namespace
u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases)
{
if (item.isNpc && (item.status & 2) == 0) {
return static_cast<u16>(item.itemNumber + bases.npc);
}
if (item.family == 4) {
return static_cast<u16>((item.quality & 0xff) + bases.unknownEgg);
}
return static_cast<u16>(item.shape + bases.regularShape);
}
std::optional<std::vector<u8>> loadUsecodeOwnerRows(const FlexArchive& archive)
{
auto rows = readFlexEntry(archive, 1);
if (!rows || rows->size() % 13 != 0) {
return std::nullopt;
}
return rows;
}
bool ownerRowAllowsEvent(const std::vector<u8>& ownerRows, u16 classId, u32 eventMask)
{
constexpr std::size_t rowSize = 13;
const std::size_t row = static_cast<std::size_t>(classId) * rowSize;
if (eventMask == 0 || row > ownerRows.size() || ownerRows.size() - row < rowSize) {
return false;
}
return (readDword(ownerRows, row) & eventMask) != 0;
}
std::optional<UsecodeClass> loadUsecodeClass(const FlexArchive& archive, u32 classId)
{
if (classId >= archive.entryCount || archive.entryCount - classId <= 2) {
return std::nullopt;
}
const auto names = loadUsecodeOwnerRows(archive);
auto bytes = readFlexEntry(archive, classId + 2);
if (!names || !bytes || bytes->size() < 20 || classId >= names->size() / 13) {
return std::nullopt;
}
const std::size_t nameOffset = 4 + static_cast<std::size_t>(classId) * 13;
const u32 codeBase = readDword(*bytes, 8);
if (codeBase < 20 || codeBase > bytes->size() || (codeBase - 20) % 6 != 0) {
return std::nullopt;
}
std::string name;
for (std::size_t index = 0; index < 9 && (*names)[nameOffset + index] != 0; ++index) {
name.push_back(static_cast<char>((*names)[nameOffset + index]));
}
return UsecodeClass{classId, std::move(name), codeBase, std::move(*bytes)};
}
std::optional<UsecodeEventBody> readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId)
{
if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() ||
eventId >= (usecodeClass.codeBase - 20) / 6) {
return std::nullopt;
}
const std::size_t row = 20 + static_cast<std::size_t>(eventId) * 6;
const u16 length = readWord(usecodeClass.bytes, row);
const u32 offset = readDword(usecodeClass.bytes, row + 2);
if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) {
return std::nullopt;
}
const std::size_t start = usecodeClass.codeBase + static_cast<std::size_t>(offset) - 1;
if (length > usecodeClass.bytes.size() - start) {
return std::nullopt;
}
return UsecodeEventBody{length, offset,
std::vector<u8>(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)};
}
std::optional<EligibleUsecodeEvent> selectEligibleUsecodeEvent(const FlexArchive& archive,
const std::vector<u8>& ownerRows, const UsecodeItemIdentity& item,
const UsecodeClassBases& bases, u32 eventMask, u16 eventId)
{
const u16 classId = selectUsecodeClassId(item, bases);
if (!ownerRowAllowsEvent(ownerRows, classId, eventMask)) {
return std::nullopt;
}
const auto usecodeClass = loadUsecodeClass(archive, classId);
const auto body = usecodeClass ? readUsecodeEventBody(*usecodeClass, eventId) : std::nullopt;
if (!body) {
return std::nullopt;
}
return EligibleUsecodeEvent{classId, usecodeClass->name, *body};
}
} // namespace remorse

View file

@ -14,6 +14,7 @@
#include "remorse/runtime.h"
#include "remorse/shape_archive.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include <algorithm>
#include <cmath>
@ -37,6 +38,7 @@ constexpr remorse::u32 backingHeight = 1440;
constexpr int initialClientWidth = 1280;
constexpr int initialClientHeight = 760;
constexpr double simulationTickSeconds = 0.025;
constexpr remorse::s32 diagnosticItemRange = 48;
struct AppState {
remorse::GameDataRoot root;
@ -45,6 +47,13 @@ struct AppState {
remorse::u16 diagnosticGroupCounts[32]{};
remorse::StandProcessEntry* diagnosticStand = nullptr;
remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr;
std::vector<remorse::StagedFixedMapItem> stagedItems;
std::optional<remorse::StagedFixedMapItem> diagnosticItem;
remorse::u16 diagnosticItemProcessId = 0;
remorse::u16 diagnosticReleaseEventItem = 0;
std::string diagnosticReleaseClass;
std::size_t diagnosticReleaseBodyBytes = 0;
bool diagnosticItemCompleted = false;
remorse::u32 standWakeCount = 0;
remorse::u32 diagnosticKeyEvents = 0;
std::mutex sceneMutex;
@ -55,6 +64,9 @@ struct AppState {
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames;
remorse::CollisionBody playerCollisionBody{};
std::vector<remorse::CollisionBody> collisionBodies;
std::vector<remorse::ShapeTypeInfo> shapeTypes;
std::optional<remorse::FlexArchive> usecodeArchive;
std::vector<remorse::u8> usecodeOwnerRows;
remorse::Palette256 playerPalette{};
std::vector<std::uint8_t> dibPixels;
std::vector<std::uint8_t> viewPixels;
@ -139,6 +151,7 @@ void loadSceneAsync(HWND window, AppState& state)
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto stagedItems = remorse::stageFixedMapItems(*map);
const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath);
const auto globObjects = remorse::loadGlobObjects(*globPath);
@ -148,6 +161,11 @@ void loadSceneAsync(HWND window, AppState& state)
return;
}
auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects);
const auto usecodePath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX");
auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt;
const auto usecodeOwnerRows = usecodeArchive
? remorse::loadUsecodeOwnerRows(*usecodeArchive) : std::nullopt;
const auto animationPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "ANIM.DAT");
@ -246,6 +264,11 @@ void loadSceneAsync(HWND window, AppState& state)
state.playerWorld = spawn;
state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
state.collisionBodies = std::move(collisionBodies);
state.shapeTypes = *shapeTypes;
state.usecodeArchive = std::move(usecodeArchive);
if (usecodeOwnerRows) {
state.usecodeOwnerRows = *usecodeOwnerRows;
}
state.minWorldX = minX;
state.minWorldY = minY;
state.maxWorldX = maxX;
@ -257,6 +280,9 @@ void loadSceneAsync(HWND window, AppState& state)
state.runAnimation = *runAnimation;
state.playerFrames = std::move(playerFrames);
state.playerPalette = *palette;
if (stagedItems) {
state.stagedItems = std::move(*stagedItems);
}
state.sceneLoaded = true;
}
} catch (const std::exception& error) {
@ -285,23 +311,23 @@ bool isKeyDown(int key)
std::optional<remorse::u8> readMovementDirection()
{
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return static_cast<remorse::u8>(12);
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return static_cast<remorse::u8>(0);
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return static_cast<remorse::u8>(8);
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return static_cast<remorse::u8>(4);
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return remorse::controllerDirectionFromScan(0x47);
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return remorse::controllerDirectionFromScan(0x49);
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return remorse::controllerDirectionFromScan(0x4f);
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return remorse::controllerDirectionFromScan(0x51);
const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8);
const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6);
const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2);
const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4);
if (up && left) return static_cast<remorse::u8>(12);
if (up && right) return static_cast<remorse::u8>(0);
if (down && left) return static_cast<remorse::u8>(8);
if (down && right) return static_cast<remorse::u8>(4);
if (up) return static_cast<remorse::u8>(14);
if (right) return static_cast<remorse::u8>(2);
if (down) return static_cast<remorse::u8>(6);
if (left) return static_cast<remorse::u8>(10);
if (up && left) return remorse::controllerDirectionFromScan(0x47);
if (up && right) return remorse::controllerDirectionFromScan(0x49);
if (down && left) return remorse::controllerDirectionFromScan(0x4f);
if (down && right) return remorse::controllerDirectionFromScan(0x51);
if (up) return remorse::controllerDirectionFromScan(0x48);
if (right) return remorse::controllerDirectionFromScan(0x4d);
if (down) return remorse::controllerDirectionFromScan(0x50);
if (left) return remorse::controllerDirectionFromScan(0x4b);
return std::nullopt;
}
@ -488,7 +514,7 @@ void paintWindow(HWND window, AppState& state)
}
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
RECT hud{0, 0, viewWidth, 62};
RECT hud{0, 0, viewWidth, 80};
HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29));
FillRect(device, &hud, hudBrush);
DeleteObject(hudBrush);
@ -510,7 +536,7 @@ void paintWindow(HWND window, AppState& state)
HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
RECT labelBounds{20, 0, viewWidth - 12, 36};
RECT labelBounds{20, 0, viewWidth - 12, 30};
const int saved = SaveDC(device);
SetBkMode(device, TRANSPARENT);
SetTextColor(device, RGB(224, 229, 214));
@ -528,9 +554,27 @@ void paintWindow(HWND window, AppState& state)
: 0)
<< L" | WAKEUPS " << state.standWakeCount
<< L" | KEY EVENTS " << state.diagnosticKeyEvents;
RECT diagnosticsBounds{20, 36, viewWidth - 12, hud.bottom - 1};
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);
if (state.diagnosticItem || nearbyItem) {
const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem;
std::wostringstream itemStatus;
itemStatus << L"MAP ITEM " << displayItem->itemNumber
<< L" | SHAPE " << displayItem->data.shape
<< L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem
<< L" | " << (state.diagnosticReleaseBodyBytes != 0
? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (NOT RUN)"
: L"NO RELEASE SCRIPT")
<< L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" :
state.diagnosticItemProcessId != 0 ? L"QUEUED" :
displayItem->itemNumber > remorse::ProcessKernel::maxTrackedItemNumber ? L"ITEM OUT OF RANGE" :
!remorse::itemGrabCanCreateProcess(*displayItem) ? L"ITEM FLAG BLOCKS" : L"F: TEST RELEASE");
RECT itemBounds{20, 54, viewWidth - 12, hud.bottom - 1};
DrawTextW(device, itemStatus.str().c_str(), -1, &itemBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
}
RestoreDC(device, saved);
DeleteObject(hudFont);
@ -567,14 +611,38 @@ void updatePlayer(HWND window, AppState& state)
state.diagnosticKernel.deliverSystemTimerEvent();
const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0;
const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand);
state.diagnosticKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& entry, void* context) {
state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) {
auto& app = *static_cast<AppState*>(context);
if (&entry == &app.diagnosticStand->base) {
remorse::StandProcess::run(entry,
[](const remorse::EntityDispatchEntryBase&, void*) { return false; },
nullptr, app.diagnosticKernel.systemTimerTick());
} else if (entry.bytes[0] == 0x2f && entry.bytes[1] == 0x10) {
remorse::ItemProcess::run(entry, app.diagnosticKernel, app.diagnosticGroupCounts,
[](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) {
auto& app = *static_cast<AppState*>(releaseContext);
app.diagnosticReleaseEventItem = itemNumber;
if (app.diagnosticItem && app.usecodeArchive &&
app.diagnosticItem->data.shape < app.shapeTypes.size()) {
const auto& item = *app.diagnosticItem;
const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, app.shapeTypes[item.data.shape].family, false};
const remorse::UsecodeClassBases bases{0, 0x800, 0x900};
const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive,
app.usecodeOwnerRows, identity, bases, eventMask, eventId);
if (eligible) {
app.diagnosticReleaseClass = eligible->className;
app.diagnosticReleaseBodyBytes = eligible->body.bytes.size();
}
}
}, &app);
}
}, &state, state.diagnosticKernel.systemTimerTick());
}, &state);
state.diagnosticKernel.refreshActiveGroup(state.diagnosticGroupCounts);
if (state.diagnosticItemProcessId != 0 &&
state.diagnosticKernel.processAt(state.diagnosticItemProcessId) == nullptr) {
state.diagnosticItemCompleted = true;
}
if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) {
++state.standWakeCount;
}
@ -656,6 +724,26 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
updatePlayer(window, *state);
}
return 0;
case WM_KEYDOWN:
if (wParam == 'F') {
std::lock_guard<std::mutex> 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);
}
if (state->diagnosticItem && state->diagnosticItemProcessId == 0 &&
state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber &&
remorse::itemGrabCanCreateProcess(*state->diagnosticItem)) {
auto* itemProcess = state->diagnosticKernel.createItemProcess(
state->diagnosticKernel.activeGroup(), state->diagnosticItem->itemNumber,
state->diagnosticGroupCounts);
state->diagnosticItemProcessId = static_cast<remorse::u16>(
itemProcess->bytes[2] | (static_cast<remorse::u16>(itemProcess->bytes[3]) << 8));
InvalidateRect(window, nullptr, FALSE);
}
}
return 0;
case WM_CHAR:
if (wParam > 0 && wParam <= 0xff) {
remorse::KeyEvent lastEvent{};
@ -677,9 +765,10 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
case WM_PAINT:
paintWindow(window, *state);
return 0;
case sceneReadyMessage:
case sceneReadyMessage: {
InvalidateRect(window, nullptr, FALSE);
return 0;
}
case WM_DESTROY:
KillTimer(window, timerId);
if (state->sceneThread.joinable()) {

View file

@ -33,6 +33,15 @@ int main()
remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x00f2);
assert(entry.bytes[0x06] == 0xf2);
assert(entry.bytes[0x07] == 0x00);
remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x0fff);
assert(entry.bytes[0x06] == 0xff && entry.bytes[0x07] == 0x0f);
bool invalidEventType = false;
try {
remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x1000);
} catch (const std::invalid_argument&) {
invalidEventType = true;
}
assert(invalidEventType && entry.bytes[0x06] == 0 && entry.bytes[0x07] == 0x10);
remorse::EntityDispatchEntry::sleep(entry, 0x12345678, 0x0001003c);
assert(entry.bytes[0x18] == 0x01 && entry.bytes[0x19] == 0x10);
@ -63,8 +72,34 @@ int main()
assert(rejected && entry.bytes[0x08] == 4 && groupCounts[4] == 1);
}
remorse::EntityDispatchEntry::incrementGroupId(entry);
assert(entry.bytes[0x08] == 5);
remorse::ProcessKernel incrementKernel;
incrementKernel.setActiveGroup(4);
remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts);
assert(entry.bytes[0x08] == 5 && groupCounts[4] == 0 && groupCounts[5] == 1);
assert(incrementKernel.activeGroup() == 5 && incrementKernel.groupSelectionPending());
bool wrongActiveGroup = false;
try {
remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts);
} catch (const std::invalid_argument&) {
wrongActiveGroup = true;
}
assert(!wrongActiveGroup && entry.bytes[0x08] == 6 && incrementKernel.activeGroup() == 6);
incrementKernel.setActiveGroup(7);
try {
remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts);
} catch (const std::invalid_argument&) {
wrongActiveGroup = true;
}
assert(wrongActiveGroup && entry.bytes[0x08] == 6 && groupCounts[6] == 1);
remorse::EntityDispatchEntry::setGroupId(entry, 29, groupCounts);
incrementKernel.setActiveGroup(29);
bool groupLimitReached = false;
try {
remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts);
} catch (const std::invalid_argument&) {
groupLimitReached = true;
}
assert(groupLimitReached && entry.bytes[0x08] == 29 && groupCounts[29] == 1);
remorse::ProcessKernel kernel;
kernel.setLastAllocationSize(sizeof(entry));
@ -171,8 +206,43 @@ int main()
}
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
remorse::ProcessKernel groupKernel;
remorse::u16 groupTable[32]{};
for (int index = 0; index < 3; ++index) {
groupKernel.createProcess(1, groupTable);
}
groupKernel.createProcess(2, groupTable);
groupKernel.createProcess(3, groupTable);
groupKernel.createProcess(30, groupTable);
groupKernel.createProcess(31, groupTable);
groupKernel.refreshActiveGroup(groupTable);
assert(groupKernel.activeGroup() == 1 && !groupKernel.groupSelectionPending());
groupKernel.setActiveGroup(4);
assert(groupKernel.activeGroup() == 4 && groupKernel.groupSelectionPending());
groupKernel.refreshActiveGroup(groupTable);
assert(groupKernel.activeGroup() == 3 && !groupKernel.groupSelectionPending());
groupKernel.terminateProcess(4, groupTable);
groupKernel.clearTerminatedProcesses();
groupKernel.refreshActiveGroup(groupTable);
assert(groupKernel.activeGroup() == 2 && !groupKernel.groupSelectionPending());
for (remorse::u8 invalidGroup : {remorse::u8{0}, remorse::u8{32}}) {
bool rejected = false;
try {
groupKernel.setActiveGroup(invalidGroup);
} catch (const std::invalid_argument&) {
rejected = true;
}
assert(rejected && groupKernel.activeGroup() == 2 && !groupKernel.groupSelectionPending());
}
groupKernel.setActiveGroup(30);
groupKernel.refreshActiveGroup(groupTable);
assert(groupKernel.activeGroup() == 30 && groupKernel.groupSelectionPending());
remorse::ProcessKernel scheduler;
remorse::u16 scheduledGroups[32]{};
assert(scheduler.activeGroup() == 1 && !scheduler.groupSelectionPending());
scheduler.setActiveGroup(1);
assert(!scheduler.groupSelectionPending());
auto* otherGroup = scheduler.createProcess(1, scheduledGroups);
auto* matching = scheduler.createProcess(2, scheduledGroups);
auto* syncingProcess = scheduler.createProcess(2, scheduledGroups);
@ -185,6 +255,7 @@ int main()
};
scheduler.scanRunnableProcesses(2, recordRun, &ran);
assert((ran == std::vector<remorse::u16>{1, 3}));
assert(scheduler.activeGroup() == 2 && scheduler.groupSelectionPending());
assert(syncingProcess->bytes[0x16] == 0 && otherGroup->bytes[0x16] == 0);
ran.clear();
matching->bytes[0x16] = 1;
@ -246,10 +317,37 @@ int main()
assert(sleeper->bytes[offset] == 0);
}
remorse::ProcessKernel timedPassKernel;
remorse::u16 timedPassGroups[32]{};
auto* timedPassSleeper = timedPassKernel.createProcess(1, timedPassGroups);
timedPassKernel.createSystemTimerProcess(1, timedPassGroups);
timedPassKernel.deliverSystemTimerEvent();
remorse::EntityDispatchEntry::sleep(*timedPassSleeper, 1, 1);
std::vector<remorse::u16> timedPassRuns;
const auto advanceTimer = [](void* context) {
static_cast<remorse::ProcessKernel*>(context)->deliverSystemTimerEvent();
};
assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns,
advanceTimer, &timedPassKernel) == 1);
assert(timedPassRuns.empty() && timedPassKernel.systemTimerTick() == 2);
assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns,
advanceTimer, &timedPassKernel) == 1);
assert(timedPassRuns.empty() && timedPassKernel.systemTimerTick() == 3);
assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns,
advanceTimer, &timedPassKernel) == 1);
assert((timedPassRuns == std::vector<remorse::u16>{0}));
remorse::ProcessKernel standKernel;
remorse::u16 standGroups[32]{};
standKernel.createProcess(2, standGroups);
assert(!standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
bool oversizedStandRejected = false;
try {
standKernel.createStandProcess(2, 0x2400, standGroups);
} catch (const std::out_of_range&) {
oversizedStandRejected = true;
}
assert(oversizedStandRejected && standGroups[2] == 1 && standKernel.processCount() == 1);
auto* standEntry = standKernel.createStandProcess(2, 0x1234, standGroups);
auto* standing = &standEntry->base;
assert(standKernel.processAt(1) == standing && standKernel.allocationSizeAt(1) == 0x42);
@ -260,6 +358,72 @@ int main()
assert(standing->bytes[0x17] == 0x03 && standEntry->extra[0] == 0x01 && standEntry->extra[1] == 0x01);
assert(standEntry->extra[0x0e] == 0x34 && standEntry->extra[0x0f] == 0x12);
assert(standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
remorse::ProcessKernel cachedItemKernel;
remorse::u16 cachedItemGroups[32]{};
for (int index = 0; index < 3; ++index) {
cachedItemKernel.createProcess(1, cachedItemGroups);
}
auto* itemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups);
assert(cachedItemKernel.processAt(3) == itemProcess && cachedItemKernel.allocationSizeAt(3) == 0x32);
assert(std::strcmp(cachedItemKernel.processNameAt(3), "ItemProcess") == 0);
assert(itemProcess->bytes[0] == 0x2f && itemProcess->bytes[1] == 0x10);
assert(itemProcess->bytes[4] == 0 && itemProcess->bytes[5] == 1);
assert(itemProcess->bytes[6] == 0xf1 && itemProcess->bytes[7] == 0);
assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemProcessTypes(0x100) == 2);
assert(cachedItemGroups[1] == 4);
auto* sharedItemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups);
assert(cachedItemKernel.itemProcessTypes(0x100) == 2);
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x101);
assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemHasProcess(0x101));
assert(cachedItemKernel.itemProcessTypes(0x100) == 2 && cachedItemKernel.itemProcessTypes(0x101) == 2);
cachedItemKernel.setProcessEventTypeChecked(*sharedItemProcess, 0xf2);
assert(cachedItemKernel.itemProcessTypes(0x101) == 4);
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0);
assert(!cachedItemKernel.itemHasProcess(0x101) && cachedItemKernel.itemProcessTypes(0x101) == 0);
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x102);
assert(cachedItemKernel.itemHasProcess(0x102) && cachedItemKernel.itemProcessTypes(0x102) == 4);
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x23ff);
assert(cachedItemKernel.itemHasProcess(0x23ff) && cachedItemKernel.itemProcessTypes(0x23ff) == 4);
bool invalidItemNumber = false;
try {
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x2400);
} catch (const std::out_of_range&) {
invalidItemNumber = true;
}
assert(invalidItemNumber && cachedItemKernel.itemHasProcess(0x23ff));
assert(!cachedItemKernel.itemHasProcess(0x2400) && cachedItemKernel.itemProcessTypes(0x2400) == 0);
cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x102);
cachedItemKernel.terminateProcess(4, cachedItemGroups);
cachedItemKernel.clearTerminatedProcesses();
assert(!cachedItemKernel.itemHasProcess(0x102) && cachedItemKernel.itemProcessTypes(0x102) == 0);
bool missingReleaseRejected = false;
try {
remorse::ItemProcess::run(*itemProcess, cachedItemKernel, cachedItemGroups, nullptr, nullptr);
} catch (const std::invalid_argument&) {
missingReleaseRejected = true;
}
assert(missingReleaseRejected && cachedItemKernel.itemHasProcess(0x100) && cachedItemGroups[1] == 4);
remorse::u16 releasedItem = 0;
struct ItemRunContext {
remorse::ProcessKernel* kernel;
remorse::u16 (*groups)[32];
remorse::u16* released;
} itemRunContext{&cachedItemKernel, &cachedItemGroups, &releasedItem};
cachedItemKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& state = *static_cast<ItemRunContext*>(context);
if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) {
remorse::ItemProcess::run(process, *state.kernel, *state.groups,
[](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* result) {
assert(eventMask == 0x200 && eventId == 9);
*static_cast<remorse::u16*>(result) = itemNumber;
},
state.released);
}
}, &itemRunContext);
assert(releasedItem == 0x100 && !cachedItemKernel.itemHasProcess(0x100));
assert(cachedItemKernel.itemProcessTypes(0x100) == 0);
assert(cachedItemKernel.processAt(3) == nullptr && cachedItemGroups[1] == 3);
bool itemTeardownRejected = false;
try {
standKernel.terminateProcess(1, standGroups);

View file

@ -29,6 +29,10 @@ int main(int argc, char** argv)
}
}
#ifdef _DEBUG
if (argc == 2 && std::strcmp(argv[1], "--assert-probe") == 0) {
assert(false && "diagnostic assert probe");
return 0;
}
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
#endif
@ -44,52 +48,63 @@ int main(int argc, char** argv)
if (GetModuleFileNameW(nullptr, executable, MAX_PATH) == 0) {
return 1;
}
std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" --crash-probe";
SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
HANDLE readPipe = nullptr;
HANDLE writePipe = nullptr;
if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) {
return 1;
}
if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(readPipe);
auto runProbe = [&](const wchar_t* option, const char* expectedOutput, bool expectExitOne) {
std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" " + option;
SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
HANDLE readPipe = nullptr;
HANDLE writePipe = nullptr;
if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) {
return false;
}
if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(readPipe);
CloseHandle(writePipe);
return false;
}
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESTDHANDLES;
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startup.hStdOutput = writePipe;
startup.hStdError = writePipe;
PROCESS_INFORMATION child{};
if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW,
nullptr, nullptr, &startup, &child)) {
CloseHandle(readPipe);
CloseHandle(writePipe);
return false;
}
CloseHandle(writePipe);
return 1;
}
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESTDHANDLES;
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startup.hStdOutput = writePipe;
startup.hStdError = writePipe;
PROCESS_INFORMATION child{};
if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW,
nullptr, nullptr, &startup, &child)) {
const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000);
if (waitResult == WAIT_TIMEOUT) {
TerminateProcess(child.hProcess, 2);
WaitForSingleObject(child.hProcess, INFINITE);
}
char buffer[512];
DWORD count = 0;
std::string crashOutput;
while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) {
crashOutput.append(buffer, count);
}
DWORD exitCode = 0;
const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode);
CloseHandle(readPipe);
CloseHandle(writePipe);
return 1;
}
CloseHandle(writePipe);
const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000);
if (waitResult == WAIT_TIMEOUT) {
TerminateProcess(child.hProcess, 2);
WaitForSingleObject(child.hProcess, INFINITE);
}
char buffer[512];
DWORD count = 0;
std::string crashOutput;
while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) {
crashOutput.append(buffer, count);
}
DWORD exitCode = 0;
const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode);
CloseHandle(readPipe);
CloseHandle(child.hThread);
CloseHandle(child.hProcess);
if (!gotExitCode || waitResult != WAIT_OBJECT_0 || exitCode != 1 ||
crashOutput.find("Unhandled C++ exception: diagnostic probe") == std::string::npos) {
std::fprintf(stderr, "Crash probe wait=%lu exit=0x%08lX output=%s\n",
waitResult, exitCode, crashOutput.c_str());
CloseHandle(child.hThread);
CloseHandle(child.hProcess);
const bool passed = gotExitCode && waitResult == WAIT_OBJECT_0 &&
(expectExitOne ? exitCode == 1 : exitCode != 0) &&
crashOutput.find(expectedOutput) != std::string::npos;
if (!passed) {
std::fprintf(stderr, "Probe %ls wait=%lu exit=0x%08lX output=%s\n",
option, waitResult, exitCode, crashOutput.c_str());
}
return passed;
};
if (!runProbe(L"--crash-probe", "Unhandled C++ exception: diagnostic probe", true)
#ifdef _DEBUG
|| !runProbe(L"--assert-probe", "diagnostic assert probe", false)
#endif
) {
return 1;
}
#endif

View file

@ -1,8 +1,11 @@
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/type_flags.h"
#include <cassert>
#include <filesystem>
#include <vector>
int main()
{
@ -31,6 +34,126 @@ int main()
}
assert(foundNonEmptyMap);
const auto retailMap = remorse::loadFixedMap(*archive, 1);
assert(retailMap.has_value() && !retailMap->entries.empty());
const auto cachedItems = remorse::stageFixedMapItems(*retailMap);
assert(cachedItems.has_value() && !cachedItems->empty());
assert(cachedItems->back().itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber);
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& originShape = (*typeFlags)[cachedItems->front().data.shape];
auto origin = cachedItems->front();
origin.data.z = 80;
auto candidate = origin;
candidate.itemNumber = static_cast<remorse::u16>(origin.itemNumber + 1);
candidate.data.z = static_cast<remorse::u8>(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::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 1);
assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 2) == 0);
candidate.data.z = 79;
assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 2);
remorse::ShapeTypeInfo flatShape{0, 1, 1, 1, 0, 0};
candidate.data.z = 80;
assert(remorse::classifyItemFindZMatch(origin, flatShape, candidate, flatShape, 3) == 1);
candidate.data.x = static_cast<remorse::u16>(origin.data.x + 16);
assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0);
const auto retailSearchArea = remorse::itemFindAreaAroundItem(cachedItems->front(), originShape);
const auto retailSearchBlocks = remorse::itemFindBlockOrder(retailSearchArea);
assert(!retailSearchBlocks.empty() && retailSearchBlocks.front() ==
(retailSearchArea.minX >> 9) * 0x40 + (retailSearchArea.minY >> 9));
origin.data.x = 511;
origin.data.y = 511;
const auto crossingArea = remorse::itemFindAreaAroundItem(origin, footprint);
assert(crossingArea.minX == 496 && crossingArea.minY == 496);
assert(crossingArea.maxX == 767 && crossingArea.maxY == 767);
assert((remorse::itemFindBlockOrder(crossingArea) == std::vector<remorse::u16>{0, 64, 1, 65}));
origin.data.x = 0;
origin.data.y = 0;
const auto edgeArea = remorse::itemFindAreaAroundItem(origin, footprint);
assert(edgeArea.minX == 0 && edgeArea.minY == 0);
assert((remorse::itemFindBlockOrder(edgeArea) == std::vector<remorse::u16>{0}));
candidate.itemNumber = 0;
assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0);
assert(cachedItems->front().recordIndex < retailMap->entries.size());
for (const auto& item : *cachedItems) {
const auto& record = retailMap->entries[item.recordIndex];
assert(record.shape != 0 && (record.flags & 8) == 0);
assert(item.data.x == record.x / 2 && item.data.y == record.y / 2);
assert(item.data.shape == record.shape);
assert(item.data.npcNumber == record.npcNumber);
assert(item.data.flags == (record.flags & ~1u));
}
remorse::ProcessKernel retailKernel;
remorse::u16 retailGroups[32]{};
for (int index = 0; index < 3; ++index) {
retailKernel.createProcess(1, retailGroups);
}
const auto retailItemNumber = cachedItems->front().itemNumber;
auto* retailProcess = retailKernel.createItemProcess(1, retailItemNumber, retailGroups);
assert(retailProcess->bytes[4] == static_cast<remorse::u8>(retailItemNumber));
assert(retailKernel.itemHasProcess(retailItemNumber));
struct RetailScan {
remorse::ProcessKernel* kernel;
remorse::u16 (*groups)[32];
remorse::u16 released = 0;
int releaseCount = 0;
} retailScan{&retailKernel, &retailGroups};
auto runRetailItem = [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& scan = *static_cast<RetailScan*>(context);
if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) {
remorse::ItemProcess::run(process, *scan.kernel, *scan.groups,
[](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) {
assert(eventMask == 0x200 && eventId == 9);
auto& result = *static_cast<RetailScan*>(releaseContext);
result.released = itemNumber;
++result.releaseCount;
}, &scan);
}
};
retailKernel.scanRunnableProcesses(1, runRetailItem, &retailScan, 1);
retailKernel.scanRunnableProcesses(1, runRetailItem, &retailScan, 2);
assert(retailScan.released == retailItemNumber && retailScan.releaseCount == 1);
assert(retailKernel.processAt(3) == nullptr && !retailKernel.itemHasProcess(retailItemNumber));
assert(retailGroups[1] == 3);
remorse::FixedMap stagedMap;
stagedMap.entries.resize(4);
stagedMap.entries[1].shape = 16;
stagedMap.entries[2].shape = 16;
stagedMap.entries[2].flags = 8;
stagedMap.entries[3].shape = 16;
stagedMap.entries[3].flags = 1;
auto stagedItems = remorse::stageFixedMapItems(stagedMap);
assert(stagedItems && stagedItems->size() == 2);
assert((*stagedItems)[0].recordIndex == 1 && (*stagedItems)[0].itemNumber == 0x100);
assert((*stagedItems)[1].recordIndex == 3 && (*stagedItems)[1].itemNumber == 0x102);
assert((*stagedItems)[1].data.flags == 0);
assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0]));
(*stagedItems)[0].data.flags |= 0x02;
assert(!remorse::itemGrabCanCreateProcess((*stagedItems)[0]));
(*stagedItems)[0].data.x = 20;
(*stagedItems)[0].data.y = 10;
(*stagedItems)[1].data.x = 30;
(*stagedItems)[1].data.y = 10;
const auto nearby = remorse::nearestStagedFixedMapItem(*stagedItems, 59, 20, 16);
assert(nearby && nearby->itemNumber == 0x102);
assert(!remorse::nearestStagedFixedMapItem(*stagedItems, 100, 20, 16));
assert(!remorse::nearestStagedFixedMapItem(*stagedItems, 60, 20, -1));
remorse::FixedMap oversizedMap;
oversizedMap.entries.resize(0x2701);
for (auto& record : oversizedMap.entries) {
record.shape = 16;
}
assert(!remorse::stageFixedMapItems(oversizedMap).has_value());
remorse::FixedMap widerCacheMap;
widerCacheMap.entries.resize(0x2301);
for (auto& record : widerCacheMap.entries) {
record.shape = 16;
}
const auto widerCacheItems = remorse::stageFixedMapItems(widerCacheMap);
assert(widerCacheItems && widerCacheItems->back().itemNumber == 0x2400);
assert(widerCacheItems->back().itemNumber > remorse::ProcessKernel::maxTrackedItemNumber);
const auto outOfRange = remorse::loadFixedMap(*archive, archive->mapCount);
assert(!outOfRange.has_value());
return 0;

View file

@ -1,5 +1,8 @@
#include "remorse/file_system.h"
#include "remorse/flex_archive.h"
#include "remorse/fixed_map.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include <cassert>
#include <filesystem>
@ -23,5 +26,91 @@ int main()
assert((*firstEntry)[1] == 'u');
assert((*firstEntry)[2] == 'm');
assert((*firstEntry)[3] == 'b');
const auto usecodePath = remorse::resolveGameDataPath(*root, std::filesystem::path("USECODE") / "EUSECODE.FLX");
assert(usecodePath);
const auto usecode = remorse::loadFlexArchive(*usecodePath);
assert(usecode);
const auto retailOwnerRows = remorse::loadUsecodeOwnerRows(*usecode);
assert(retailOwnerRows && retailOwnerRows->size() % 13 == 0);
const auto eventClass = remorse::loadUsecodeClass(*usecode, 0x361);
assert(eventClass && eventClass->name == "EVENT" && eventClass->codeBase == 0xd4);
const auto eventBody = remorse::readUsecodeEventBody(*eventClass, 0x0a);
assert(eventBody && eventBody->length == 0x1fd6 && eventBody->relativeOffset == 1);
assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]);
assert(!remorse::readUsecodeEventBody(*eventClass, 0x20));
assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount));
auto truncated = *eventClass;
truncated.bytes.resize(truncated.codeBase + 1);
assert(!remorse::readUsecodeEventBody(truncated, 0x0a));
auto invalidOffset = *eventClass;
invalidOffset.bytes[20 + 0x0a * 6 + 2] = 0;
assert(!remorse::readUsecodeEventBody(invalidOffset, 0x0a));
const auto rechargeClass = remorse::loadUsecodeClass(*usecode, 0x138);
assert(rechargeClass && rechargeClass->name == "RECHFLNS");
const auto releaseBody = remorse::readUsecodeEventBody(*rechargeClass, 9);
assert(releaseBody && releaseBody->length == 102 && releaseBody->relativeOffset == 0x256);
assert(remorse::ownerRowAllowsEvent(*retailOwnerRows, 0x138, 0x200));
const remorse::UsecodeClassBases bases{0x200, 0x400, 0x600};
remorse::UsecodeItemIdentity identity{7, 0x45, 0, 0x1278, 4, true};
assert(remorse::selectUsecodeClassId(identity, bases) == 0x407);
identity.status = 2;
assert(remorse::selectUsecodeClassId(identity, bases) == 0x678);
identity.family = 0;
assert(remorse::selectUsecodeClassId(identity, bases) == 0x245);
identity.isNpc = false;
identity.status = 0;
assert(remorse::selectUsecodeClassId(identity, bases) == 0x245);
const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT");
const auto flagsPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
assert(fixedPath && flagsPath);
const auto fixedArchive = remorse::loadFixedMapArchive(*fixedPath);
const auto fixedMap = fixedArchive ? remorse::loadFixedMap(*fixedArchive, 1) : std::nullopt;
const auto typeFlags = remorse::loadTypeFlags(*flagsPath);
assert(fixedMap && typeFlags);
const auto stagedItems = remorse::stageFixedMapItems(*fixedMap);
assert(stagedItems && !stagedItems->empty());
const auto& staged = stagedItems->front();
assert(staged.data.shape < typeFlags->size());
const remorse::UsecodeItemIdentity stagedIdentity{staged.itemNumber, staged.data.shape,
staged.data.flags, staged.data.quality, (*typeFlags)[staged.data.shape].family, false};
const remorse::UsecodeClassBases retailBases{0, 0x800, 0x900};
assert(remorse::selectUsecodeClassId(stagedIdentity, retailBases) == staged.data.shape);
const auto stagedClass = remorse::loadUsecodeClass(*usecode,
remorse::selectUsecodeClassId(stagedIdentity, retailBases));
assert(!stagedClass);
assert(!remorse::ownerRowAllowsEvent(*retailOwnerRows, staged.data.shape, 0x200));
assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
stagedIdentity, retailBases, 0x200, 9));
bool foundStagedRelease = false;
for (const auto& item : *stagedItems) {
if (item.data.shape >= typeFlags->size()) {
continue;
}
const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false};
if (remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
mapItemIdentity, retailBases, 0x200, 9)) {
foundStagedRelease = true;
break;
}
}
assert(foundStagedRelease);
const remorse::UsecodeItemIdentity rechargeItem{0x100, 0x138, 0, 0, 0, false};
const auto eligibleRelease = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
rechargeItem, retailBases, 0x200, 9);
assert(eligibleRelease && eligibleRelease->classId == 0x138 &&
eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102);
assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
rechargeItem, retailBases, 0, 9));
std::vector<remorse::u8> ownerRows(26);
ownerRows[13] = 0x00;
ownerRows[14] = 0x02;
ownerRows[16] = 0x01;
assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x200));
assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x1000000));
assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0x400));
assert(!remorse::ownerRowAllowsEvent(ownerRows, 0, 0x200));
assert(!remorse::ownerRowAllowsEvent(ownerRows, 2, 0x200));
assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0));
return 0;
}

View file

@ -11,6 +11,12 @@ int main()
assert(!remorse::controllerWalkRequested(0x40));
assert(remorse::controllerWalkRequested(0x41));
assert(remorse::controllerWalkRequested(0x42));
constexpr remorse::u8 scans[] = {0x47, 0x48, 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51};
constexpr remorse::u8 directions[] = {12, 14, 0, 10, 2, 8, 6, 4};
for (std::size_t index = 0; index < std::size(scans); ++index) {
assert(remorse::controllerDirectionFromScan(scans[index]) == directions[index]);
}
assert(!remorse::controllerDirectionFromScan(0x52));
constexpr remorse::s32 originX = 1024;
constexpr remorse::s32 originY = 2048;
const remorse::ScreenPoint origin = remorse::projectToScreen({originX, originY, 0});

View file

@ -0,0 +1,11 @@
#include "remorse/runtime.h"
namespace {
struct TestCrashSetup {
TestCrashSetup() { remorse::installCrashDiagnostics(); }
};
TestCrashSetup testCrashSetup;
} // namespace