diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index 7f3b30c..07ce5ef 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -55,6 +55,8 @@ Live runtime-helper classification added during the 2026-04-05 MCP-upgrade pass: - obtains the chunk through `UProcess_1420_0000` using the owner-row offset/size, materializes it through the owner-resource helper, and caches the returned far pointer in the slot entry - marks the chunk present through the slot-local state arrays and updates the runtime-wide budget counters - `GetSlotChunkPtrAtOffset` (`1420:1d72`) returns that allocator-produced pointer plus the caller's intra-chunk offset; it does not expose a stable file/archive address +- `ReleaseSlotChunkRef` (`1420:1d8d`) decrements a positive chunk-state reference count and asserts on an unretained chunk +- `TryUnloadSlotChunk` (`1420:1e17`) unloads only a zero-count chunk, restores its saved source pointer, resets the state to `0xffff`, and removes its loaded-list record - `1420:1f24 entity_vm_runtime_apply_to_matching_owner_rows` - runtime-owned iterator over the owner list, used both for broad cleanup and for filtered slot/category work - `1420:2040 entity_vm_slot_entry_create_or_clear` @@ -137,6 +139,8 @@ The embedded interpreter initializes its stack limit to 199 bytes; the host boot The host opcode service currently maps segment `0` to the task's item-memory buffer through `UsecodeProcessTask::readMappedItemWord`; all other segments are rejected. This centralizes the existing fixture behavior but is not a general segmented address space. +`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. `UsecodeSlotChunkCache` reads descriptors through this buffer, tracks ensure/release counts, and unloads only at count zero, restoring the state sentinel so a later ensure reloads the body. This remains an archive-backed host model: the 0x16-byte `UProcess_1420_0000` object, owner-helper materialization, runtime loaded-list record, and far-pointer allocation/restoration are not implemented. + Current caution: - context dispatch semantics are still active work, so this object should be modeled around lifecycle and data ownership first, not around final method names for every opcode-facing helper. diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 499ec8b..9be7b12 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -17,6 +17,7 @@ The exported files are evidence, not directly compilable game source. Keep them - 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 +Current progress correction: the long progress paragraph below predates the latest selector change. `E` now walks `itemGrabSearchCandidates` in source order and queues the first candidate with an eligible `use` event; it does not select the nearest eligible item. This remains host-side selection, not the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch. 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. @@ -712,8 +713,9 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat 4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. 5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. 6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Port `EnsureSlotChunkLoaded` (`1420:19fd`), its `UProcess_1420_0000` allocation and owner-helper materialization path, and the slot cache's far-pointer ownership. Then extend the host's segment-0 item-memory mapping to that runtime-owned code region, finish `CreateFromSlotIndex`/`Inter_1418_0244` context wiring, and execute one selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. +7. Complete runtime chunk materialization before context dispatch: extend the tested archive-backed `UsecodeSlotChunkCache` through `InitSlotOwnerBuffers`/`EnsureSlotChunkLoaded` (`1420:1866/19fd`), port the `0x16`-byte `UProcess_1420_0000` allocation and owner-helper materialization, then model loaded-list ownership, far-pointer restoration, release, and eviction. After that, map runtime-owned code into host VM memory, lift `CreateFromSlotIndex`/`Inter_1418_0244`, and execute a selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. ## Current Bottom Line +Runtime-cache progress correction: the host now models the extra-slot header, descriptor/state buffers, ensure/release counts, and archive-backed zero-count unload/reload. It still lacks `UProcess_1420_0000` allocation, owner-helper materialization, loaded-list ownership, and runtime far-pointer restoration; complete those prerequisites before far-address integration and the numbered context-dispatch action above. The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry runs an item process bound to a staged retail map record, queues an eligible release body into the subset VM, and runs a Stand entry under the host tick. Retail tests demonstrate script-driven item-frame mutation. The `E` selector now iterates bounded, source-order candidates from `itemGrabSearchCandidates` (the modeled `Item_Grab` query) and queues the first candidate with an eligible `use` body, replacing its earlier nearest-distance choice. This is source-derived candidate selection, not original interaction dispatch: the window still constructs the item identity and queues the event body directly, and no visible before/input/after interaction is proven. The partial `CreateFromSlotIndex` slice writes the verified slot index (`+0x32`), value offset (`+0x34`), owner-source far pointer (`+0x11b`), mode byte (`+0x121`), and cleared parameter/active fields (`+0x11f/+0x122`) into the allocated 0x124-byte context. The VM bootstrap now copies the item parameter only for nonzero mode flags, then optional context bytes, reserves the four-byte saved-stack-pointer slot, and records the context-relative parameter offset; focused tests cover the ordering and zero-mode case. Real segment:offset pointer mapping, runtime code/owner-resource addresses, and embedded interpreter-context execution remain unported. `F` remains a separate release diagnostic. The original item cache/block IDs, full `Item_Grab`/`Usecode_ItemCallEvent`/`CreateFromSlotIndex` chain, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, and renderer integration remain open. This is not a playable-game milestone; the next measure is mapping far addresses into the host VM and using them to execute one selected retail event through original context dispatch. diff --git a/rebuild/remorse/include/remorse/usecode_archive.h b/rebuild/remorse/include/remorse/usecode_archive.h index dc50820..4d7b136 100644 --- a/rebuild/remorse/include/remorse/usecode_archive.h +++ b/rebuild/remorse/include/remorse/usecode_archive.h @@ -11,16 +11,38 @@ namespace remorse { struct UsecodeClass { u32 classId = 0; std::string name; + u32 extraSlotCount = 0; u32 codeBase = 0; std::vector bytes; }; +struct UsecodeSlotOwnerBuffers { + std::vector descriptors; + std::vector chunkStates; +}; + struct UsecodeEventBody { u16 length = 0; u32 relativeOffset = 0; std::vector bytes; }; +class UsecodeSlotChunkCache { +public: + explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass); + const UsecodeEventBody* ensureLoaded(u16 chunkIndex); + bool release(u16 chunkIndex) noexcept; + bool tryUnload(u16 chunkIndex) noexcept; + u16 inUseCount(u16 chunkIndex) const noexcept; + std::size_t chunkCount() const noexcept { return chunks_.size(); } + const UsecodeSlotOwnerBuffers& ownerBuffers() const noexcept { return ownerBuffers_; } + +private: + UsecodeClass usecodeClass_; + UsecodeSlotOwnerBuffers ownerBuffers_; + std::vector> chunks_; +}; + struct UsecodeClassBases { u16 regularShape = 0; u16 npc = 0; @@ -46,6 +68,7 @@ u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBase std::optional> loadUsecodeOwnerRows(const FlexArchive& archive); bool ownerRowAllowsEvent(const std::vector& ownerRows, u16 classId, u32 eventMask); std::optional loadUsecodeClass(const FlexArchive& archive, u32 classId); +std::optional initializeUsecodeSlotOwnerBuffers(const UsecodeClass& usecodeClass); std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId); std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, const std::vector& ownerRows, const UsecodeItemIdentity& item, diff --git a/rebuild/remorse/src/usecode_archive.cpp b/rebuild/remorse/src/usecode_archive.cpp index a8fd2c2..dfbdb3c 100644 --- a/rebuild/remorse/src/usecode_archive.cpp +++ b/rebuild/remorse/src/usecode_archive.cpp @@ -16,6 +16,29 @@ u32 readDword(const std::vector& bytes, std::size_t offset) (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); } +std::optional readEventBodyFromDescriptors(const UsecodeClass& usecodeClass, + const std::vector& descriptors, std::size_t descriptorOffset, u32 eventId) +{ + if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() || + eventId >= (usecodeClass.codeBase - 20) / 6 || + descriptorOffset > descriptors.size() || descriptors.size() - descriptorOffset < + static_cast(eventId) * 6 + 6) { + return std::nullopt; + } + const std::size_t row = descriptorOffset + static_cast(eventId) * 6; + const u16 length = readWord(descriptors, row); + const u32 offset = readDword(descriptors, row + 2); + if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) { + return std::nullopt; + } + const std::size_t start = usecodeClass.codeBase + static_cast(offset) - 1; + if (length > usecodeClass.bytes.size() - start) { + return std::nullopt; + } + return UsecodeEventBody{length, offset, + std::vector(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)}; +} + } // namespace u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases) @@ -59,6 +82,7 @@ std::optional loadUsecodeClass(const FlexArchive& archive, u32 cla return std::nullopt; } const std::size_t nameOffset = 4 + static_cast(classId) * 13; + const u32 extraSlotCount = readDword(*bytes, 0); const u32 codeBase = readDword(*bytes, 8); if (codeBase < 20 || codeBase > bytes->size() || (codeBase - 20) % 6 != 0) { return std::nullopt; @@ -67,27 +91,103 @@ std::optional loadUsecodeClass(const FlexArchive& archive, u32 cla for (std::size_t index = 0; index < 9 && (*names)[nameOffset + index] != 0; ++index) { name.push_back(static_cast((*names)[nameOffset + index])); } - return UsecodeClass{classId, std::move(name), codeBase, std::move(*bytes)}; + return UsecodeClass{classId, std::move(name), extraSlotCount, codeBase, std::move(*bytes)}; +} + +std::optional initializeUsecodeSlotOwnerBuffers(const UsecodeClass& usecodeClass) +{ + constexpr std::size_t baseChunkCount = 0x20; + constexpr std::size_t baseDescriptorBytes = 0xc0; + constexpr std::size_t baseStateBytes = 0x40; + if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size()) { + return std::nullopt; + } + + const std::size_t chunkCount = baseChunkCount + usecodeClass.extraSlotCount; + const std::size_t descriptorBytes = baseDescriptorBytes + + static_cast(usecodeClass.extraSlotCount) * 6; + const std::size_t stateBytes = baseStateBytes + + static_cast(usecodeClass.extraSlotCount) * 2; + if (chunkCount != (usecodeClass.codeBase - 20) / 6 || + descriptorBytes != chunkCount * 6 || stateBytes != chunkCount * 2 || + descriptorBytes > usecodeClass.bytes.size() - 20) { + return std::nullopt; + } + + UsecodeSlotOwnerBuffers buffers; + buffers.descriptors.assign(usecodeClass.bytes.begin() + 20, + usecodeClass.bytes.begin() + 20 + descriptorBytes); + buffers.chunkStates.assign(stateBytes / 2, 0xffff); + return buffers; } std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId) { - if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() || - eventId >= (usecodeClass.codeBase - 20) / 6) { - return std::nullopt; + return readEventBodyFromDescriptors(usecodeClass, usecodeClass.bytes, 20, eventId); +} + +UsecodeSlotChunkCache::UsecodeSlotChunkCache(UsecodeClass usecodeClass) + : usecodeClass_(std::move(usecodeClass)) +{ + auto buffers = initializeUsecodeSlotOwnerBuffers(usecodeClass_); + if (buffers) { + ownerBuffers_ = std::move(*buffers); + chunks_.resize(ownerBuffers_.chunkStates.size()); } - const std::size_t row = 20 + static_cast(eventId) * 6; - const u16 length = readWord(usecodeClass.bytes, row); - const u32 offset = readDword(usecodeClass.bytes, row + 2); - if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) { - return std::nullopt; +} + +const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) +{ + if (chunkIndex >= chunks_.size()) { + return nullptr; } - const std::size_t start = usecodeClass.codeBase + static_cast(offset) - 1; - if (length > usecodeClass.bytes.size() - start) { - return std::nullopt; + auto& body = chunks_[chunkIndex]; + auto& state = ownerBuffers_.chunkStates[chunkIndex]; + if (!body) { + if (state != 0xffff) { + return nullptr; + } + auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex); + if (!loadedBody) { + return nullptr; + } + chunks_[chunkIndex] = std::move(*loadedBody); + state = 1; + } else { + if (state >= 29999) { + return nullptr; + } + ++state; } - return UsecodeEventBody{length, offset, - std::vector(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)}; + return &*chunks_[chunkIndex]; +} + +bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] == 0xffff || + ownerBuffers_.chunkStates[chunkIndex] == 0) { + return false; + } + --ownerBuffers_.chunkStates[chunkIndex]; + return true; +} + +bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0) { + return false; + } + chunks_[chunkIndex].reset(); + ownerBuffers_.chunkStates[chunkIndex] = 0xffff; + return true; +} + +u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] == 0xffff) { + return 0; + } + return ownerBuffers_.chunkStates[chunkIndex]; } std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index 0d04ad6..b020a0f 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -48,9 +48,53 @@ int main() assert(retailOwnerRows && retailOwnerRows->size() % 13 == 0); const auto eventClass = remorse::loadUsecodeClass(*usecode, 0x361); assert(eventClass && eventClass->name == "EVENT" && eventClass->codeBase == 0xd4); + assert(eventClass->extraSlotCount == 0); + const auto eventOwnerBuffers = remorse::initializeUsecodeSlotOwnerBuffers(*eventClass); + assert(eventOwnerBuffers && eventOwnerBuffers->descriptors.size() == 0xc0 && + eventOwnerBuffers->chunkStates.size() == 32); + assert(std::all_of(eventOwnerBuffers->chunkStates.begin(), eventOwnerBuffers->chunkStates.end(), + [](remorse::u16 state) { return state == 0xffff; })); + assert(std::equal(eventOwnerBuffers->descriptors.begin(), eventOwnerBuffers->descriptors.end(), + eventClass->bytes.begin() + 20)); + const auto npcTriggerClass = remorse::loadUsecodeClass(*usecode, 0x363); + assert(npcTriggerClass && npcTriggerClass->name == "NPCTRIG" && + npcTriggerClass->extraSlotCount == 1 && npcTriggerClass->codeBase == 0xda); + const auto npcTriggerOwnerBuffers = remorse::initializeUsecodeSlotOwnerBuffers(*npcTriggerClass); + assert(npcTriggerOwnerBuffers && npcTriggerOwnerBuffers->descriptors.size() == 0xc6 && + npcTriggerOwnerBuffers->chunkStates.size() == 33); + assert(std::all_of(npcTriggerOwnerBuffers->chunkStates.begin(), npcTriggerOwnerBuffers->chunkStates.end(), + [](remorse::u16 state) { return state == 0xffff; })); + assert(std::equal(npcTriggerOwnerBuffers->descriptors.begin(), npcTriggerOwnerBuffers->descriptors.end(), + npcTriggerClass->bytes.begin() + 20)); + auto inconsistentOwnerHeader = *eventClass; + inconsistentOwnerHeader.extraSlotCount = 1; + assert(!remorse::initializeUsecodeSlotOwnerBuffers(inconsistentOwnerHeader)); const auto eventBody = remorse::readUsecodeEventBody(*eventClass, 0x0a); assert(eventBody && eventBody->length == 0x1fd6 && eventBody->relativeOffset == 1); assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]); + remorse::UsecodeSlotChunkCache eventChunkCache(*eventClass); + assert(eventChunkCache.chunkCount() == 32); + const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes && + eventChunkCache.inUseCount(0x0a) == 1); + const auto* reusedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(reusedEventChunk == loadedEventChunk && eventChunkCache.inUseCount(0x0a) == 2); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 1); + assert(!eventChunkCache.tryUnload(0x0a)); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 0); + assert(!eventChunkCache.release(0x0a)); + assert(eventChunkCache.tryUnload(0x0a)); + assert(eventChunkCache.ownerBuffers().chunkStates[0x0a] == 0xffff); + const auto* reloadedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(reloadedEventChunk && reloadedEventChunk->bytes == eventBody->bytes && + eventChunkCache.inUseCount(0x0a) == 1); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 0); + for (remorse::u32 acquiredReferences = 0; acquiredReferences < 29999; ++acquiredReferences) { + assert(eventChunkCache.ensureLoaded(0x0a) == reloadedEventChunk); + } + assert(eventChunkCache.inUseCount(0x0a) == 29999); + assert(eventChunkCache.ensureLoaded(0x0a) == nullptr && eventChunkCache.inUseCount(0x0a) == 29999); + assert(eventChunkCache.ensureLoaded(0x20) == nullptr && eventChunkCache.inUseCount(0x20) == 0); assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); auto truncated = *eventClass;