From e757bb33d0fd9b877eee3ca92d6d12f4d3044b3d Mon Sep 17 00:00:00 2001 From: Maddo Date: Sun, 27 Sep 2026 11:48:14 +0200 Subject: [PATCH] Add extensive tests for animation, input handling, and map rendering - Enhanced animation archive tests to validate frame metadata and start frame selection logic. - Introduced new tests for entity dispatch entry handling, including key event queuing and processing. - Added tests for fixed map item interactions, including glob egg hatching and item movement. - Expanded flex archive tests to cover teleport egg spawning and usecode event selection. - Implemented isometric controls tests to verify directional key handling and animation state changes. - Improved map renderer tests to ensure correct rendering of map previews and collision detection. --- docs/remorse-windows-rebuild-roadmap.md | 23 +- rebuild/remorse/CMakeLists.txt | 1 + .../include/remorse/animation_archive.h | 7 + .../include/remorse/entity_dispatch_entry.h | 36 ++ rebuild/remorse/include/remorse/fixed_map.h | 20 + .../include/remorse/isometric_controls.h | 43 ++ .../remorse/include/remorse/map_renderer.h | 23 ++ rebuild/remorse/include/remorse/usecode_vm.h | 30 ++ rebuild/remorse/src/animation_archive.cpp | 23 ++ rebuild/remorse/src/entity_dispatch_entry.cpp | 205 +++++++++- rebuild/remorse/src/fixed_map.cpp | 114 +++++- rebuild/remorse/src/map_renderer.cpp | 106 +++-- rebuild/remorse/src/usecode_vm.cpp | 29 ++ rebuild/remorse/src/windowed_game_main.cpp | 383 +++++++++++++----- .../remorse/tests/animation_archive_tests.cpp | 23 ++ .../tests/entity_dispatch_entry_tests.cpp | 133 ++++++ rebuild/remorse/tests/fixed_map_tests.cpp | 32 +- rebuild/remorse/tests/flex_archive_tests.cpp | 47 +++ .../tests/isometric_controls_tests.cpp | 16 + rebuild/remorse/tests/map_renderer_tests.cpp | 99 +++++ 20 files changed, 1249 insertions(+), 144 deletions(-) create mode 100644 rebuild/remorse/include/remorse/usecode_vm.h create mode 100644 rebuild/remorse/src/usecode_vm.cpp diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index eccb171..aa7898e 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -16,6 +16,25 @@ The exported files are evidence, not directly compilable game source. Keep them - At each milestone, count original functions translated and exercised in the Windows build, platform calls replaced, and parity checks passed. A rendered scene or a controllable stand-in actor alone does not pass a game-code milestone. - Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. +## Source-Backed In-Game Vertical Slice + +The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host-controlled sprite over a frozen map does **not** count. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. + +1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, not from the map bounds, and prove its coordinates and the spawned avatar/item ID in a retail-data test. Do not implement intro movies, main menu, save loading, or warp overrides for this slice. +2. **Live world ownership:** initialize the original item cache and NPC/avatar state for that map. The displayed avatar must be the same numbered, mutable item advanced by the process runtime; reject a separately drawn or separately positioned stand-in. +3. **Tick and input:** port the minimal recovered cycle/scheduler and keyboard queue/control chain that moves that avatar. Route Win32 key/timer events through the host boundary into those routines; test deterministic state changes with recorded inputs, including idle and blocked movement. +4. **Gameplay presentation:** render the live item/sprite state in source draw order each tick and follow the recovered camera state. Verify that movement, facing, and at least one changed world item appear on screen, without relying on a single prepainted fixed-map image. +5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. +6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. + +Progress: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; opcode execution is not implemented. These are partial translations of steps 1-4, **not completed steps**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and USECODE execution remain open. Collision is approximate; no visible scripted world mutation or deterministic end-to-end interaction acceptance exists. Steps 5-6 remain open. + +Retail map-1 probing at the starting egg found four children after fast-area GLOB hatching and no eligible `use` script on those children; no direct fixed-map item within 1,024 staged units has an eligible event body. The nearest direct `use` items are panel/card objects roughly 8,800 staged units away. Their event bodies delegate to `TRIGGER.slot_20` or `SWITCH.slot_21`, which require additional VM, timer, selector, and world-state services. A renderer regression confirms that moving hatched children changes live scene pixels, but this is not script execution or proof that those distant interactions are reachable through the current collision path. + +Control-path evidence for step 3: live `CRUSADER.EXE` disassembly at `1130:224b-226a` compares event selectors against the five words at `1130:273b` (`1, 2, 4, 0x10, 0x100`); the matching CS jump-table words at `1130:274f` target `226e, 2276, 22b6, 22bd, 22b6`. The gameplay-key case at `1130:22bd` copies all 12 bytes of the incoming key event. The exported `Controller_HandleKeyEvent` pseudo-C contains an invalid branch after this table and must not be compiled verbatim. The 32-slot, 12-byte pending-key ring (`11d0:3533/3ad4/3a74/3aad`) and a registered-subscriber dispatch (`11d0:3c4d`) are ported in `ProcessKernel`; tests cover order, full/overflow, wrap, and delivery to a controller entry rather than the excluded keyboard process. The 0x40-byte controller entry mirrors the keyboard registration and daemon/update flags of `ControllerProcess_CreateProcess` (`1130:00e3`), **but the window does not create it or feed its queue**. `Controller_PickNextAnimByKeyevent` (`1130:12d6`) reads two keyboard state arrays through `Keyboard_GetKeyState` (`11d0:39b9`, DS offsets `3652` and `3352`) and selects animation through NPC state and services. `Kernel_11d0_39fb` installs the DOS interrupt-9 keyboard path through `FUN_1218_059b`; exported C exposes the arrays' reads/resets but not their hardware writer. Recover the key-state update semantics from the interrupt path and port the controller's reachable movement branches before replacing host polling; do not guess their edge/held meaning. + +Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies `NPC_DoAnim` (`10e8:0252`) with the controlled NPC item pointer, animation number, direction, and two zero arguments that the exported controller pseudo-C omits. The unarmed walk/run cases allocate `AnimPrimitiveProcess` (`1150:0000`, size `0x5b`); live disassembly at `1150:0033-009c` confirms its normal vtable offset `0x2a57`, event type `0xf0`, and linear-capable setup. A kernel-owned constructor with this layout, item/type registration, direction, and clip metadata now has a byte-level test. `AnimPrimitive_SetStartFrame` (`1150:17b2`) is ported and tested for two-step/looping and controlled-avatar frame-skip branches. Its tick (`1150:1906`) still needs NPC animation-frame state, fast-area/collision behavior, item updates, transitions, and teardown. The Windows host frame counter is not this process. Finish the tick and collision result before swapping the default control path. + ## Current Inputs - `exports/src_remorse/export_manifest.json` reports `CRUSADER.EXE`, 2,984 exported function files, 9 fallback function files, 57 global buckets, and 15,403 global definitions. @@ -348,6 +367,8 @@ Next source-port checks, in call-chain order: `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. +The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. Pass `--diagnostics` (before or after the map number) to restore the diagnostic harness and its HUD. The map-1 startup midpoint is checked against the same collision bodies as the window, with at least one legal neighboring move. This is a **retail-data movement test**, not yet the real game: the player is host-created, rendering uses a static map preview, movement uses host polling/step policy, and neither the original startup/game loop nor item USECODE/mission interactions are running. Do not use this mode split as the roadmap's playable-game exit criterion. + From the repository root: ```powershell @@ -355,7 +376,7 @@ rebuild\remorse\build_msvc.cmd Debug .\rebuild\remorse\out\build-nmake\remorse_game.exe 1 ``` -The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. +The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The opt-in diagnostic HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. 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. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 67ee6da..9a37b5c 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -18,6 +18,7 @@ add_library(remorse_core src/shape_archive.cpp src/type_flags.cpp src/usecode_archive.cpp + src/usecode_vm.cpp ) target_compile_features(remorse_core PUBLIC cxx_std_17) diff --git a/rebuild/remorse/include/remorse/animation_archive.h b/rebuild/remorse/include/remorse/animation_archive.h index 3af202f..2b08e30 100644 --- a/rebuild/remorse/include/remorse/animation_archive.h +++ b/rebuild/remorse/include/remorse/animation_archive.h @@ -39,6 +39,13 @@ std::optional getAnimationFrame( u8 frameIndex); u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept; bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept; +u8 selectAnimationStartFrame( + const AnimationClip& clip, + bool returningFromTwoStep, + bool sameAsLastAnimation, + bool controlledAvatar, + bool entirelyOnScreen, + u8 frameSkip) noexcept; std::optional decodeAnimationDisplacement( const AnimationFrameMetadata& metadata, u8 direction, diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 3492924..b993856 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -2,13 +2,16 @@ #include "remorse/compat.h" +#include #include #include +#include #include namespace remorse { class LiveFixedMapItems; +struct AnimationClip; struct ShapeTypeInfo; struct WorldPoint; struct FastAreaRange; @@ -43,6 +46,16 @@ struct KeyDaemonProcessEntry { u8 extra[0x0e]; } CR_PACKED; +struct ControllerProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x0e]; +} CR_PACKED; + +struct AnimPrimitiveProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x29]; +} CR_PACKED; + struct KeyEvent { u8 character; u8 scanCode; @@ -65,6 +78,8 @@ static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size mus static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); +static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence"); +static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); struct NpcBehaviorServices { @@ -97,6 +112,20 @@ public: SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); + ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); + AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, + u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); + bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, u8 frameSkip = 0); + std::optional advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, const std::vector& shapes, + const FastAreaRange& fastArea); + bool queuePendingKeyEvent(const KeyEvent& event); + std::optional popPendingKeyEvent(); + u8 pendingKeyEventCount() const; + bool pendingKeyEventOverflowed() const; + void dispatchPendingKeyEvents( + void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context); void deliverSystemTimerEvent(); u32 systemTimerTick() const; void setSyncContext(bool enabled, u16 currentProcessId); @@ -136,9 +165,16 @@ private: std::vector> ownedProcesses_; std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; + std::vector> ownedAnimPrimitiveProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; + std::unique_ptr controllerProcess_; + std::vector keyboardSubscriberIds_; + std::array pendingKeyEvents_{}; + u8 nextKeyEventOffset_ = 0; + u8 keyEventOffset_ = 0; + bool pendingKeyEventOverflowed_ = false; u16 systemTimerProcessId_ = 0xffff; std::vector itemProcessPresence_; std::vector itemProcessTypes_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 184964c..3b7bd42 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -10,6 +10,7 @@ namespace remorse { struct ShapeTypeInfo; struct WorldRect; +struct GlobObject; class ProcessKernel; struct FixedMapEntry { @@ -77,6 +78,8 @@ struct FixedMapArchive { std::optional loadFixedMapArchive(const std::filesystem::path& path); std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); std::optional> stageFixedMapItems(const FixedMap& map); +std::optional findTeleportEgg( + const std::vector& items, const std::vector& shapes, u8 eggId); std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes); std::optional nearestStagedFixedMapItem( @@ -99,16 +102,30 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& const std::vector& items, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick); +struct NpcAnimationState { + u16 lastAnimation = 0xffff; + u8 frame = 0; + u8 moreFlags = 0; +}; + class LiveFixedMapItems { public: explicit LiveFixedMapItems(std::vector items, std::vector containedItems = {}); + bool initializeAvatar(); + bool teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber); const StagedFixedMapItem* findItem(u16 itemNumber) const; + const std::vector& mapItems() const noexcept { return items_; } + const NpcAnimationState* findNpcAnimation(u16 itemNumber) const; + NpcAnimationState* editNpcAnimation(u16 itemNumber); u16 containedParent(u16 itemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); + std::optional> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob, + const std::vector& shapes); + bool isGlobHatched(u16 eggItemNumber) const; bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; @@ -118,7 +135,10 @@ public: private: std::vector items_; + std::optional avatar_; + std::vector npcAnimations_; std::vector allocatedIds_; + std::vector hatchedGlobIds_; std::vector parentById_; u16 nextFreeItemNumber_ = 0x100; }; diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h index e0f50ae..3120aad 100644 --- a/rebuild/remorse/include/remorse/isometric_controls.h +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -3,6 +3,9 @@ #include "remorse/animation_archive.h" #include "remorse/compat.h" +#include +#include + namespace remorse { struct WorldPositionD { @@ -33,6 +36,46 @@ inline std::optional controllerDirectionFromScan(u8 scanCode) } } +struct ControllerMovementRequest { + u8 animation = 0; + u8 direction = 14; +}; + +class ControllerMovementState { +public: + void handleDirectionalKey(u8 scanCode, u16 modifiers, bool pressed) + { + modifiers_ = modifiers; + const auto direction = controllerDirectionFromScan(scanCode); + if (!direction) { + return; + } + const auto held = std::find(heldScans_.begin(), heldScans_.end(), scanCode); + if (held != heldScans_.end()) { + heldScans_.erase(held); + } + if (pressed && (modifiers & 0x20) == 0) { + heldScans_.push_back(scanCode); + } + } + + ControllerMovementRequest request() const + { + if (heldScans_.empty()) { + return {0, lastDirection_}; + } + lastDirection_ = *controllerDirectionFromScan(heldScans_.back()); + return {static_cast(controllerWalkRequested(modifiers_) ? 1 : 3), lastDirection_}; + } + + void clear() { heldScans_.clear(); } + +private: + std::vector heldScans_; + u16 modifiers_ = 0; + mutable u8 lastDirection_ = 14; +}; + inline std::optional hostMovementStep( const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection) { diff --git a/rebuild/remorse/include/remorse/map_renderer.h b/rebuild/remorse/include/remorse/map_renderer.h index 90510b3..28425dc 100644 --- a/rebuild/remorse/include/remorse/map_renderer.h +++ b/rebuild/remorse/include/remorse/map_renderer.h @@ -6,7 +6,13 @@ #include "remorse/compat.h" #include "remorse/file_system.h" +#include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/palette.h" +#include "remorse/shape_archive.h" +#include "remorse/type_flags.h" + +#include namespace remorse { @@ -17,6 +23,8 @@ struct WorldRect { s32 maxY = 0; }; +class LiveFixedMapItems; + struct WorldPoint { s32 x = 0; s32 y = 0; @@ -53,7 +61,22 @@ struct RenderedMapImage { std::vector pixels; }; +struct MapSceneRenderer { + FixedMap map; + std::vector globs; + ShapeArchive shapes; + Palette256 palette; + std::vector typeFlags; + std::map, DecodedShapeFrame> decodedFrames; + + std::optional render(const MapRenderOptions& options, + const LiveFixedMapItems* liveItems = nullptr); +}; + +std::optional loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex); std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options); +std::optional renderLiveMapPreview(const GameDataRoot& root, + const MapRenderOptions& options, const LiveFixedMapItems& items); ScreenPoint projectToScreen(const WorldPoint& point); bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image); diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h new file mode 100644 index 0000000..1d59e25 --- /dev/null +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct UsecodeCallFrame { + u16 offset = 0; + u16 segment = 0; +}; + +class UsecodeInterpreterState { +public: + static std::optional initialize( + const std::vector& itemParameter); + bool pushCodeAddress(u16 offset, u16 segment); + + std::array valueStack{}; + std::size_t stackTop = 0xcc; + std::array callFrames{}; + u16 callFrameCount = 0; + u16 stackLimit = 199; +}; + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/animation_archive.cpp b/rebuild/remorse/src/animation_archive.cpp index f898135..401ee9e 100644 --- a/rebuild/remorse/src/animation_archive.cpp +++ b/rebuild/remorse/src/animation_archive.cpp @@ -104,6 +104,29 @@ bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept return (metadata.bytes[1] & 0x80) != 0; } +u8 selectAnimationStartFrame( + const AnimationClip& clip, + bool returningFromTwoStep, + bool sameAsLastAnimation, + bool controlledAvatar, + bool entirelyOnScreen, + u8 frameSkip) noexcept +{ + const u8 flags = clip.header[1]; + if ((flags & 1) != 0) { + if (!returningFromTwoStep) { + return static_cast(clip.frameCount / 2); + } + return (flags & 4) != 0 ? static_cast(clip.frameCount - 1) : 0; + } + if ((flags & 4) == 0 || !sameAsLastAnimation) { + return 0; + } + const bool skipFrame = controlledAvatar ? frameSkip == 3 : + frameSkip >= 2 || !entirelyOnScreen; + return skipFrame ? 2 : 1; +} + std::optional decodeAnimationDisplacement( const AnimationFrameMetadata& metadata, u8 direction, diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index a07b7e5..829e83a 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -1,4 +1,5 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/animation_archive.h" #include "remorse/collision.h" #include "remorse/fixed_map.h" @@ -138,6 +139,115 @@ EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 it return result; } +AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, + u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]) +{ + if (itemNumber == 0 || itemNumber > maxTrackedItemNumber || animationNumber > 0x3f || + direction > 15 || clip.frameCount == 0) { + throw std::out_of_range("invalid animation process request"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x2a57); + setProcessSourceType(process->base, itemNumber); + setProcessEventTypeChecked(process->base, 0xf0); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x800)); + writeLe16(process->base, 0x22, 0xf0); + process->extra[0] = 1; + process->extra[4] = static_cast(animationNumber); + process->extra[5] = static_cast(animationNumber >> 8); + process->extra[6] = direction; + process->extra[7] = clip.frameCount; + std::copy(clip.header.begin(), clip.header.end(), process->extra + 0x18); + setLastAllocationSize(sizeof(AnimPrimitiveProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "AnimPrimitive"; + AnimPrimitiveProcessEntry* result = process.get(); + ownedAnimPrimitiveProcesses_.push_back(std::move(process)); + return result; +} + +bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, u8 frameSkip) +{ + auto* process = processAt(processId); + if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) || + (readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] != 0 || + std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; }) || + clip.frameCount != process->bytes[0x39] || + !std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) { + return false; + } + auto* npc = items.editNpcAnimation(readLe16(*process, 0x04)); + if (npc == nullptr) { + return false; + } + const u16 animation = readLe16(*process, 0x36); + npc->frame = selectAnimationStartFrame(clip, (npc->moreFlags & 4) != 0, + npc->lastAnimation == animation, readLe16(*process, 0x04) == 1, true, frameSkip); + npc->lastAnimation = animation; + process->bytes[0x3a] = 1; + return true; +} + +std::optional ProcessKernel::advanceGroundedAnimPrimitive(u16 processId, + LiveFixedMapItems& items, const AnimationClip& clip, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + auto* process = processAt(processId); + if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) || + (readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] == 0 || + std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; }) || + clip.frameCount != process->bytes[0x39] || + !std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) { + return std::nullopt; + } + const u16 itemNumber = readLe16(*process, 0x04); + auto* npc = items.editNpcAnimation(itemNumber); + const auto* item = items.findItem(itemNumber); + if (npc == nullptr || item == nullptr || item->data.shape >= shapes.size() || + npc->lastAnimation != readLe16(*process, 0x36)) { + return std::nullopt; + } + u8 nextFrame = static_cast(npc->frame + 1); + if ((clip.header[1] & 1) != 0 && (npc->moreFlags & 4) != 0 && + nextFrame == clip.frameCount / 2) { + return std::nullopt; + } + if (nextFrame >= clip.frameCount && (clip.header[1] & 5) == 5) { + nextFrame = 1; + } + if (nextFrame >= clip.frameCount) { + return std::nullopt; + } + const u8 direction = process->bytes[0x38]; + const auto metadata = getAnimationFrame(clip, direction, nextFrame); + if (!metadata || (metadata->bytes[5] & 2) == 0) { + return std::nullopt; + } + const auto step = decodeAnimationDisplacement(*metadata, direction, (clip.header[2] & 0x10) != 0); + if (!step) { + return std::nullopt; + } + const WorldPoint destination{static_cast(item->data.x) + step->x, + static_cast(item->data.y) + step->y, + static_cast(item->data.z) + step->z}; + const auto sweep = resolveSolidLiveSweep(items, itemNumber, destination, shapes, fastArea); + if (!sweep || sweep->failed || sweep->failedDirections != 0 || + !items.moveItem(itemNumber, static_cast(sweep->destination.x), + static_cast(sweep->destination.y), static_cast(sweep->destination.z))) { + process->bytes[0x3c] = 1; + return false; + } + npc->frame = nextFrame; + return true; +} + u16 ProcessKernel::hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, u32 timerTick, u16 (&groupCounts)[32]) { @@ -350,6 +460,7 @@ KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 ( const u16 id = addProcess(process->base); processNames_[id] = "KeyboardProcess"; writeLe16(process->base, 0x18, static_cast(readLe16(process->base, 0x18) | 0x180)); + keyboardSubscriberIds_.push_back(id); keyboardProcess_ = std::move(process); return keyboardProcess_.get(); } @@ -375,6 +486,30 @@ KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16 return keyDaemonProcess_.get(); } +ControllerProcessEntry* ProcessKernel::createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (controllerProcess_ != nullptr) { + throw std::logic_error("controller process already exists"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x3aa6); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x300)); + writeLe16(process->base, 0x18, static_cast(readLe16(process->base, 0x18) | 0x80)); + process->extra[0] = 0x15; + process->extra[1] = 0x01; + process->extra[4] = 0x3c; + setLastAllocationSize(sizeof(ControllerProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Controller"; + keyboardSubscriberIds_.push_back(id); + controllerProcess_ = std::move(process); + return controllerProcess_.get(); +} + void ProcessKernel::deliverSystemTimerEvent() { if (systemTimerProcess_ == nullptr) { @@ -504,6 +639,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedGravityProcesses_.erase(gravity); return; } + const auto animation = std::find_if(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (animation != ownedAnimPrimitiveProcesses_.end()) { + ownedAnimPrimitiveProcesses_.erase(animation); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -526,6 +667,12 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) { throw std::logic_error("key daemon process teardown is not ported"); } + if (controllerProcess_ != nullptr && entry == &controllerProcess_->base) { + throw std::logic_error("controller process teardown is not ported"); + } + const bool ownedAnimationProcess = std::any_of(ownedAnimPrimitiveProcesses_.begin(), + ownedAnimPrimitiveProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); const bool ownedGravityProcess = readLe16(*entry, 0x00) == 0x0610 && @@ -534,12 +681,13 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) 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 && !ownedGravityProcess || id < 3 || + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && + !ownedGravityProcess && !ownedAnimationProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } - if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && + if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); @@ -928,4 +1076,57 @@ bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector return true; } +bool ProcessKernel::queuePendingKeyEvent(const KeyEvent& event) +{ + if ((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size() == keyEventOffset_) { + pendingKeyEventOverflowed_ = true; + return false; + } + pendingKeyEvents_[nextKeyEventOffset_] = event; + nextKeyEventOffset_ = static_cast((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size()); + return true; +} + +std::optional ProcessKernel::popPendingKeyEvent() +{ + if (keyEventOffset_ == nextKeyEventOffset_) { + return std::nullopt; + } + const KeyEvent event = pendingKeyEvents_[keyEventOffset_]; + keyEventOffset_ = static_cast((keyEventOffset_ + 1) % pendingKeyEvents_.size()); + pendingKeyEventOverflowed_ = false; + return event; +} + +u8 ProcessKernel::pendingKeyEventCount() const +{ + return static_cast((nextKeyEventOffset_ + pendingKeyEvents_.size() - keyEventOffset_) % + pendingKeyEvents_.size()); +} + +bool ProcessKernel::pendingKeyEventOverflowed() const +{ + return pendingKeyEventOverflowed_; +} + +void ProcessKernel::dispatchPendingKeyEvents( + void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context) +{ + while (auto event = popPendingKeyEvent()) { + const std::size_t subscriberCount = keyboardSubscriberIds_.size(); + for (std::size_t index = 0; index < subscriberCount; ++index) { + const u16 id = keyboardSubscriberIds_[index]; + auto* process = processAt(id); + if (!process || allocationSizeAt(id) < 0x34 || + (readLe16(*process, 0x16) & 0x08) != 0 || + (readLe16(*process, 0x18) & 0x180) != 0x80 || + (reinterpret_cast(process)[0x32] & 0x10) == 0) { + continue; + } + KeyEvent copy = *event; + deliver(*process, 0x10, 0, copy, context); + } + } +} + } // namespace remorse diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 79d4fa5..c13b6fa 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -1,4 +1,5 @@ #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" @@ -153,6 +154,23 @@ std::optional> stageFixedMapItems(const FixedMap return items; } +std::optional findTeleportEgg( + const std::vector& items, const std::vector& shapes, u8 eggId) +{ + std::optional match; + for (const auto& item : items) { + if (item.data.shape >= shapes.size() || shapes[item.data.shape].family != 8 || + item.data.frame != 1 || (item.data.quality & 0xff) != eggId) { + continue; + } + if (match) { + return std::nullopt; + } + match = item; + } + return match; +} + std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes) { @@ -415,7 +433,7 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& LiveFixedMapItems::LiveFixedMapItems(std::vector items, std::vector containedItems) - : items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800) + : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800) { if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); @@ -439,8 +457,36 @@ LiveFixedMapItems::LiveFixedMapItems(std::vector items, } } +bool LiveFixedMapItems::initializeAvatar() +{ + if (avatar_) { + return false; + } + avatar_.emplace(); + avatar_->itemNumber = 1; + avatar_->data.shape = 1; + avatar_->data.npcNumber = 1; + npcAnimations_.resize(2); + return true; +} + +bool LiveFixedMapItems::teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber) +{ + if (!avatar_) { + return false; + } + avatar_->data.x = egg.data.x; + avatar_->data.y = egg.data.y; + avatar_->data.z = egg.data.z; + avatar_->data.mapNumber = mapNumber; + return true; +} + const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const { + if (itemNumber == 1) { + return avatar_ ? &*avatar_ : nullptr; + } for (const auto& item : items_) { if (item.itemNumber == itemNumber) { return &item; @@ -449,6 +495,19 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const return nullptr; } +const NpcAnimationState* LiveFixedMapItems::findNpcAnimation(u16 itemNumber) const +{ + const auto* item = findItem(itemNumber); + return itemNumber < npcAnimations_.size() && item != nullptr && item->data.npcNumber != 0 + ? &npcAnimations_[itemNumber] : nullptr; +} + +NpcAnimationState* LiveFixedMapItems::editNpcAnimation(u16 itemNumber) +{ + return const_cast( + static_cast(this)->findNpcAnimation(itemNumber)); +} + u16 LiveFixedMapItems::containedParent(u16 itemNumber) const { return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; @@ -517,11 +576,64 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) return true; } +std::optional> LiveFixedMapItems::hatchGlobEgg(u16 eggItemNumber, + const GlobObject& glob, const std::vector& shapes) +{ + const auto* egg = findItem(eggItemNumber); + if (!egg || egg->data.shape >= shapes.size() || shapes[egg->data.shape].family != 3 || + egg->data.quality == 0 || egg->data.quality != glob.index || + isGlobHatched(eggItemNumber)) { + return std::nullopt; + } + std::vector children; + children.reserve(glob.entries.size()); + for (const auto& entry : glob.entries) { + StagedFixedMapItem child; + child.recordIndex = static_cast(-1); + child.data.x = static_cast((egg->data.x & ~0x1ff) + entry.x * 2 + 1); + child.data.y = static_cast((egg->data.y & ~0x1ff) + entry.y * 2 + 1); + child.data.z = static_cast(egg->data.z + entry.z); + child.data.shape = entry.shape; + child.data.frame = entry.frame; + child.data.flags = 0x82; + if (entry.shape == 0 || child.data.x > 0x7fff || child.data.y > 0x7fff) { + return std::nullopt; + } + children.push_back(child); + } + const std::size_t freeCount = static_cast(std::count( + allocatedIds_.begin() + nextFreeItemNumber_, allocatedIds_.end(), false)); + if (freeCount < children.size()) { + return std::nullopt; + } + std::vector childIds; + childIds.reserve(children.size()); + for (auto& child : children) { + childIds.push_back(*allocateItem(child)); + } + hatchedGlobIds_[eggItemNumber] = true; + return childIds; +} + +bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const +{ + return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber]; +} + bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) { if (x > 0x7fff || y > 0x7fff) { return false; } + if (itemNumber == 1) { + if (!avatar_) { + return false; + } + avatar_->data.x = x; + avatar_->data.y = y; + avatar_->data.z = std::min(z, 0xfa); + return true; + } const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { return candidate.itemNumber == itemNumber; }); diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index 8f2a84b..568131d 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -39,7 +39,7 @@ struct SceneItem { struct RenderNode { SceneItem item; - DecodedShapeFrame decoded; + const DecodedShapeFrame* decoded = nullptr; s32 left = 0; s32 top = 0; s32 right = 0; @@ -82,14 +82,27 @@ std::vector collectSceneItems( const FixedMap& fixedMap, const std::vector& typeFlags, const std::vector& globs, - const MapRenderOptions& options) + const MapRenderOptions& options, + const LiveFixedMapItems* liveItems) { std::vector pending; pending.reserve(fixedMap.entries.size()); - for (const FixedMapEntry& entry : fixedMap.entries) { + std::vector liveByRecord; + if (liveItems != nullptr) { + liveByRecord.resize(fixedMap.entries.size(), nullptr); + for (const auto& item : liveItems->mapItems()) { + if (item.recordIndex < liveByRecord.size()) { + liveByRecord[item.recordIndex] = &item; + } + } + } + for (std::size_t recordIndex = 0; recordIndex < fixedMap.entries.size(); ++recordIndex) { + const FixedMapEntry& entry = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr + ? fixedMap.entries[recordIndex] : liveByRecord[recordIndex]->data; + const s32 scale = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr ? 1 : 2; pending.push_back(SceneItem{ - static_cast(entry.x), - static_cast(entry.y), + static_cast(entry.x) * scale, + static_cast(entry.y) * scale, static_cast(entry.z), entry.shape, entry.frame, @@ -98,6 +111,16 @@ std::vector collectSceneItems( entry.mapNumber, true}); } + if (liveItems != nullptr) { + for (const auto& item : liveItems->mapItems()) { + if (item.recordIndex == static_cast(-1)) { + pending.push_back(SceneItem{static_cast(item.data.x) * 2, + static_cast(item.data.y) * 2, item.data.z, item.data.shape, + item.data.frame, item.data.flags, item.data.quality, item.data.mapNumber, + false}); + } + } + } std::vector items; for (std::size_t index = 0; index < pending.size(); ++index) { @@ -116,7 +139,10 @@ std::vector collectSceneItems( continue; } if (options.expandGlobs && info.family == 3 && item.fromFixed) { - const auto glob = findGlobObject(globs, item.quality); + const auto* stagedEgg = liveByRecord.empty() || index >= liveByRecord.size() + ? nullptr : liveByRecord[index]; + const auto glob = stagedEgg && liveItems->isGlobHatched(stagedEgg->itemNumber) + ? std::nullopt : findGlobObject(globs, item.quality); if (glob) { for (const GlobObjectEntry& entry : glob->entries) { pending.push_back(SceneItem{ @@ -153,7 +179,7 @@ s32 screenY(const SceneItem& item) return projectToScreen(WorldPoint{item.x, item.y, item.z}).y; } -std::optional cachedDecode( +const DecodedShapeFrame* cachedDecode( const ShapeArchive& archive, std::map, DecodedShapeFrame>& cache, u32 shape, @@ -162,28 +188,27 @@ std::optional cachedDecode( const auto key = std::make_pair(shape, frame); const auto found = cache.find(key); if (found != cache.end()) { - return found->second; + return &found->second; } const auto decoded = decodeShapeFrame(archive, shape, frame); if (!decoded) { - return std::nullopt; + return nullptr; } - cache.emplace(key, *decoded); - return decoded; + return &cache.emplace(key, std::move(*decoded)).first->second; } std::vector prepareRenderNodes( const std::vector& items, const ShapeArchive& shapeArchive, - const std::vector& typeFlags) + const std::vector& typeFlags, + std::map, DecodedShapeFrame>& cache) { - std::map, DecodedShapeFrame> cache; std::vector nodes; std::vector sortItems; nodes.reserve(items.size()); sortItems.reserve(items.size()); for (const SceneItem& item : items) { - const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); + const auto* decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); if (!decoded) { continue; } @@ -193,13 +218,13 @@ std::vector prepareRenderNodes( const bool flipped = (item.flags & flagFlipped) != 0; RenderNode node; node.item = item; - node.decoded = *decoded; + node.decoded = decoded; node.left = flipped - ? bottomX + node.decoded.frame.xOffset - static_cast(node.decoded.frame.width) - : bottomX - node.decoded.frame.xOffset; - node.top = bottomY - node.decoded.frame.yOffset; - node.right = node.left + static_cast(node.decoded.frame.width); - node.bottom = node.top + static_cast(node.decoded.frame.height); + ? bottomX + decoded->frame.xOffset - static_cast(decoded->frame.width) + : bottomX - decoded->frame.xOffset; + node.top = bottomY - decoded->frame.yOffset; + node.right = node.left + static_cast(decoded->frame.width); + node.bottom = node.top + static_cast(decoded->frame.height); const ShapeTypeInfo& info = typeFlags[item.shape]; const s32 xDimension = static_cast(flipped ? info.y : info.x) * 32; @@ -251,15 +276,15 @@ std::vector prepareRenderNodes( void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette) { const bool flipped = (node.item.flags & flagFlipped) != 0; - for (u32 sourceY = 0; sourceY < node.decoded.frame.height; ++sourceY) { + for (u32 sourceY = 0; sourceY < node.decoded->frame.height; ++sourceY) { const s32 destY = node.top - image.sourceTop + static_cast(sourceY); if (destY < 0 || destY >= static_cast(image.height)) { continue; } - const std::size_t sourceRow = static_cast(sourceY) * node.decoded.frame.width; - for (u32 sourceX = 0; sourceX < node.decoded.frame.width; ++sourceX) { - const u32 actualSourceX = flipped ? node.decoded.frame.width - 1 - sourceX : sourceX; - const s16 colorIndex = node.decoded.pixels[sourceRow + actualSourceX]; + const std::size_t sourceRow = static_cast(sourceY) * node.decoded->frame.width; + for (u32 sourceX = 0; sourceX < node.decoded->frame.width; ++sourceX) { + const u32 actualSourceX = flipped ? node.decoded->frame.width - 1 - sourceX : sourceX; + const s16 colorIndex = node.decoded->pixels[sourceRow + actualSourceX]; if (colorIndex < 0 || colorIndex >= 256) { continue; } @@ -293,7 +318,7 @@ ScreenPoint projectToScreen(const WorldPoint& point) return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z}; } -std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) +std::optional loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex) { const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT"); const auto globPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "GLOB.FLX"); @@ -305,7 +330,7 @@ std::optional renderMapPreview(const GameDataRoot& root, const } const auto fixedArchive = loadFixedMapArchive(*fixedPath); - const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, options.mapIndex) : std::nullopt; + const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, mapIndex) : std::nullopt; const auto globs = loadGlobObjects(*globPath); const auto shapeArchive = loadShapeArchive(*shapePath); const auto palette = loadPalette256(*palettePath); @@ -313,9 +338,15 @@ std::optional renderMapPreview(const GameDataRoot& root, const if (!fixedMap || !globs || !shapeArchive || !palette || !typeFlags) { return std::nullopt; } + return MapSceneRenderer{std::move(*fixedMap), std::move(*globs), std::move(*shapeArchive), + *palette, std::move(*typeFlags), {}}; +} - const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options); - auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags); +std::optional MapSceneRenderer::render(const MapRenderOptions& options, + const LiveFixedMapItems* liveItems) +{ + const auto items = collectSceneItems(map, typeFlags, globs, options, liveItems); + auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames); if (nodes.empty()) { return std::nullopt; } @@ -332,7 +363,7 @@ std::optional renderMapPreview(const GameDataRoot& root, const } RenderedMapImage image; - image.rawItemCount = static_cast(fixedMap->entries.size()); + image.rawItemCount = static_cast(map.entries.size()); image.renderItemCount = static_cast(items.size()); image.decodedItemCount = static_cast(nodes.size()); image.fullWidth = maxRight - minLeft; @@ -361,12 +392,25 @@ std::optional renderMapPreview(const GameDataRoot& root, const node.top >= image.sourceTop + static_cast(image.height)) { continue; } - paintNode(image, node, *palette); + paintNode(image, node, palette); ++image.paintedItemCount; } return image; } +std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) +{ + auto renderer = loadMapSceneRenderer(root, options.mapIndex); + return renderer ? renderer->render(options) : std::nullopt; +} + +std::optional renderLiveMapPreview(const GameDataRoot& root, + const MapRenderOptions& options, const LiveFixedMapItems& items) +{ + auto renderer = loadMapSceneRenderer(root, options.mapIndex); + return renderer ? renderer->render(options, &items) : std::nullopt; +} + bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image) { if (image.width == 0 || image.height == 0 || image.pixels.size() != static_cast(image.width) * image.height) { diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp new file mode 100644 index 0000000..86d6d81 --- /dev/null +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -0,0 +1,29 @@ +#include "remorse/usecode_vm.h" + +#include + +namespace remorse { + +std::optional UsecodeInterpreterState::initialize( + const std::vector& itemParameter) +{ + if (itemParameter.size() > 0xcc) { + return std::nullopt; + } + UsecodeInterpreterState state; + state.stackTop -= itemParameter.size(); + std::copy(itemParameter.begin(), itemParameter.end(), + state.valueStack.begin() + state.stackTop); + return state; +} + +bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment) +{ + if (callFrameCount >= 0x1f) { + return false; + } + callFrames[callFrameCount++] = UsecodeCallFrame{offset, segment}; + return true; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 345d6a7..6027077 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -43,10 +44,13 @@ constexpr remorse::s32 diagnosticItemRange = 48; struct AppState { remorse::GameDataRoot root; remorse::u32 mapIndex = 1; + bool diagnostics = false; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; + remorse::ControllerMovementState controllerMovement; + remorse::u16 animationProcessId = 0; std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; @@ -57,7 +61,11 @@ struct AppState { remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; std::mutex sceneMutex; + std::condition_variable renderWake; + bool renderRequested = false; + bool renderStop = false; std::optional scene; + std::optional renderer; std::optional standAnimation; std::optional walkAnimation; std::optional runAnimation; @@ -71,7 +79,6 @@ struct AppState { std::vector dibPixels; std::vector viewPixels; remorse::WorldPoint spawn{}; - remorse::WorldPoint playerWorld{}; remorse::FastAreaRange fastArea{}; remorse::s32 minWorldX = 0; remorse::s32 minWorldY = 0; @@ -86,6 +93,7 @@ struct AppState { std::wstring loadError; bool sceneLoaded = false; std::thread sceneThread; + std::thread renderThread; HDC backBufferDc = nullptr; HBITMAP backBufferBitmap = nullptr; HBITMAP previousBackBufferBitmap = nullptr; @@ -124,6 +132,16 @@ void setLoadFailure(AppState& state, const std::wstring& message) state.sceneLoaded = true; } +remorse::WorldPoint avatarWorld(const AppState& state) +{ + const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr; + return avatar ? remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z} + : state.spawn; +} + +bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, + const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); + void loadSceneAsync(HWND window, AppState& state) { state.sceneThread = std::thread([window, &state]() { @@ -153,6 +171,11 @@ void loadSceneAsync(HWND window, AppState& state) return; } const auto stagedItems = remorse::stageFixedMapItems(*map); + if (!stagedItems) { + setLoadFailure(state, L"The fixed-map item cache could not be initialized."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); const auto globObjects = remorse::loadGlobObjects(*globPath); @@ -249,13 +272,38 @@ void loadSceneAsync(HWND window, AppState& state) maxY = std::max(maxY, static_cast(entry.y)); } - const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0}; + const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); + if (state.mapIndex == 1 && !startingEgg) { + setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + if (state.mapIndex != 1 && !state.diagnostics) { + setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + const remorse::WorldPoint spawn = startingEgg + ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} + : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options; options.mapIndex = state.mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; options.viewCenter = spawn; - auto scene = remorse::renderMapPreview(state.root, options); + remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); + liveItems.initializeAvatar(); + remorse::StagedFixedMapItem diagnosticStart; + diagnosticStart.data.x = static_cast(spawn.x / 2); + diagnosticStart.data.y = static_cast(spawn.y / 2); + diagnosticStart.data.z = static_cast(spawn.z); + liveItems.teleportAvatar(startingEgg ? *startingEgg : diagnosticStart, + static_cast(state.mapIndex)); + auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); + if (renderer) { + hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); + } + auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt; if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); @@ -272,7 +320,6 @@ void loadSceneAsync(HWND window, AppState& state) { std::lock_guard lock(state.sceneMutex); state.spawn = spawn; - state.playerWorld = spawn; state.fastArea = remorse::calculateFastAreaRange(spawn); state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); state.collisionBodies = std::move(collisionBodies); @@ -286,15 +333,14 @@ void loadSceneAsync(HWND window, AppState& state) state.maxWorldX = maxX; state.maxWorldY = maxY; state.scene = std::move(scene); + state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); state.standAnimation = *standAnimation; state.walkAnimation = *walkAnimation; state.runAnimation = *runAnimation; state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; - if (stagedItems) { - state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems)); - } + state.liveItems.emplace(std::move(liveItems)); state.sceneLoaded = true; } } catch (const std::exception& error) { @@ -306,6 +352,78 @@ void loadSceneAsync(HWND window, AppState& state) }); } +bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, + const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range) +{ + std::vector eggIds; + for (const auto& item : items.mapItems()) { + if (item.data.shape < renderer.typeFlags.size() && + renderer.typeFlags[item.data.shape].family == 3 && + !items.isGlobHatched(item.itemNumber) && remorse::isWorldPointInFastArea( + item.data.x * 2, item.data.y * 2, range)) { + eggIds.push_back(item.itemNumber); + } + } + bool changed = false; + for (const remorse::u16 eggId : eggIds) { + const auto* egg = items.findItem(eggId); + const auto glob = std::find_if(renderer.globs.begin(), renderer.globs.end(), + [egg](const auto& object) { return object.index == egg->data.quality; }); + if (glob != renderer.globs.end()) { + changed = items.hatchGlobEgg(eggId, *glob, renderer.typeFlags).has_value() || changed; + } + } + return changed; +} + +void startLiveRenderer(HWND window, AppState& state) +{ + state.renderThread = std::thread([window, &state]() { + for (;;) { + std::optional snapshot; + remorse::WorldPoint center{}; + { + std::unique_lock lock(state.sceneMutex); + state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); + if (state.renderStop) { + return; + } + state.renderRequested = false; + snapshot.emplace(*state.liveItems); + center = avatarWorld(state); + } + remorse::MapRenderOptions options; + options.mapIndex = state.mapIndex; + options.maxWidth = backingWidth; + options.maxHeight = backingHeight; + options.viewCenter = center; + const remorse::s32 radius = static_cast( + backingWidth + backingHeight * 2 + 512); + options.worldRect = remorse::WorldRect{ + center.x - radius, center.y - radius, center.x + radius, center.y + radius}; + auto scene = state.renderer->render(options, &*snapshot); + if (!scene) { + continue; + } + std::vector pixels(scene->pixels.size() * 3); + for (std::size_t index = 0; index < scene->pixels.size(); ++index) { + pixels[index * 3] = scene->pixels[index].blue; + pixels[index * 3 + 1] = scene->pixels[index].green; + pixels[index * 3 + 2] = scene->pixels[index].red; + } + { + std::lock_guard lock(state.sceneMutex); + if (state.renderStop) { + return; + } + state.scene = std::move(scene); + state.dibPixels = std::move(pixels); + } + PostMessageW(window, sceneReadyMessage, 0, 0); + } + }); +} + void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font) { const int saved = SaveDC(device); @@ -316,41 +434,6 @@ void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLOR RestoreDC(device, saved); } -bool isKeyDown(int key) -{ - return (GetAsyncKeyState(key) & 0x8000) != 0; -} - -std::optional readMovementDirection() -{ - 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 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; -} - -bool isWalkRequested() -{ - remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; - if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01; - if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02; - return remorse::controllerWalkRequested(modifiers); -} - void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, int sourceLeft, int sourceTop, std::size_t viewStride) { @@ -377,10 +460,9 @@ void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, } const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame]; - const int actorX = static_cast(state.scene->width / 2) + - static_cast(std::lround(state.playerOffsetX)) - sourceLeft; - const int actorY = static_cast(state.scene->height / 2) + - static_cast(std::lround(state.playerOffsetY)) - sourceTop; + const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); + const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft; + const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop; const int spriteLeft = actorX + sprite.frame.xOffset; const int spriteTop = actorY + sprite.frame.yOffset; const bool flipped = remorse::isAnimationFrameFlipped(*metadata); @@ -507,10 +589,9 @@ void paintWindow(HWND window, AppState& state) const int viewWidth = std::min(clientWidth, static_cast(state.scene->width)); const int viewHeight = std::min(clientHeight, static_cast(state.scene->height)); - const int centeredLeft = static_cast(state.scene->width / 2) + - static_cast(std::lround(state.playerOffsetX)) - viewWidth / 2; - const int centeredTop = static_cast(state.scene->height / 2) + - static_cast(std::lround(state.playerOffsetY)) - viewHeight / 2; + const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); + const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2; + const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); @@ -525,6 +606,10 @@ void paintWindow(HWND window, AppState& state) static_cast(viewWidth) * 3); } compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); + if (!state.diagnostics) { + finishPaint(); + return; + } RECT hud{0, 0, viewWidth, 80}; HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29)); @@ -538,10 +623,11 @@ void paintWindow(HWND window, AppState& state) DeleteObject(hudLine); std::wostringstream label; + const remorse::WorldPoint playerWorld = avatarWorld(state); label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex - << L" X " << state.playerWorld.x - << L" Y " << state.playerWorld.y - << L" Z " << static_cast(state.playerWorld.z) + << L" X " << playerWorld.x + << L" Y " << playerWorld.y + << L" Z " << static_cast(playerWorld.z) << L" DIR " << std::setw(2) << static_cast(state.playerDirection) << L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE") << L" WASD / KEYPAD SHIFT RUN"; @@ -570,7 +656,7 @@ void paintWindow(HWND window, AppState& state) 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 = state.liveItems ? state.liveItems->nearestItem( - state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt; + playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; std::wostringstream itemStatus; @@ -603,10 +689,6 @@ void updatePlayer(HWND window, AppState& state) 0.0, 0.25); state.lastTick = now; - if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) { - DestroyWindow(window); - return; - } if (GetForegroundWindow() != window) { return; } @@ -616,11 +698,19 @@ void updatePlayer(HWND window, AppState& state) } state.simulationAccumulator += elapsed; - const auto direction = readMovementDirection(); bool changed = false; while (state.simulationAccumulator >= simulationTickSeconds) { state.simulationAccumulator -= simulationTickSeconds; + state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + auto& app = *static_cast(context); + if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { + app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); + } + }, &state); + const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); + if (state.diagnostics) { const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { @@ -664,53 +754,69 @@ void updatePlayer(HWND window, AppState& state) if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { ++state.standWakeCount; } - changed = true; - if (!direction) { + } + changed = changed || state.diagnostics; + if (movement.animation == 0) { + if (state.animationProcessId != 0) { + auto* process = state.diagnosticKernel.processAt(state.animationProcessId); + process->bytes[0x18] |= 4; + state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); + state.animationProcessId = 0; + } changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; continue; } - const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3; + const remorse::u8 requestedAnimation = movement.animation; const remorse::AnimationClip& clip = requestedAnimation == 1 ? *state.walkAnimation : *state.runAnimation; - if (state.playerAnimation != requestedAnimation) { - state.playerAnimation = requestedAnimation; - state.playerFrame = 0; - } else { - state.playerFrame = static_cast( - (state.playerFrame + 1) % clip.frameCount); - } - state.playerDirection = *direction; - - const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame); - if (metadata) { - const auto step = remorse::hostMovementStep( - *metadata, state.playerDirection, (clip.header[2] & 0x10) != 0); - if (step) { - const remorse::WorldPoint destination{ - state.playerWorld.x + step->x, - state.playerWorld.y + step->y, - state.playerWorld.z + step->z}; - const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination); - const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); - const double nextOffsetX = destinationScreen.x - spawnScreen.x; - const double nextOffsetY = destinationScreen.y - spawnScreen.y; - const bool withinMapBounds = destination.x >= state.minWorldX && - destination.x <= state.maxWorldX && destination.y >= state.minWorldY && - destination.y <= state.maxWorldY; - const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 && - std::abs(nextOffsetY) <= backingHeight / 2 - 16; - if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody( - state.playerCollisionBody, destination, state.collisionBodies)) { - state.playerWorld = destination; - state.fastArea = remorse::calculateFastAreaRange(destination); - state.playerCollisionBody.location = destination; - state.playerOffsetX = nextOffsetX; - state.playerOffsetY = nextOffsetY; - } + if (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation || + state.playerDirection != movement.direction) { + if (state.animationProcessId != 0) { + auto* process = state.diagnosticKernel.processAt(state.animationProcessId); + process->bytes[0x18] |= 4; + state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); } + auto* process = state.diagnosticKernel.createAnimPrimitiveProcess( + state.diagnosticKernel.activeGroup(), 1, requestedAnimation, movement.direction, + clip, state.diagnosticGroupCounts); + state.animationProcessId = static_cast(process->base.bytes[2] | + (static_cast(process->base.bytes[3]) << 8)); + state.diagnosticKernel.startAnimPrimitiveProcess(state.animationProcessId, *state.liveItems, clip); + state.playerAnimation = requestedAnimation; + } + state.playerDirection = movement.direction; + const auto* avatar = state.liveItems->findItem(1); + const remorse::WorldPoint beforeMove{avatar->data.x, avatar->data.y, avatar->data.z}; + const auto fastArea = remorse::calculateFastAreaRange( + {avatar->data.x, avatar->data.y, avatar->data.z}); + state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), + [](remorse::EntityDispatchEntryBase& entry, void* context) { + auto& app = *static_cast(context); + if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) { + const remorse::AnimationClip& activeClip = app.playerAnimation == 1 + ? *app.walkAnimation : *app.runAnimation; + const auto* item = app.liveItems->findItem(1); + app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, + *app.liveItems, activeClip, app.shapeTypes, + remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z})); + } + }, &state); + state.fastArea = fastArea; + state.playerFrame = state.liveItems->findNpcAnimation(1)->frame; + const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(avatarWorld(state)); + const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); + state.playerOffsetX = destinationScreen.x - spawnScreen.x; + state.playerOffsetY = destinationScreen.y - spawnScreen.y; + const bool moved = avatar->data.x != beforeMove.x || avatar->data.y != beforeMove.y || + avatar->data.z != beforeMove.z; + const bool hatched = moved && hatchGlobsInFastArea( + *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); + if (state.renderThread.joinable() && (moved || hatched)) { + state.renderRequested = true; + state.renderWake.notify_one(); } changed = true; } @@ -743,13 +849,47 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA updatePlayer(window, *state); } return 0; + case WM_KILLFOCUS: + state->controllerMovement.clear(); + while (state->diagnosticKernel.popPendingKeyEvent()) {} + return 0; case WM_KEYDOWN: - if (wParam == 'F') { + case WM_KEYUP: + if (wParam == VK_ESCAPE && message == WM_KEYDOWN) { + DestroyWindow(window); + return 0; + } + { + remorse::KeyEvent event{}; + event.scanCode = static_cast((lParam >> 16) & 0xff); + switch (wParam) { + case 'W': event.scanCode = 0x48; break; + case 'A': event.scanCode = 0x4b; break; + case 'S': event.scanCode = 0x50; break; + case 'D': event.scanCode = 0x4d; break; + case 'Q': event.scanCode = 0x47; break; + case 'E': event.scanCode = 0x49; break; + case 'Z': event.scanCode = 0x4f; break; + case 'C': event.scanCode = 0x51; break; + } + event.modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; + if (GetKeyState(VK_NUMLOCK) & 1) event.modifiers |= 0x20; + if ((lParam & (1L << 24)) != 0 || wParam == 'W' || wParam == 'A' || + wParam == 'S' || wParam == 'D' || wParam == 'Q' || wParam == 'E' || + wParam == 'Z' || wParam == 'C') event.modifiers &= ~0x20; + if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; + if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; + event.field8 = message == WM_KEYDOWN ? 1 : 0; + state->diagnosticKernel.queuePendingKeyEvent(event); + } + if (message == WM_KEYUP) return 0; + if (state->diagnostics && wParam == 'F') { std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { + const remorse::WorldPoint playerWorld = avatarWorld(*state); state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( - state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt; + playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; } if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && @@ -764,7 +904,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA } return 0; case WM_CHAR: - if (wParam > 0 && wParam <= 0xff) { + if (state->diagnostics && wParam > 0 && wParam <= 0xff) { remorse::KeyEvent lastEvent{}; lastEvent.character = static_cast(wParam); lastEvent.scanCode = static_cast((lParam >> 16) & 0xff); @@ -785,6 +925,12 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA paintWindow(window, *state); return 0; case sceneReadyMessage: { + { + std::lock_guard lock(state->sceneMutex); + if (state->sceneLoaded && state->renderer && !state->renderThread.joinable()) { + startLiveRenderer(window, *state); + } + } InvalidateRect(window, nullptr, FALSE); return 0; } @@ -793,6 +939,14 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA if (state->sceneThread.joinable()) { state->sceneThread.join(); } + { + std::lock_guard lock(state->sceneMutex); + state->renderStop = true; + } + state->renderWake.notify_one(); + if (state->renderThread.joinable()) { + state->renderThread.join(); + } if (state->backBufferDc) { SelectObject(state->backBufferDc, state->previousBackBufferBitmap); DeleteObject(state->backBufferBitmap); @@ -811,11 +965,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo { remorse::installCrashDiagnostics(); remorse::u32 mapIndex = 1; - if (commandLine && *commandLine) { - wchar_t* end = nullptr; - const unsigned long parsed = std::wcstoul(commandLine, &end, 0); - if (end != commandLine && parsed <= 255) { - mapIndex = static_cast(parsed); + bool diagnostics = false; + std::wistringstream arguments(commandLine ? commandLine : L""); + std::wstring argument; + while (arguments >> argument) { + if (argument == L"--diagnostics") { + diagnostics = true; + } else { + wchar_t* end = nullptr; + const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0); + if (end != argument.c_str() && *end == L'\0' && parsed <= 255) { + mapIndex = static_cast(parsed); + } } } @@ -835,13 +996,17 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo AppState state; state.root = *root; state.mapIndex = mapIndex; + state.diagnostics = diagnostics; for (int index = 0; index < 3; ++index) { state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts); } state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts); state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts); - state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); - state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); + state.diagnosticKernel.createControllerProcess(1, state.diagnosticGroupCounts); + if (diagnostics) { + state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); + state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); + } WNDCLASSEXW windowClass{}; windowClass.cbSize = sizeof(windowClass); @@ -859,7 +1024,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo RECT bounds{0, 0, initialClientWidth, initialClientHeight}; AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW, + HWND window = CreateWindowExW(0, windowClassName, + diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test", + WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr, instance, &state); if (!window) { diff --git a/rebuild/remorse/tests/animation_archive_tests.cpp b/rebuild/remorse/tests/animation_archive_tests.cpp index 6795822..b88fae4 100644 --- a/rebuild/remorse/tests/animation_archive_tests.cpp +++ b/rebuild/remorse/tests/animation_archive_tests.cpp @@ -100,6 +100,29 @@ int main() assert(stand.has_value() && stand->frameCount > 0); assert(walk.has_value() && walk->frameCount == 17); assert(run.has_value() && run->frameCount == 12); + for (const remorse::AnimationClip* clip : {&*walk, &*run}) { + assert(clip->header[1] == 5); + for (remorse::u8 direction = 0; direction < 16; ++direction) { + for (remorse::u8 frame = 1; frame < clip->frameCount; ++frame) { + const auto metadata = remorse::getAnimationFrame(*clip, direction, frame); + assert(metadata && (metadata->bytes[5] & 2) != 0); + } + } + } + auto startClip = *walk; + startClip.header[1] = 1; + assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 8); + assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 0); + startClip.header[1] = 5; + assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 16); + startClip.header[1] = 4; + assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 0); + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 1); + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 3) == 2); + assert(remorse::selectAnimationStartFrame(startClip, false, true, false, false, 0) == 2); + assert(remorse::selectAnimationStartFrame(startClip, false, true, false, true, 2) == 2); + startClip.header[1] = 0; + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 0); assert(remorse::getAnimationFrame(*walk, 0, 0).has_value()); assert(remorse::getAnimationFrame(*run, 15, 11).has_value()); for (remorse::u8 direction : {remorse::u8{6}, remorse::u8{7}, remorse::u8{10}, remorse::u8{11}}) { diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 4d16f58..177f96f 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,6 +1,8 @@ +#include "remorse/animation_archive.h" #include "remorse/collision.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/fixed_map.h" +#include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" @@ -877,8 +879,139 @@ int main() assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); keyboardEvent.character = 0x41; assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); + remorse::ProcessKernel inputKernel; + assert(!inputKernel.popPendingKeyEvent()); + for (remorse::u8 index = 0; index < 31; ++index) { + remorse::KeyEvent queued{}; + queued.scanCode = index; + assert(inputKernel.queuePendingKeyEvent(queued)); + } + assert(inputKernel.pendingKeyEventCount() == 31); + assert(!inputKernel.queuePendingKeyEvent({})); + assert(inputKernel.pendingKeyEventOverflowed()); + for (remorse::u8 index = 0; index < 31; ++index) { + const auto queued = inputKernel.popPendingKeyEvent(); + assert(queued && queued->scanCode == index); + } + assert(inputKernel.pendingKeyEventCount() == 0 && !inputKernel.pendingKeyEventOverflowed()); + remorse::KeyEvent wrapped{}; + wrapped.scanCode = 0x47; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + assert(inputKernel.popPendingKeyEvent()->scanCode == 0x47); + remorse::u16 inputGroups[32]{}; + auto* inputKeyboard = inputKernel.createKeyboardProcess(1, inputGroups); + auto* inputController = inputKernel.createControllerProcess(1, inputGroups); + assert(inputController && inputController->base.bytes[0x00] == 0xa6 && + inputController->base.bytes[0x01] == 0x3a); + assert(inputController->base.bytes[0x17] == 0x03 && inputController->extra[4] == 0x3c); + assert(!inputKeyboard->extra[0]); + assert(inputKernel.queuePendingKeyEvent(wrapped)); + wrapped.scanCode = 0x48; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + std::vector deliveredScans; + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + assert(selector == 0x10 && filter == 0); + assert(process.bytes[0x00] == 0xa6); + static_cast*>(context)->push_back(event.scanCode); + }, &deliveredScans); + assert((deliveredScans == std::vector{0x47, 0x48})); + assert(inputKernel.pendingKeyEventCount() == 0); + remorse::ControllerMovementState deliveredMovement; + wrapped.scanCode = 0x48; + wrapped.field8 = 1; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + assert(process.bytes[0] == 0xa6 && selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + }, &deliveredMovement); + assert(deliveredMovement.request().animation == 1 && deliveredMovement.request().direction == 14); + wrapped.field8 = 0; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, + remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) { + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + }, &deliveredMovement); + assert(deliveredMovement.request().animation == 0); assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0); assert(keyboard->extra[0] == 0x21); + remorse::ProcessKernel animationKernel; + remorse::u16 animationGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + animationKernel.createProcess(1, animationGroups); + } + remorse::AnimationClip walking{}; + walking.header = {17, 4, 0, 0}; + walking.frameCount = 17; + auto* animation = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.processAt(3) == &animation->base); + assert(animationKernel.allocationSizeAt(3) == 0x5b && animationGroups[1] == 4); + assert(animationKernel.findProcessForItemAndType(1, 0xf0) == &animation->base); + assert(animation->base.bytes[0] == 0x57 && animation->base.bytes[1] == 0x2a); + assert(animation->base.bytes[0x16] == 0 && animation->base.bytes[0x17] == 0x08); + assert(animation->extra[0] == 1 && animation->extra[4] == 1 && animation->extra[6] == 6); + assert(animation->extra[7] == 17 && animation->extra[0x18] == 17 && animation->extra[0x19] == 4); + remorse::LiveFixedMapItems animationItems({}); + assert(animationItems.initializeAvatar()); + assert(animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); + const auto* npcAnimation = animationItems.findNpcAnimation(1); + assert(npcAnimation && npcAnimation->lastAnimation == 1 && npcAnimation->frame == 0); + assert(!animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); + auto* repeatedWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(4, animationItems, walking)); + assert(repeatedWalk->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 1); + auto* turning = animationKernel.createAnimPrimitiveProcess(1, 1, 0, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(5, animationItems, walking)); + assert(turning->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 0); + remorse::StagedFixedMapItem animationSpawn{}; + animationSpawn.data.x = 512; + animationSpawn.data.y = 512; + assert(animationItems.teleportAvatar(animationSpawn, 1)); + walking.frames.resize(17 * 8); + auto& nextWalkFrame = walking.frames[3 * 17 + 1]; + nextWalkFrame.bytes[4] = 1; + nextWalkFrame.bytes[5] = 2; + std::vector animationShapes(2); + animationShapes[1].x = animationShapes[1].y = animationShapes[1].z = 2; + auto& movingNpc = *animationItems.editNpcAnimation(1); + movingNpc.lastAnimation = 1; + movingNpc.frame = 0; + const auto animationArea = remorse::calculateFastAreaRange({512, 512, 0}); + assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems, + walking, animationShapes, animationArea) == true); + assert(animationItems.findItem(1)->data.x == 514 && animationItems.findItem(1)->data.y == 514); + assert(movingNpc.frame == 1); + nextWalkFrame.bytes[4] = 100; + movingNpc.frame = 0; + remorse::StagedFixedMapItem animationWall{}; + animationWall.itemNumber = 0x100; + animationWall.data.shape = 2; + animationWall.data.x = 650; + animationWall.data.y = 650; + animationShapes.push_back(animationShapes[1]); + animationShapes[2].flags = 2; + assert(animationItems.insertItem(animationWall)); + assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems, + walking, animationShapes, animationArea) == false); + assert(animationItems.findItem(1)->data.x == 514 && movingNpc.frame == 0); + assert(animation->extra[0x0a] == 1); + walking.header[1] = 5; + nextWalkFrame.bytes[4] = 1; + auto* twoStepWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(6, animationItems, walking)); + assert(movingNpc.frame == 8 && twoStepWalk->extra[7] == 17); + movingNpc.frame = 16; + assert(animationKernel.advanceGroundedAnimPrimitive(6, animationItems, + walking, animationShapes, animationArea) == true); + assert(movingNpc.frame == 1 && animationItems.findItem(1)->data.x == 516); + twoStepWalk->base.bytes[0x18] |= 4; + animationKernel.terminateProcess(6, animationGroups); + assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0); + assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1)); + return 0; } diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index bd81532..9be0fa8 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -1,6 +1,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" @@ -235,6 +236,24 @@ int main() assert(allocatedItems.allocateItem(newItem) == 0x107); newItem.data.x = 0x8000; assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); + remorse::StagedFixedMapItem globEgg; + globEgg.itemNumber = 0x100; + globEgg.data.x = 0x403; + globEgg.data.y = 0x601; + globEgg.data.z = 12; + globEgg.data.shape = 3; + globEgg.data.quality = 7; + remorse::LiveFixedMapItems hatchedItems({globEgg}); + std::vector globShapes(4); + globShapes[3].family = 3; + remorse::GlobObject glob{7, {{2, 5, 3, 1, 2}}}; + const auto childIds = hatchedItems.hatchGlobEgg(0x100, glob, globShapes); + assert(childIds && *childIds == std::vector{0x101}); + const auto* child = hatchedItems.findItem(0x101); + assert(child && child->recordIndex == static_cast(-1)); + assert(child->data.x == 0x405 && child->data.y == 0x60b && child->data.z == 15); + assert(child->data.flags == 0x82 && child->data.frame == 2); + assert(hatchedItems.isGlobHatched(0x100) && !hatchedItems.hatchGlobEgg(0x100, glob, globShapes)); remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -266,7 +285,18 @@ int main() candidate.itemNumber = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); assert(cachedItems->front().recordIndex < retailMap->entries.size()); - const remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + assert(!retailLiveItems.findItem(1)); + assert(retailLiveItems.initializeAvatar()); + assert(!retailLiveItems.initializeAvatar()); + assert(retailLiveItems.findItem(1)->data.shape == 1); + assert(retailLiveItems.findItem(1)->data.frame == 0); + assert(retailLiveItems.findItem(1)->data.npcNumber == 1); + assert(retailLiveItems.teleportAvatar(cachedItems->front(), 1)); + assert(retailLiveItems.findItem(1)->data.x == cachedItems->front().data.x); + assert(retailLiveItems.findItem(1)->data.mapNumber == 1); + assert(retailLiveItems.moveItem(1, 100, 200, 5)); + assert(retailLiveItems.findItem(1)->data.x == 100 && retailLiveItems.findItem(1)->data.y == 200); assert(retailLiveItems.findItem(cachedItems->front().itemNumber)->recordIndex == cachedItems->front().recordIndex); for (const auto& item : *cachedItems) { diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index dbb5900..a828602 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,8 +1,11 @@ +#include "remorse/collision.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" +#include "remorse/usecode_vm.h" #include #include @@ -69,6 +72,38 @@ int main() assert(fixedMap && typeFlags); const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); assert(stagedItems && !stagedItems->empty()); + const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); + assert(spawnEgg); + const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); + const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; + assert(globs); + remorse::LiveFixedMapItems spawnedItems(*stagedItems); + const auto fastArea = remorse::calculateFastAreaRange({ + spawnEgg->data.x * 2, spawnEgg->data.y * 2, spawnEgg->data.z}); + unsigned hatched = 0; + for (const auto& egg : *stagedItems) { + if (egg.data.shape >= typeFlags->size() || (*typeFlags)[egg.data.shape].family != 3 || + !remorse::isWorldPointInFastArea(egg.data.x * 2, egg.data.y * 2, fastArea)) continue; + for (const auto& glob : *globs) { + if (glob.index == egg.data.quality) { + const auto children = spawnedItems.hatchGlobEgg(egg.itemNumber, glob, *typeFlags); + if (children) hatched += static_cast(children->size()); + break; + } + } + } + unsigned scriptChildren = 0; + for (const auto& item : spawnedItems.mapItems()) { + if (item.recordIndex != static_cast(-1) || item.data.shape >= typeFlags->size()) continue; + const remorse::UsecodeItemIdentity childIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false}; + const auto use = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, childIdentity, + remorse::UsecodeClassBases{0, 0x800, 0x900}, 2, 1); + if (use) { + ++scriptChildren; + } + } + assert(hatched == 4 && scriptChildren == 0); const auto& staged = stagedItems->front(); assert(staged.data.shape < typeFlags->size()); const remorse::UsecodeItemIdentity stagedIdentity{staged.itemNumber, staged.data.shape, @@ -100,6 +135,18 @@ int main() rechargeItem, retailBases, 0x200, 9); assert(eligibleRelease && eligibleRelease->classId == 0x138 && eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102); + auto interpreter = remorse::UsecodeInterpreterState::initialize({0x00, 0x01}); + assert(interpreter && interpreter->stackTop == 0xca && interpreter->stackLimit == 199); + assert(interpreter->valueStack[0xca] == 0x00 && interpreter->valueStack[0xcb] == 0x01); + assert(interpreter->pushCodeAddress(eligibleRelease->classId, 9)); + assert(interpreter->callFrameCount == 1 && interpreter->callFrames[0].offset == 0x138 && + interpreter->callFrames[0].segment == 9); + for (unsigned index = 1; index < 0x1f; ++index) { + assert(interpreter->pushCodeAddress(static_cast(index), 0)); + } + assert(!interpreter->pushCodeAddress(0xffff, 0)); + assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0); + assert(!remorse::UsecodeInterpreterState::initialize(std::vector(0xcd))); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp index 7c8032f..a9bd432 100644 --- a/rebuild/remorse/tests/isometric_controls_tests.cpp +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -5,6 +5,22 @@ int main() { + remorse::ControllerMovementState controller; + assert(controller.request().animation == 0); + controller.handleDirectionalKey(0x48, 0, true); + assert(controller.request().animation == 1 && controller.request().direction == 14); + controller.handleDirectionalKey(0x4d, 1, true); + assert(controller.request().animation == 3 && controller.request().direction == 2); + controller.handleDirectionalKey(0x4d, 1, false); + assert(controller.request().animation == 3 && controller.request().direction == 14); + controller.handleDirectionalKey(0x48, 0, false); + assert(controller.request().animation == 0 && controller.request().direction == 14); + controller.handleDirectionalKey(0x49, 0x20, true); + assert(controller.request().animation == 0); + controller.handleDirectionalKey(0x47, 0x40, true); + assert(controller.request().animation == 3 && controller.request().direction == 12); + controller.clear(); + assert(controller.request().animation == 0); assert(remorse::controllerWalkRequested(0)); assert(!remorse::controllerWalkRequested(0x01)); assert(!remorse::controllerWalkRequested(0x02)); diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp index 987e88d..d4197da 100644 --- a/rebuild/remorse/tests/map_renderer_tests.cpp +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -1,10 +1,14 @@ +#include "remorse/collision.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/map_renderer.h" +#include "remorse/type_flags.h" #include #include #include +#include int main() { @@ -51,5 +55,100 @@ int main() const remorse::ScreenPoint center = remorse::projectToScreen(*options.viewCenter); assert(centeredImage->sourceLeft == center.x - static_cast(options.maxWidth / 2)); assert(centeredImage->sourceTop == center.y - static_cast(options.maxHeight / 2)); + + const auto typesPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); + assert(typesPath && globPath); + const auto shapeTypes = remorse::loadTypeFlags(*typesPath); + const auto globs = remorse::loadGlobObjects(*globPath); + assert(shapeTypes && shapeTypes->size() > 1 && globs); + const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); + assert(stagedItems); + const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); + assert(startingEgg && startingEgg->itemNumber >= 0x100); + assert((startingEgg->data.quality & 0xff) == 0x1e && startingEgg->data.frame == 1); + assert(startingEgg->data.x > 0 && startingEgg->data.y > 0); + assert(startingEgg->data.x * 2 == fixedMap->entries[startingEgg->recordIndex].x); + assert(startingEgg->data.y * 2 == fixedMap->entries[startingEgg->recordIndex].y); + const auto obstacles = remorse::collectMapCollisionBodies(*fixedMap, *shapeTypes, *globs); + const remorse::WorldPoint spawn{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z}; + options.maxWidth = 320; + options.maxHeight = 200; + options.viewCenter = spawn; + const auto startingScene = remorse::renderMapPreview(*root, options); + assert(startingScene && startingScene->paintedItemCount > 0); + remorse::LiveFixedMapItems liveSceneItems(*stagedItems); + auto cachedRenderer = remorse::loadMapSceneRenderer(*root, 1); + assert(cachedRenderer); + const auto liveBefore = cachedRenderer->render(options, &liveSceneItems); + const auto samePixels = [](const auto& left, const auto& right) { + return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(), + [](const auto& lhs, const auto& rhs) { + return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue; + }); + }; + assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels)); + const remorse::s32 redrawRadius = static_cast( + options.maxWidth + options.maxHeight * 2 + 512); + options.worldRect = remorse::WorldRect{spawn.x - redrawRadius, spawn.y - redrawRadius, + spawn.x + redrawRadius, spawn.y + redrawRadius}; + const auto boundedScene = cachedRenderer->render(options, &liveSceneItems); + assert(boundedScene && samePixels(boundedScene->pixels, liveBefore->pixels)); + options.worldRect.reset(); + const auto nearEgg = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) { + return item.data.shape < shapeTypes->size() && + (*shapeTypes)[item.data.shape].family == 3 && item.data.quality != 0 && + std::any_of(globs->begin(), globs->end(), [&](const auto& object) { + return object.index == item.data.quality; + }); + }); + assert(nearEgg != stagedItems->end()); + { + options.viewCenter = remorse::WorldPoint{ + nearEgg->data.x * 2, nearEgg->data.y * 2, nearEgg->data.z}; + const auto unhatchedScene = cachedRenderer->render(options, &liveSceneItems); + assert(unhatchedScene); + const auto glob = std::find_if(globs->begin(), globs->end(), [&](const auto& object) { + return object.index == nearEgg->data.quality; + }); + assert(glob != globs->end()); + const auto childIds = liveSceneItems.hatchGlobEgg(nearEgg->itemNumber, *glob, *shapeTypes); + assert(childIds && childIds->size() == glob->entries.size()); + const auto hatchedScene = cachedRenderer->render(options, &liveSceneItems); + assert(hatchedScene && samePixels(hatchedScene->pixels, unhatchedScene->pixels)); + for (const remorse::u16 childId : *childIds) { + const auto* child = liveSceneItems.findItem(childId); + assert(child && liveSceneItems.moveItem(childId, + static_cast(child->data.x + 512), + static_cast(child->data.y + 512), child->data.z)); + } + const auto movedScene = cachedRenderer->render(options, &liveSceneItems); + assert(movedScene && !samePixels(movedScene->pixels, hatchedScene->pixels)); + } + options.viewCenter = spawn; + auto visibleItem = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) { + if (item.data.shape >= shapeTypes->size() || (item.data.flags & 0x10) != 0 || + ((*shapeTypes)[item.data.shape].flags & 0x400) != 0) { + return false; + } + const auto family = (*shapeTypes)[item.data.shape].family; + if (family == 3 || family == 4 || family == 7 || family == 8) { + return false; + } + return true; + }); + assert(visibleItem != stagedItems->end()); + assert(liveSceneItems.moveItem(visibleItem->itemNumber, startingEgg->data.x, + startingEgg->data.y, 16)); + const auto liveAfter = cachedRenderer->render(options, &liveSceneItems); + assert(liveAfter && !samePixels(liveAfter->pixels, liveBefore->pixels)); + assert(!cachedRenderer->decodedFrames.empty()); + const auto actor = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); + bool canLeaveSpawn = false; + for (const auto [deltaX, deltaY] : {std::pair{32, 0}, {0, 32}, {-32, 0}, {0, -32}}) { + canLeaveSpawn |= remorse::canMoveCollisionBody(actor, + {spawn.x + deltaX, spawn.y + deltaY, spawn.z}, obstacles); + } + assert(canLeaveSpawn); return 0; }