#include "remorse/collision.h" #include "remorse/animation_archive.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/game_start.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" #include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" #include "remorse/usecode_vm.h" #include #include #include #include #include #include #include #include #include #include int main() { const auto hasRetailEventEntry = [](const std::vector& body, const std::array& prefix) { return body.size() > remorse::usecodeEventBytecodeOffset && std::equal(prefix.begin(), prefix.end(), body.begin()) && body[remorse::usecodeEventBytecodeOffset] == 0x0b; }; const auto readDescriptorPointer = [](const std::vector& descriptors, std::size_t chunkIndex) { const std::size_t offset = chunkIndex * 6 + 2; return static_cast(descriptors[offset]) | (static_cast(descriptors[offset + 1]) << 8) | (static_cast(descriptors[offset + 2]) << 16) | (static_cast(descriptors[offset + 3]) << 24); }; remorse::UsecodeRuntimeMemory boundedMemory; assert(!boundedMemory.allocate(0)); assert(!boundedMemory.allocate(0x10001)); const auto fullSegment = boundedMemory.allocate(0x10000, 0x5a); assert(fullSegment); const auto finalSegmentByte = boundedMemory.read({0xffff, fullSegment->segment}, 1); assert(finalSegmentByte && finalSegmentByte->size() == 1 && finalSegmentByte->front() == 0x5a); assert(!boundedMemory.read({0xffff, fullSegment->segment}, 2)); assert(!boundedMemory.read({0, 0xffff}, 1)); assert(boundedMemory.release(*fullSegment) && boundedMemory.allocationCount() == 0); const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); const auto combatPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "COMBAT.DAT"); assert(combatPath.has_value()); const auto archive = remorse::loadFlexArchive(*combatPath); assert(archive.has_value()); assert(archive->populatedEntries.size() == 14); const auto firstEntry = remorse::readFlexEntry(*archive, 0); assert(firstEntry.has_value()); assert(firstEntry->size() == 0x4f); assert((*firstEntry)[0] == 'D'); assert((*firstEntry)[1] == 'u'); assert((*firstEntry)[2] == 'm'); assert((*firstEntry)[3] == 'b'); const auto usecodePath = remorse::resolveGameDataPath(*root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); assert(usecodePath); const auto usecode = remorse::loadFlexArchive(*usecodePath); assert(usecode); const auto retailOwnerRows = remorse::loadUsecodeOwnerRows(*usecode); assert(retailOwnerRows && retailOwnerRows->size() % 13 == 0); const auto eventClass = remorse::loadUsecodeClass(*usecode, 0x361); assert(eventClass && eventClass->name == "EVENT" && eventClass->codeBase == 0xd4); 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)); remorse::UsecodeSlotChunkCache npcTriggerChunkCache(*npcTriggerClass); const auto originalNpcTriggerDescriptors = npcTriggerChunkCache.ownerBuffers().descriptors; std::optional npcTriggerChunkIndex; for (remorse::u16 chunkIndex = 0; chunkIndex < npcTriggerChunkCache.chunkCount(); ++chunkIndex) { if (npcTriggerChunkCache.ensureLoaded(chunkIndex)) { npcTriggerChunkIndex = chunkIndex; break; } } assert(npcTriggerChunkIndex); const auto npcTriggerSourcePointer = readDescriptorPointer( originalNpcTriggerDescriptors, *npcTriggerChunkIndex); const auto* loadedNpcTriggerProcess = npcTriggerChunkCache.loadedProcess(*npcTriggerChunkIndex); assert(loadedNpcTriggerProcess && loadedNpcTriggerProcess->layout.slotIndex == 0x363 && loadedNpcTriggerProcess->layout.chunkIndex == *npcTriggerChunkIndex && loadedNpcTriggerProcess->layout.savedSource.offset == static_cast(npcTriggerSourcePointer) && loadedNpcTriggerProcess->layout.savedSource.segment == static_cast(npcTriggerSourcePointer >> 16)); const auto loadedNpcTriggerBytes = npcTriggerChunkCache.runtimeMemory().read( loadedNpcTriggerProcess->layout.chunkBuffer, loadedNpcTriggerProcess->body.length); assert(loadedNpcTriggerBytes && *loadedNpcTriggerBytes == loadedNpcTriggerProcess->body.bytes && readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.offset) | (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.segment) << 16))); assert(npcTriggerChunkCache.release(*npcTriggerChunkIndex)); assert(npcTriggerChunkCache.tryUnload(*npcTriggerChunkIndex)); assert(npcTriggerChunkCache.loadedProcessCount() == 0 && npcTriggerChunkCache.runtimeMemory().allocationCount() == 0 && readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == npcTriggerSourcePointer); 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 sourceEventPointer = readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a); const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes && eventChunkCache.inUseCount(0x0a) == 1); const auto* loadedEventProcess = eventChunkCache.loadedProcess(0x0a); assert(loadedEventProcess && loadedEventProcess->layout.vtableOffset == 0x673c && loadedEventProcess->layout.slotIndex == 0x361 && loadedEventProcess->layout.chunkIndex == 0x0a && loadedEventProcess->layout.savedSource.offset == static_cast(sourceEventPointer) && loadedEventProcess->layout.savedSource.segment == static_cast(sourceEventPointer >> 16)); const auto loadedEventBytes = eventChunkCache.runtimeMemory().read( loadedEventProcess->layout.chunkBuffer, loadedEventProcess->body.length); assert(loadedEventBytes && *loadedEventBytes == loadedEventProcess->body.bytes && eventChunkCache.loadedListHead().offset == loadedEventProcess->processAddress.offset && eventChunkCache.loadedListHead().segment == loadedEventProcess->processAddress.segment && eventChunkCache.loadedProcessCount() == 1 && eventChunkCache.runtimeMemory().allocationCount() == 2); assert(readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == (static_cast(loadedEventProcess->layout.chunkBuffer.offset) | (static_cast(loadedEventProcess->layout.chunkBuffer.segment) << 16))); 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); assert(eventChunkCache.loadedProcessCount() == 0 && eventChunkCache.runtimeMemory().allocationCount() == 0 && eventChunkCache.loadedListHead().offset == 0 && eventChunkCache.loadedListHead().segment == 0 && readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == sourceEventPointer); 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); remorse::UsecodeClass syntheticOwnerClass; syntheticOwnerClass.classId = 0x123; syntheticOwnerClass.name = "SYNTHETIC"; syntheticOwnerClass.codeBase = 0xd4; syntheticOwnerClass.bytes.resize(syntheticOwnerClass.codeBase + 2); syntheticOwnerClass.bytes[20] = 1; syntheticOwnerClass.bytes[22] = 1; syntheticOwnerClass.bytes[26] = 1; syntheticOwnerClass.bytes[28] = 2; syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase] = 0xaa; syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase + 1] = 0xbb; remorse::UsecodeSlotChunkCache syntheticChunkCache(std::move(syntheticOwnerClass)); const auto syntheticSourceDescriptors = syntheticChunkCache.ownerBuffers().descriptors; const auto* firstSyntheticBody = syntheticChunkCache.ensureLoaded(0); const auto* secondSyntheticBody = syntheticChunkCache.ensureLoaded(1); assert(firstSyntheticBody && firstSyntheticBody->bytes == std::vector{0xaa} && secondSyntheticBody && secondSyntheticBody->bytes == std::vector{0xbb}); const auto* firstSyntheticProcess = syntheticChunkCache.loadedProcess(0); const auto* secondSyntheticProcess = syntheticChunkCache.loadedProcess(1); assert(firstSyntheticProcess && secondSyntheticProcess && secondSyntheticProcess->layout.previous.offset == firstSyntheticProcess->processAddress.offset && secondSyntheticProcess->layout.previous.segment == firstSyntheticProcess->processAddress.segment && firstSyntheticProcess->layout.next.offset == secondSyntheticProcess->processAddress.offset && firstSyntheticProcess->layout.next.segment == secondSyntheticProcess->processAddress.segment && syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment); const auto firstSyntheticSourcePointer = readDescriptorPointer( syntheticSourceDescriptors, 0); const auto secondSyntheticSourcePointer = readDescriptorPointer( syntheticSourceDescriptors, 1); assert(syntheticChunkCache.release(0) && syntheticChunkCache.tryUnload(0)); assert(syntheticChunkCache.loadedProcessCount() == 1 && syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment && syntheticChunkCache.loadedProcess(1)->layout.previous.offset == 0 && syntheticChunkCache.loadedProcess(1)->layout.previous.segment == 0 && readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 0) == firstSyntheticSourcePointer); assert(syntheticChunkCache.release(1) && syntheticChunkCache.tryUnload(1)); assert(syntheticChunkCache.loadedProcessCount() == 0 && syntheticChunkCache.runtimeMemory().allocationCount() == 0 && syntheticChunkCache.loadedListHead().offset == 0 && syntheticChunkCache.loadedListHead().segment == 0 && readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 1) == secondSyntheticSourcePointer); assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); auto truncated = *eventClass; truncated.bytes.resize(truncated.codeBase + 1); assert(!remorse::readUsecodeEventBody(truncated, 0x0a)); auto invalidOffset = *eventClass; invalidOffset.bytes[20 + 0x0a * 6 + 2] = 0; assert(!remorse::readUsecodeEventBody(invalidOffset, 0x0a)); const auto rechargeClass = remorse::loadUsecodeClass(*usecode, 0x138); assert(rechargeClass && rechargeClass->name == "RECHFLNS"); const auto releaseBody = remorse::readUsecodeEventBody(*rechargeClass, 9); assert(releaseBody && releaseBody->length == 102 && releaseBody->relativeOffset == 0x256); const std::array releasePrefix{ 0x5a, 0x02, 0x5c, 0x49, 0x00, 'R', 'E', 'C', 'H', 'F', 'L', 'N', 'S', 0x00}; assert(hasRetailEventEntry(releaseBody->bytes, releasePrefix)); assert(remorse::ownerRowAllowsEvent(*retailOwnerRows, 0x138, 0x200)); const remorse::UsecodeClassBases bases{0x200, 0x400, 0x600}; remorse::UsecodeItemIdentity identity{7, 0x45, 0, 0x1278, 4, true}; assert(remorse::selectUsecodeClassId(identity, bases) == 0x407); identity.status = 2; assert(remorse::selectUsecodeClassId(identity, bases) == 0x678); identity.family = 0; assert(remorse::selectUsecodeClassId(identity, bases) == 0x245); identity.isNpc = false; identity.status = 0; assert(remorse::selectUsecodeClassId(identity, bases) == 0x245); const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT"); const auto flagsPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); assert(fixedPath && flagsPath); const auto fixedArchive = remorse::loadFixedMapArchive(*fixedPath); const auto fixedMap = fixedArchive ? remorse::loadFixedMap(*fixedArchive, 1) : std::nullopt; const auto typeFlags = remorse::loadTypeFlags(*flagsPath); assert(fixedMap && typeFlags); const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); assert(stagedItems && !stagedItems->empty()); const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); assert(spawnEgg); remorse::LiveFixedMapItems spawnSearchWorld(*stagedItems); assert(spawnSearchWorld.initializeAvatar()); remorse::ProcessKernel teleporterKernel; remorse::u16 teleporterGroups[32]{}; for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { teleporterKernel.createProcess(1, teleporterGroups); } auto* startupTimer = teleporterKernel.createSystemTimerProcess(1, teleporterGroups); auto* startupKeyboard = teleporterKernel.createKeyboardProcess(1, teleporterGroups); auto* startupController = teleporterKernel.createControllerProcess(1, teleporterGroups); assert(startupTimer && startupKeyboard && startupController); const auto processIdOf = [](const auto& process) { return static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); }; const remorse::u16 startupTimerId = processIdOf(startupTimer); const remorse::u16 startupKeyboardId = processIdOf(startupKeyboard); const remorse::u16 startupControllerId = processIdOf(startupController); bool avatarInStasis = false; auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups, true, false, avatarInStasis); const remorse::u16 teleporterProcessId = static_cast( teleporterProcess->base.bytes[2] | (static_cast(teleporterProcess->base.bytes[3]) << 8)); const remorse::u16 clearStasisProcessId = static_cast(teleporterProcessId + 1); assert(avatarInStasis && clearStasisProcessId > startupControllerId && teleporterKernel.allocationSizeAt(clearStasisProcessId) == 0x33 && teleporterKernel.processAt(clearStasisProcessId)->bytes[0] == 0x5e && teleporterKernel.processAt(clearStasisProcessId)->bytes[1] == 0x0f); assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags)); assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); struct TeleporterPassContext { remorse::ProcessKernel& kernel; remorse::LiveFixedMapItems& items; const std::vector& shapes; remorse::u16 (&groupCounts)[32]; bool& avatarInStasis; bool teleported = false; } teleporterPass{teleporterKernel, spawnSearchWorld, *typeFlags, teleporterGroups, avatarInStasis}; const auto runTeleporterPass = [](remorse::EntityDispatchEntryBase& entry, void* opaque) { auto& context = *static_cast(opaque); const remorse::u16 processId = static_cast(entry.bytes[2] | (static_cast(entry.bytes[3]) << 8)); if (processId < 3) return; const remorse::u16 vtable = static_cast(entry.bytes[0] | (static_cast(entry.bytes[1]) << 8)); if (vtable == remorse::ClearAvatarInStasisProcess::vtableOffset) { assert(context.kernel.runClearAvatarInStasisProcess(processId, context.avatarInStasis, context.groupCounts)); } else if (vtable == remorse::TeleporterProcess::vtableOffset) { const auto& process = *reinterpret_cast(&entry); context.teleported = remorse::TeleporterProcess::run(process, context.items, 1, context.shapes); entry.bytes[0x18] |= 4; context.kernel.terminateProcess(processId, context.groupCounts); } }; teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); assert(!avatarInStasis && !teleporterPass.teleported && teleporterKernel.processAt(startupTimerId) == &startupTimer->base && teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base && teleporterKernel.processAt(startupControllerId) == &startupController->base && teleporterKernel.processAt(clearStasisProcessId) == nullptr && teleporterKernel.processAt(teleporterProcessId) == &teleporterProcess->base && spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); assert(teleporterPass.teleported); assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 6 && teleporterKernel.processAt(startupTimerId) == &startupTimer->base && teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base && teleporterKernel.processAt(startupControllerId) == &startupController->base); assert(spawnEgg->recordIndex < fixedMap->entries.size()); const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex]; const auto* spawnedAvatar = spawnSearchWorld.findItem(1); assert(spawnEgg->data.x == startingEggRecord.x / 2 && spawnEgg->data.y == startingEggRecord.y / 2 && spawnEgg->data.z == startingEggRecord.z); assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 && spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y && spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1); remorse::LiveFixedMapItems integratedStartupWorld(*stagedItems); assert(integratedStartupWorld.initializeAvatar()); remorse::ProcessKernel integratedStartupKernel; remorse::u16 integratedStartupGroups[32]{}; for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { integratedStartupKernel.createProcess(1, integratedStartupGroups); } auto* integratedTimer = integratedStartupKernel.createSystemTimerProcess(1, integratedStartupGroups); auto* integratedKeyboard = integratedStartupKernel.createKeyboardProcess(1, integratedStartupGroups); auto* integratedController = integratedStartupKernel.createControllerProcess(1, integratedStartupGroups); assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld, 1, 0x1e, *typeFlags, integratedStartupGroups)); const auto* integratedAvatar = integratedStartupWorld.findItem(1); assert(integratedTimer && integratedKeyboard && integratedController && integratedAvatar && integratedAvatar->data.x == spawnEgg->data.x && integratedAvatar->data.y == spawnEgg->data.y && integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 && integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base && integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base && integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base); const auto stagingTeleporter = remorse::findNearbyActiveTeleportEgg(*integratedAvatar, integratedStartupWorld.mapItems(), *typeFlags, 1); const auto levelStartEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x63); assert(stagingTeleporter && stagingTeleporter->itemNumber == 1598 && stagingTeleporter->data.shape == 0x0194 && stagingTeleporter->data.frame == 0 && stagingTeleporter->data.quality == 0x0063 && stagingTeleporter->data.mapNumber == 1 && levelStartEgg && levelStartEgg->itemNumber == 6812 && levelStartEgg->data.x == 30328 && levelStartEgg->data.y == 29656 && levelStartEgg->data.z == 16); assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld, stagingTeleporter->data.mapNumber, static_cast(stagingTeleporter->data.quality & 0xff), *typeFlags, integratedStartupGroups)); integratedAvatar = integratedStartupWorld.findItem(1); assert(integratedAvatar && integratedAvatar->data.x == levelStartEgg->data.x && integratedAvatar->data.y == levelStartEgg->data.y && integratedAvatar->data.z == levelStartEgg->data.z && integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 && integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base && integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base && integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base); remorse::LiveFixedMapItems freshGameWorld(*stagedItems); remorse::ProcessKernel freshGameKernel; remorse::u16 freshGameGroups[32]{}; for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { freshGameKernel.createProcess(1, freshGameGroups); } auto* freshGameTimer = freshGameKernel.createSystemTimerProcess(1, freshGameGroups); auto* freshGameKeyboard = freshGameKernel.createKeyboardProcess(1, freshGameGroups); auto* freshGameController = freshGameKernel.createControllerProcess(1, freshGameGroups); assert(remorse::startFreshGameMapOne(freshGameKernel, freshGameWorld, *typeFlags, freshGameGroups)); const auto* freshGameAvatar = freshGameWorld.findItem(1); const auto* expectedLevelStart = freshGameWorld.findItem(6812); assert(freshGameAvatar && expectedLevelStart && freshGameAvatar->data.x == expectedLevelStart->data.x && freshGameAvatar->data.y == expectedLevelStart->data.y && freshGameAvatar->data.z == expectedLevelStart->data.z && freshGameAvatar->data.mapNumber == 1 && freshGameGroups[1] == 6 && freshGameTimer && freshGameKeyboard && freshGameController && freshGameKernel.processAt(processIdOf(freshGameTimer)) == &freshGameTimer->base && freshGameKernel.processAt(processIdOf(freshGameKeyboard)) == &freshGameKeyboard->base && freshGameKernel.processAt(processIdOf(freshGameController)) == &freshGameController->base); remorse::ControllerActorState bootTickActor; bootTickActor.mapNumber = 1; bootTickActor.direction = 14; remorse::ControllerMovementState bootTickController; bootTickController.setActorState(bootTickActor); remorse::KeyEvent bootInput{}; bootInput.scanCode = 0x48; bootInput.field8 = 1; bootInput.field9 = 1; bootInput.fieldA = 1; assert(freshGameKernel.queuePendingKeyEvent(bootInput)); freshGameKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { static_cast(context)->handleKeyEvent( event.scanCode, event.modifiers, event.field8, event.field9, event.fieldA, event.field6); } }, &bootTickController); const auto bootMovement = bootTickController.request(); assert(bootMovement.animation == 1 && bootMovement.direction == 14); remorse::AnimationClip bootTickAnimation{}; bootTickAnimation.header = {17, 4, 0, 0}; bootTickAnimation.frameCount = 17; bootTickAnimation.frames.resize(17 * 8); auto* bootTickProcess = freshGameKernel.createAnimPrimitiveProcess(1, 1, bootMovement.animation, bootMovement.direction, bootTickAnimation, freshGameGroups); const remorse::u16 bootTickProcessId = static_cast(bootTickProcess->base.bytes[2] | (static_cast(bootTickProcess->base.bytes[3]) << 8)); assert(freshGameKernel.startAnimPrimitiveProcess(bootTickProcessId, freshGameWorld, bootTickAnimation)); struct FreshGameTickContext { remorse::ProcessKernel& kernel; remorse::LiveFixedMapItems& items; const remorse::AnimationClip& clip; const std::vector& shapes; remorse::u16 processId; std::optional advanced; } freshGameTick{freshGameKernel, freshGameWorld, bootTickAnimation, *typeFlags, bootTickProcessId}; freshGameKernel.deliverSystemTimerEvent(); freshGameKernel.runTimedSchedulerPass(freshGameKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* opaque) { auto& tick = *static_cast(opaque); if (&process == tick.kernel.processAt(tick.processId)) { const auto* avatar = tick.items.findItem(1); assert(avatar); tick.advanced = tick.kernel.advanceGroundedAnimPrimitive(tick.processId, tick.items, tick.clip, tick.shapes, remorse::calculateFastAreaRange({avatar->data.x * 2, avatar->data.y * 2, avatar->data.z})); } }, &freshGameTick); assert(freshGameKernel.systemTimerTick() == 1 && freshGameTick.advanced == true && freshGameWorld.findNpcAnimation(1)->frame == 1 && freshGameWorld.findItem(1)->itemNumber == 1); const auto destinationUseCandidates = remorse::itemGrabSearchCandidates( *integratedAvatar, integratedStartupWorld.mapItems(), *typeFlags); assert(destinationUseCandidates); const std::array expectedDestinationCandidates{6812, 6811, 6810, 6804, 6786, 6785}; assert(destinationUseCandidates->size() == expectedDestinationCandidates.size()); unsigned eligibleDestinationUses = 0; for (std::size_t index = 0; index < destinationUseCandidates->size(); ++index) { const auto& candidate = (*destinationUseCandidates)[index]; assert(candidate.itemNumber == expectedDestinationCandidates[index]); const auto* item = integratedStartupWorld.findItem(candidate.itemNumber); assert(item && item->data.shape < typeFlags->size()); const auto& shape = (*typeFlags)[item->data.shape]; const remorse::UsecodeItemIdentity destinationIdentity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, destinationIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); eligibleDestinationUses += eligible.has_value(); } assert(eligibleDestinationUses == 0); const auto spawnUseCandidates = remorse::itemGrabSearchCandidates( *spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags); assert(spawnUseCandidates); unsigned eligibleSpawnUses = 0; for (const auto& candidate : *spawnUseCandidates) { const auto* item = spawnSearchWorld.findItem(candidate.itemNumber); if (!item || item->data.shape >= typeFlags->size()) continue; const auto& shape = (*typeFlags)[item->data.shape]; const remorse::UsecodeItemIdentity spawnIdentity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, spawnIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (eligible) { ++eligibleSpawnUses; } } assert(eligibleSpawnUses == 0); unsigned eligibleMapUseItems = 0; unsigned keycardUseItems = 0; std::optional boxItem; for (const auto& item : *stagedItems) { if (item.data.shape >= typeFlags->size()) continue; const auto& shape = (*typeFlags)[item.data.shape]; const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape, item.data.flags, item.data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, mapItemIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (eligible) { ++eligibleMapUseItems; if (eligible->classId == 0x031d || eligible->classId == 0x031e) { ++keycardUseItems; } if (eligible->className == "BOX_NS" && item.data.frame == 0 && !boxItem) { boxItem = item; } } } assert(eligibleMapUseItems == 218 && keycardUseItems == 10 && boxItem); struct RankedUseTarget { remorse::u32 distance = 0; remorse::u16 itemNumber = 0; remorse::u16 classId = 0; std::string className; }; std::vector rankedUseTargets; for (const auto& item : *stagedItems) { if (item.data.shape >= typeFlags->size()) continue; const auto& shape = (*typeFlags)[item.data.shape]; const remorse::UsecodeItemIdentity targetIdentity{item.itemNumber, item.data.shape, item.data.flags, item.data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, targetIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (!eligible) continue; const remorse::s32 targetX = item.data.x; const remorse::s32 targetY = item.data.y; const remorse::s32 startX = integratedAvatar->data.x; const remorse::s32 startY = integratedAvatar->data.y; const auto absDelta = [](remorse::s32 left, remorse::s32 right) { return left < right ? right - left : left - right; }; rankedUseTargets.push_back({static_cast( absDelta(targetX, startX) + absDelta(targetY, startY)), item.itemNumber, eligible->classId, eligible->className}); } std::sort(rankedUseTargets.begin(), rankedUseTargets.end(), [](const auto& left, const auto& right) { return left.distance < right.distance; }); std::cout << "Nearest map-1 use targets from destination pad:\n"; for (std::size_t index = 0; index < std::min(12, rankedUseTargets.size()); ++index) { const auto& target = rankedUseTargets[index]; const auto* item = integratedStartupWorld.findItem(target.itemNumber); assert(item); std::cout << " item " << target.itemNumber << " distance " << target.distance << " xy " << item->data.x << ',' << item->data.y << ',' << static_cast(item->data.z) << " shape/frame/quality/flags " << item->data.shape << '/' << static_cast(item->data.frame) << '/' << item->data.quality << '/' << item->data.flags << " class " << target.className << " (" << target.classId << ")\n"; } constexpr remorse::s32 routeStep = 16; constexpr remorse::s32 routeRadius = 8192; constexpr remorse::s32 routeSide = routeRadius * 2 / routeStep + 1; constexpr remorse::s32 routeCenter = routeRadius / routeStep; constexpr std::size_t maximumExpandedNodes = 30000; remorse::LiveFixedMapItems approachWorld(*stagedItems); assert(approachWorld.initializeAvatar() && approachWorld.teleportAvatar(*levelStartEgg, 1)); const auto* approachAvatar = approachWorld.findItem(1); assert(approachAvatar); const remorse::StagedFixedMapItem searchOrigin = *approachAvatar; const remorse::WorldPoint routeStart{searchOrigin.data.x, searchOrigin.data.y, searchOrigin.data.z}; std::vector elevationCompatibleTargets; for (const auto& target : rankedUseTargets) { const auto* item = approachWorld.findItem(target.itemNumber); assert(item); if (remorse::classifyItemFindZMatch(searchOrigin, (*typeFlags)[searchOrigin.data.shape], *item, (*typeFlags)[item->data.shape], 3) != 0) { elevationCompatibleTargets.push_back(item); } } std::cout << "Use targets matching spawn elevation: " << elevationCompatibleTargets.size() << '\n'; for (std::size_t index = 0; index < std::min(12, elevationCompatibleTargets.size()); ++index) { const auto* item = elevationCompatibleTargets[index]; std::cout << " item " << item->itemNumber << " at " << item->data.x << ',' << item->data.y << ',' << static_cast(item->data.z) << '\n'; } struct RouteGoalArea { remorse::s32 minX; remorse::s32 maxX; remorse::s32 minY; remorse::s32 maxY; }; const auto& avatarShape = (*typeFlags)[searchOrigin.data.shape]; std::vector routeGoalAreas; for (const auto* target : elevationCompatibleTargets) { const auto& targetShape = (*typeFlags)[target->data.shape]; const remorse::s32 minX = std::max({static_cast(target->data.x) - 0x100, static_cast(target->data.x) - static_cast(targetShape.x) * 16 + 1, 0}); const remorse::s32 maxX = std::min(static_cast(target->data.x) + static_cast(avatarShape.x) * 16 - 1, 0x7fff); const remorse::s32 minY = std::max({static_cast(target->data.y) - 0x100, static_cast(target->data.y) - static_cast(targetShape.y) * 16 + 1, 0}); const remorse::s32 maxY = std::min(static_cast(target->data.y) + static_cast(avatarShape.y) * 16 - 1, 0x7fff); if (minX <= maxX && minY <= maxY) { routeGoalAreas.push_back({minX, maxX, minY, maxY}); } } const auto routeCell = [&](const remorse::WorldPoint& point) { const remorse::s32 gridX = (point.x - routeStart.x) / routeStep + routeCenter; const remorse::s32 gridY = (point.y - routeStart.y) / routeStep + routeCenter; assert(gridX >= 0 && gridX < routeSide && gridY >= 0 && gridY < routeSide); return static_cast(gridY * routeSide + gridX); }; const auto pointForRouteCell = [&](int cell) { const auto index = static_cast(cell); const remorse::s32 gridX = static_cast(index % routeSide) - routeCenter; const remorse::s32 gridY = static_cast(index / routeSide) - routeCenter; return remorse::WorldPoint{routeStart.x + gridX * routeStep, routeStart.y + gridY * routeStep, routeStart.z}; }; const auto distanceToRange = [](remorse::s32 value, remorse::s32 minimum, remorse::s32 maximum) { return value < minimum ? minimum - value : value > maximum ? value - maximum : 0; }; const auto routeHeuristic = [&](const remorse::WorldPoint& point) { remorse::s32 bestDistance = std::numeric_limits::max(); for (const auto& area : routeGoalAreas) { const remorse::s32 distance = distanceToRange(point.x, area.minX, area.maxX) + distanceToRange(point.y, area.minY, area.maxY); bestDistance = std::min(bestDistance, (distance + routeStep - 1) / routeStep); } return bestDistance == std::numeric_limits::max() ? 0 : bestDistance; }; struct RouteOpenEntry { remorse::s32 estimate; remorse::s32 distance; int cell; }; struct RouteOpenOrder { bool operator()(const RouteOpenEntry& left, const RouteOpenEntry& right) const { if (left.estimate != right.estimate) return left.estimate > right.estimate; return left.distance < right.distance; } }; const std::size_t routeCellCount = static_cast(routeSide * routeSide); std::vector routeDistances(routeCellCount, std::numeric_limits::max()); std::vector routeParents(routeCellCount, -2); const int startCell = static_cast(routeCell(routeStart)); routeDistances[static_cast(startCell)] = 0; routeParents[static_cast(startCell)] = -1; std::priority_queue, RouteOpenOrder> openRoutes; openRoutes.push({routeHeuristic(routeStart), 0, startCell}); int targetCell = -1; remorse::u16 approachTargetItem = 0; std::size_t expandedNodes = 0; constexpr std::array, 4> routeDirections{{ {routeStep, 0}, {-routeStep, 0}, {0, routeStep}, {0, -routeStep}}}; while (!openRoutes.empty() && targetCell < 0 && expandedNodes < maximumExpandedNodes) { const RouteOpenEntry entry = openRoutes.top(); openRoutes.pop(); const std::size_t currentCellIndex = static_cast(entry.cell); if (entry.distance != routeDistances[currentCellIndex]) continue; ++expandedNodes; const remorse::WorldPoint current = pointForRouteCell(entry.cell); remorse::StagedFixedMapItem currentOrigin = searchOrigin; currentOrigin.data.x = static_cast(current.x); currentOrigin.data.y = static_cast(current.y); const auto& originShape = (*typeFlags)[currentOrigin.data.shape]; const auto interactionArea = remorse::itemFindAreaAroundItem(currentOrigin, originShape); const auto targetCandidate = std::find_if(elevationCompatibleTargets.begin(), elevationCompatibleTargets.end(), [&](const auto* candidate) { return candidate->data.x >= interactionArea.minX && candidate->data.x <= interactionArea.maxX && candidate->data.y >= interactionArea.minY && candidate->data.y <= interactionArea.maxY && remorse::classifyItemFindZMatch(currentOrigin, originShape, *candidate, (*typeFlags)[candidate->data.shape], 3) != 0; }); if (targetCandidate != elevationCompatibleTargets.end()) { approachTargetItem = (*targetCandidate)->itemNumber; targetCell = entry.cell; break; } assert(approachWorld.moveItem(1, static_cast(current.x), static_cast(current.y), static_cast(current.z))); for (const auto [deltaX, deltaY] : routeDirections) { const remorse::WorldPoint destination{current.x + deltaX, current.y + deltaY, current.z}; if (destination.x < 0 || destination.x > 0x7fff || destination.y < 0 || destination.y > 0x7fff || destination.x < routeStart.x - routeRadius || destination.x > routeStart.x + routeRadius || destination.y < routeStart.y - routeRadius || destination.y > routeStart.y + routeRadius) { continue; } const std::size_t cell = routeCell(destination); const int nextDistance = entry.distance + 1; if (nextDistance >= routeDistances[cell]) continue; const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination, *typeFlags, remorse::calculateFastAreaRange(current)); if (!sweep || sweep->failed || sweep->failedDirections != 0 || sweep->destination.x != destination.x || sweep->destination.y != destination.y || sweep->destination.z != destination.z) { continue; } routeDistances[cell] = nextDistance; routeParents[cell] = entry.cell; openRoutes.push({nextDistance + routeHeuristic(destination), nextDistance, static_cast(cell)}); } } std::cout << "Route search expanded " << expandedNodes << " nodes\n"; assert(targetCell >= 0); std::vector approachRoute; for (int cell = targetCell; cell >= 0;) { approachRoute.push_back(pointForRouteCell(cell)); cell = routeParents[static_cast(cell)]; } std::reverse(approachRoute.begin(), approachRoute.end()); const remorse::u16 routeGoalItem = approachTargetItem; assert(approachWorld.teleportAvatar(*levelStartEgg, 1)); for (std::size_t index = 1; index < approachRoute.size(); ++index) { const auto& current = approachRoute[index - 1]; const auto& destination = approachRoute[index]; const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination, *typeFlags, remorse::calculateFastAreaRange(current)); assert(sweep && !sweep->failed && sweep->failedDirections == 0 && sweep->destination.x == destination.x && sweep->destination.y == destination.y && sweep->destination.z == destination.z); assert(approachWorld.moveItem(1, static_cast(destination.x), static_cast(destination.y), static_cast(destination.z))); } const auto* endpointAvatar = approachWorld.findItem(1); assert(endpointAvatar); const auto endpointCandidates = remorse::itemGrabSearchCandidates(*endpointAvatar, approachWorld.mapItems(), *typeFlags); assert(endpointCandidates && std::any_of(endpointCandidates->begin(), endpointCandidates->end(), [&](const auto& candidate) { return candidate.itemNumber == routeGoalItem; })); std::optional approachEvent; approachTargetItem = 0; for (const auto& candidate : *endpointCandidates) { const auto* item = approachWorld.findItem(candidate.itemNumber); if (item == nullptr || item->data.shape >= typeFlags->size()) continue; const auto& shape = (*typeFlags)[item->data.shape]; const remorse::UsecodeItemIdentity interactionIdentity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, shape.family, false}; auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, interactionIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (eligible) { approachTargetItem = item->itemNumber; approachEvent = std::move(*eligible); break; } } assert(approachEvent); const auto* approachTarget = approachWorld.findItem(approachTargetItem); assert(approachTarget); auto targetRenderer = remorse::loadMapSceneRenderer(*root, 1); assert(targetRenderer); remorse::MapRenderOptions targetRenderOptions; targetRenderOptions.mapIndex = 1; targetRenderOptions.maxWidth = 320; targetRenderOptions.maxHeight = 200; const remorse::WorldPoint targetWorldLocation{approachTarget->data.x * 2, approachTarget->data.y * 2, approachTarget->data.z}; targetRenderOptions.viewCenter = targetWorldLocation; targetRenderOptions.worldRect = remorse::WorldRect{targetWorldLocation.x - 1, targetWorldLocation.y - 1, targetWorldLocation.x + 1, targetWorldLocation.y + 1}; const auto targetBefore = targetRenderer->render(targetRenderOptions, &approachWorld); assert(targetBefore); const remorse::u16 originalTargetShape = approachTarget->data.shape; const remorse::u8 originalTargetFrame = approachTarget->data.frame; constexpr remorse::u16 interactionProcessId = 0x0340; remorse::UsecodeTaskRegistry interactionTasks; auto interactionContext = remorse::createUsecodeEventContext(interactionTasks.runtimeMemory(), *retailOwnerRows, approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2); auto interactionTaskValue = remorse::UsecodeProcessTask::create(interactionProcessId, approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2); assert(interactionContext && interactionTaskValue); const std::vector interactionProcessIdBytes{0x40, 0x03}; assert(interactionTasks.runtimeMemory().write(interactionContext->processIdOutput, interactionProcessIdBytes)); assert(interactionTasks.addWithContext(std::move(*interactionTaskValue), std::move(*interactionContext))); auto* interactionTask = interactionTasks.find(interactionProcessId); assert(interactionTask); remorse::UsecodeOpcodeServices interactionServices; interactionServices.readFarWord = [interactionTask](remorse::u16 offset, remorse::u16 segment) -> std::optional { return interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); }; interactionServices.setInfo = [](remorse::u16, remorse::u16) { return true; }; interactionServices.processCount = []() { return remorse::u16{2}; }; interactionServices.currentProcessId = []() { return interactionProcessId; }; std::optional> rejectedEvent; interactionServices.callEvent = [&usecode, interactionTask, &rejectedEvent]( remorse::u16 classId, remorse::u16 eventSlot) -> std::optional { std::cout << "Nested event call from " << interactionTask->classId << '/' << interactionTask->eventSlot << " pc " << interactionTask->programCounter << " BP " << interactionTask->frameBaseOffset << " stack " << interactionTask->interpreter.stackTop << ':'; for (std::size_t index = interactionTask->interpreter.stackTop; index < std::min(interactionTask->interpreter.valueStack.size(), interactionTask->interpreter.stackTop + 12); ++index) { std::cout << ' ' << static_cast(interactionTask->interpreter.valueStack[index]); } std::cout << " frame:"; for (std::size_t index = 0x30; index < 0x50; ++index) { std::cout << ' ' << static_cast(interactionTask->frame[index]); } std::cout << '\n'; const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId); auto body = usecodeClass ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; if (!body) rejectedEvent = std::pair{classId, eventSlot}; return body; }; remorse::u16 nextInteractionChildId = 0x0350; std::vector> spawnedInteractionEvents; std::optional> rejectedSpawn; interactionServices.spawn = [&usecode, &nextInteractionChildId, &spawnedInteractionEvents, &rejectedSpawn](remorse::u16 classId, remorse::u16 eventSlot, remorse::u8, remorse::u8, remorse::u16, const remorse::u8*) -> std::optional { const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId); const auto body = usecodeClass ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; if (!body) { rejectedSpawn = std::pair{classId, eventSlot}; return std::nullopt; } spawnedInteractionEvents.emplace_back(classId, eventSlot); return nextInteractionChildId++; }; std::optional rejectedIntrinsic; std::vector> interactionIntrinsics; std::vector> queriedShapeFamilies; std::vector> queriedItemFamilies; interactionServices.callIntrinsic = [interactionTask, &approachWorld, &typeFlags, &rejectedIntrinsic, &interactionIntrinsics, &queriedShapeFamilies, &queriedItemFamilies]( remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { interactionIntrinsics.emplace_back(ordinal, argumentBytes); if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0}; if (ordinal == 0xfd && argumentBytes == 2) return remorse::u16{0}; if (ordinal == 0xac && argumentBytes == 2) { const remorse::u16 shape = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); if (shape >= typeFlags->size()) return std::nullopt; const remorse::u16 family = (*typeFlags)[shape].family; queriedShapeFamilies.emplace_back(shape, family); return family; } if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0}; if (argumentBytes < 4) { rejectedIntrinsic = ordinal; return std::nullopt; } const remorse::u16 offset = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); const remorse::u16 segment = static_cast(arguments[2] | (static_cast(arguments[3]) << 8)); if (ordinal == 0x0a && argumentBytes == 4) { const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); if (itemNumber) approachWorld.destroyItem(*itemNumber); return remorse::u16{0}; } if (ordinal == 0x30 && argumentBytes == 4) { return approachWorld.popItemFromEtherealVoid().value_or(0); } if (ordinal == 0x20 && argumentBytes == 10) { const remorse::u16 x = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); const remorse::u16 y = static_cast(arguments[6] | (static_cast(arguments[7]) << 8)); return approachWorld.popItemToCoords(x, y, arguments[8]).value_or(0); } if (ordinal == 0x19 && argumentBytes == 14) { const remorse::u16 shape = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); const remorse::u16 frame = static_cast(arguments[6] | (static_cast(arguments[7]) << 8)); const remorse::u16 x = static_cast(arguments[8] | (static_cast(arguments[9]) << 8)); const remorse::u16 y = static_cast(arguments[10] | (static_cast(arguments[11]) << 8)); const remorse::u8 z = arguments[12]; const bool legalPosition = frame <= 0xff && approachWorld.canCreateItemAt(shape, x, y, z, *typeFlags); if (!legalPosition) { return remorse::u16{0}; } remorse::StagedFixedMapItem createdItem; createdItem.recordIndex = static_cast(-1); createdItem.data.x = x; createdItem.data.y = y; createdItem.data.z = z; createdItem.data.shape = shape; createdItem.data.frame = static_cast(frame); const auto itemNumber = approachWorld.allocateItem(createdItem); if (!itemNumber || !interactionTask->writeMappedFarWord( remorse::FarPtr16{offset, segment}, *itemNumber)) { return remorse::u16{0}; } return remorse::u16{1}; } const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); if (ordinal == 0x10 && argumentBytes == 4) { const auto* item = itemNumber ? approachWorld.findItem(*itemNumber) : nullptr; return item ? static_cast(item->data.quality & 0xff) : remorse::u16{0}; } if (!itemNumber) return std::nullopt; const auto* item = approachWorld.findItem(*itemNumber); if (ordinal == 0x3c && argumentBytes == 4 && item && item->data.shape < typeFlags->size()) { const remorse::u16 family = (*typeFlags)[item->data.shape].family; queriedItemFamilies.emplace_back(*itemNumber, family); return family; } if (ordinal == 0x22 && argumentBytes == 4 && item) { return approachWorld.pushItemToEtherealVoid(*itemNumber) ? std::optional{remorse::u16{0}} : std::nullopt; } if (ordinal == 0x25) return remorse::u16{0}; if (ordinal == 0xea && argumentBytes == 4 && item) { return static_cast(item->data.quality & 0xff); } if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame; if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber; if (ordinal == 0x09 && argumentBytes == 4 && item) return item->data.z; if (ordinal == 0x13 && argumentBytes == 4 && item) return item->data.x; if (ordinal == 0x14 && argumentBytes == 4 && item) return item->data.y; if (ordinal == 0x24 && argumentBytes == 6) { const remorse::u16 shape = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); return approachWorld.setItemShape(*itemNumber, shape) ? std::optional{remorse::u16{0}} : std::nullopt; } if ((ordinal == 0x02 || ordinal == 0x59) && argumentBytes == 6) { const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); return approachWorld.setItemFrame(*itemNumber, frame) ? std::optional{remorse::u16{0}} : std::nullopt; } rejectedIntrinsic = ordinal; return std::nullopt; }; remorse::UsecodeStepResult lastInteractionResult = remorse::UsecodeStepResult::Advanced; bool interactionStoppedOnError = false; bool reachedInteractionMilestone = false; bool targetVisualChanged = false; const remorse::u16 originalTargetFlags = approachTarget->data.flags; const std::size_t originalWorldItemCount = approachWorld.mapItems().size(); const auto targetRenderHasChanged = [&]() { const auto image = targetRenderer->render(targetRenderOptions, &approachWorld); return image && image->pixels.size() == targetBefore->pixels.size() && !std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(), image->pixels.begin(), image->pixels.end(), [](const auto& left, const auto& right) { return left.red == right.red && left.green == right.green && left.blue == right.blue; }); }; for (unsigned tick = 0; tick < 8 && !reachedInteractionMilestone && !interactionTask->halted && !interactionStoppedOnError; ++tick) { interactionTask->interpreter.impliedProcessId = 0; for (unsigned instruction = 0; instruction < 256; ++instruction) { lastInteractionResult = interactionTask->step(interactionServices); const auto* item = approachWorld.findItem(approachTargetItem); targetVisualChanged = !item || item->data.shape != originalTargetShape || item->data.frame != originalTargetFrame; if (lastInteractionResult == remorse::UsecodeStepResult::Advanced || lastInteractionResult == remorse::UsecodeStepResult::SetInfo || lastInteractionResult == remorse::UsecodeStepResult::Spawned) { if (!spawnedInteractionEvents.empty() && targetRenderHasChanged()) { targetVisualChanged = true; reachedInteractionMilestone = true; break; } continue; } if (lastInteractionResult != remorse::UsecodeStepResult::Yielded && lastInteractionResult != remorse::UsecodeStepResult::Returned) { interactionStoppedOnError = true; } break; } } const auto* finalInteractionTarget = approachWorld.findItem(approachTargetItem); targetVisualChanged = targetVisualChanged || finalInteractionTarget == nullptr || finalInteractionTarget->data.shape != originalTargetShape || finalInteractionTarget->data.frame != originalTargetFrame || finalInteractionTarget->data.flags != originalTargetFlags || approachWorld.mapItems().size() != originalWorldItemCount; std::cout << "Reachable target use event: class " << approachEvent->className << " (" << approachEvent->classId << ") shape/frame " << originalTargetShape << '/' << static_cast(originalTargetFrame) << " body bytes " << approachEvent->body.bytes.size() << " VM result " << static_cast(lastInteractionResult) << " PC " << interactionTask->programCounter << " class/event " << interactionTask->classId << '/' << interactionTask->eventSlot << " call depth " << interactionTask->routineFrames.size() << " rejected intrinsic " << rejectedIntrinsic.value_or(0xffff) << " rejected event " << (rejectedEvent ? rejectedEvent->first : 0xffff) << '/' << (rejectedEvent ? rejectedEvent->second : 0xffff) << " rejected spawn " << (rejectedSpawn ? rejectedSpawn->first : 0xffff) << '/' << (rejectedSpawn ? rejectedSpawn->second : 0xffff) << " spawned " << spawnedInteractionEvents.size() << " changed " << targetVisualChanged << '\n'; std::cout << "Selected target item " << approachTargetItem << " quality/flags " << (finalInteractionTarget ? finalInteractionTarget->data.quality : 0) << '/' << (finalInteractionTarget ? finalInteractionTarget->data.flags : 0) << '\n'; for (const auto& [classId, eventSlot] : spawnedInteractionEvents) { std::cout << " spawned usecode " << classId << '/' << eventSlot << '\n'; } std::cout << "Executed intrinsics:"; for (const auto& [ordinal, argumentBytes] : interactionIntrinsics) { std::cout << ' ' << ordinal << '/' << static_cast(argumentBytes); } std::cout << '\n'; for (const auto& [shape, family] : queriedShapeFamilies) { std::cout << " shape family " << shape << '=' << family << '\n'; } for (const auto& [itemNumber, family] : queriedItemFamilies) { std::cout << " item family " << itemNumber << '=' << family << '\n'; } if (lastInteractionResult == remorse::UsecodeStepResult::UnsupportedOpcode) { const std::size_t windowStart = interactionTask->programCounter > 4 ? interactionTask->programCounter - 4 : remorse::usecodeEventBytecodeOffset; const std::size_t windowEnd = std::min(interactionTask->code.size(), interactionTask->programCounter + 8); std::cout << "Unsupported usecode bytes:"; for (std::size_t index = windowStart; index < windowEnd; ++index) { std::cout << ' ' << index << ':' << static_cast(interactionTask->code[index]); } std::cout << '\n'; } assert(reachedInteractionMilestone && targetVisualChanged && !interactionStoppedOnError); const auto targetAfter = targetRenderer->render(targetRenderOptions, &approachWorld); assert(targetAfter && targetBefore->pixels.size() == targetAfter->pixels.size()); const bool targetPixelsChanged = !std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(), targetAfter->pixels.begin(), targetAfter->pixels.end(), [](const auto& left, const auto& right) { return left.red == right.red && left.green == right.green && left.blue == right.blue; }); assert(targetPixelsChanged); std::cout << "Visible target mutation: shape/frame " << (finalInteractionTarget ? finalInteractionTarget->data.shape : 0xffff) << '/' << (finalInteractionTarget ? static_cast(finalInteractionTarget->data.frame) : 0xff) << " pixels changed " << targetPixelsChanged << '\n'; std::cout << "Reachable target Item_Grab route: item " << approachTargetItem << " steps " << approachRoute.size() - 1 << " expanded " << expandedNodes << " endpoint " << approachRoute.back().x << ',' << approachRoute.back().y << ',' << approachRoute.back().z << '\n'; 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, staged.data.flags, staged.data.quality, (*typeFlags)[staged.data.shape].family, false}; const remorse::UsecodeClassBases retailBases{0, 0x800, 0x900}; assert(remorse::selectUsecodeClassId(stagedIdentity, retailBases) == staged.data.shape); const auto stagedClass = remorse::loadUsecodeClass(*usecode, remorse::selectUsecodeClassId(stagedIdentity, retailBases)); assert(!stagedClass); assert(!remorse::ownerRowAllowsEvent(*retailOwnerRows, staged.data.shape, 0x200)); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, stagedIdentity, retailBases, 0x200, 9)); bool foundStagedRelease = false; for (const auto& item : *stagedItems) { if (item.data.shape >= typeFlags->size()) { continue; } const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape, item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false}; if (remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, mapItemIdentity, retailBases, 0x200, 9)) { foundStagedRelease = true; break; } } assert(foundStagedRelease); const remorse::UsecodeItemIdentity rechargeItem{0x100, 0x138, 0, 0, 0, false}; const auto eligibleRelease = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0x200, 9); assert(eligibleRelease && eligibleRelease->classId == 0x138 && eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102); 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))); const auto cardClass = remorse::loadUsecodeClass(*usecode, 0x31d); const auto cardUse = cardClass ? remorse::readUsecodeEventBody(*cardClass, 1) : std::nullopt; assert(cardClass && cardClass->name == "CARD_NS" && cardUse && cardUse->bytes.size() == 56); const std::array cardPrefix{ 0x5a, 0x00, 0x5c, 0x24, 0x00, 'C', 'A', 'R', 'D', '_', 'N', 'S', 0x00, 0x00}; assert(hasRetailEventEntry(cardUse->bytes, cardPrefix)); std::vector frame(0x80); frame[remorse::usecodeFrameBaseOffset + 6] = 0x00; frame[remorse::usecodeFrameBaseOffset + 7] = 0x01; std::vector itemMemory(0x102); itemMemory[0x100] = 0x34; itemMemory[0x101] = 0x12; remorse::ProcessKernel vmKernel; remorse::u16 vmGroupCounts[32]{}; for (int index = 0; index < 3; ++index) { vmKernel.createProcess(1, vmGroupCounts); } auto* vmProcess = vmKernel.createUsecodeProcess(1, vmGroupCounts); const remorse::u16 vmProcessId = static_cast( vmProcess->base.bytes[2] | (static_cast(vmProcess->base.bytes[3]) << 8)); auto cardTask = remorse::UsecodeProcessTask::create(vmProcessId, 0x31d, 1, 0x1234, cardUse->bytes); assert(cardTask && cardTask->programCounter == remorse::usecodeEventBytecodeOffset && cardTask->frame.size() == 0x80 && cardTask->frame[remorse::usecodeFrameBaseOffset + 7] == 1 && cardTask->itemMemory[0x100] == 0x34 && cardTask->itemMemory[0x101] == 0x12); remorse::UsecodeTaskRegistry taskRegistry; assert(taskRegistry.add(std::move(*cardTask)) && taskRegistry.size() == 1); cardTask.reset(); auto* registeredCardTask = taskRegistry.find(vmProcessId); assert(registeredCardTask && registeredCardTask->classId == 0x31d && registeredCardTask->eventSlot == 1 && registeredCardTask->sourceItem == 0x1234); assert(!taskRegistry.add(*registeredCardTask)); const auto switchClass = remorse::loadUsecodeClass(*usecode, 0x0a16); const auto switchUse = switchClass ? remorse::readUsecodeEventBody(*switchClass, 0x21) : std::nullopt; assert(switchClass && switchClass->name == "SWITCH" && switchUse); remorse::UsecodeOpcodeServices opcodeServices; opcodeServices.readFarWord = [registeredCardTask](remorse::u16 offset, remorse::u16 segment) -> std::optional { return registeredCardTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; opcodeServices.setInfo = [&vmKernel, vmProcessId](remorse::u16 eventType, remorse::u16 sourceItem) { return vmKernel.setProcessInfo(vmProcessId, eventType, sourceItem); }; std::optional> spawnedUsecode; remorse::u16 spawnedProcessId = 0; opcodeServices.processCount = [&vmKernel]() { return vmKernel.processCount(); }; opcodeServices.spawn = [&spawnedUsecode, &spawnedProcessId, &vmKernel, &vmGroupCounts, &taskRegistry, &switchUse](remorse::u16 classId, remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, remorse::u16 itemArgument, const remorse::u8*) -> std::optional { assert(extraArgumentBytes == 0 && itemArgumentSize == 2); spawnedUsecode = std::array{classId, eventSlot, itemArgument}; auto* child = vmKernel.createUsecodeProcess(1, vmGroupCounts); spawnedProcessId = static_cast( child->base.bytes[2] | (static_cast(child->base.bytes[3]) << 8)); auto childTask = remorse::UsecodeProcessTask::create(spawnedProcessId, classId, eventSlot, itemArgument, switchUse->bytes); if (!childTask || !taskRegistry.add(std::move(*childTask))) { vmKernel.terminateProcess(spawnedProcessId, vmGroupCounts); vmKernel.clearTerminatedProcesses(); return std::nullopt; } return spawnedProcessId; }; assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 17); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 19); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 21); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::SetInfo && registeredCardTask->programCounter == 22); assert(registeredCardTask->interpreter.lastSetInfoOperands && (*registeredCardTask->interpreter.lastSetInfoOperands)[0] == 0x1234 && (*registeredCardTask->interpreter.lastSetInfoOperands)[1] == 0x0207); assert(vmKernel.processAt(vmProcessId)->bytes[0x04] == 0x34 && vmKernel.processAt(vmProcessId)->bytes[0x05] == 0x12 && vmKernel.processAt(vmProcessId)->bytes[0x06] == 0x07 && vmKernel.processAt(vmProcessId)->bytes[0x07] == 0x02); opcodeServices.setInfo = [](remorse::u16, remorse::u16) { return false; }; const auto stackTopBeforeRejectedInfo = registeredCardTask->interpreter.stackTop; assert(registeredCardTask->interpreter.pushWord(0x1234) && registeredCardTask->interpreter.pushWord(0x0207)); const auto stackTopWithRejectedInfo = registeredCardTask->interpreter.stackTop; registeredCardTask->programCounter = 21; assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::ServiceRejected && registeredCardTask->programCounter == 22); assert(registeredCardTask->interpreter.stackTop == stackTopWithRejectedInfo && registeredCardTask->interpreter.popWord() == 0x0207 && registeredCardTask->interpreter.popWord() == 0x1234); registeredCardTask->interpreter.stackTop = stackTopBeforeRejectedInfo; registeredCardTask->programCounter = 22; assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 23 && registeredCardTask->interpreter.processExcluded); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 26); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 28); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Spawned && registeredCardTask->programCounter == 35); assert(spawnedUsecode && (*spawnedUsecode)[0] == 0x0a16 && (*spawnedUsecode)[1] == 0x21 && (*spawnedUsecode)[2] == 0x1234); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 36); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 37 && registeredCardTask->interpreter.temporaryWord == spawnedProcessId); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && registeredCardTask->programCounter == 40); assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Returned && registeredCardTask->programCounter == 41); auto* registeredSwitchTask = taskRegistry.find(spawnedProcessId); assert(registeredSwitchTask && registeredSwitchTask->classId == 0x0a16 && registeredSwitchTask->eventSlot == 0x21 && registeredSwitchTask->sourceItem == 0x1234 && vmKernel.processAt(spawnedProcessId) != nullptr); vmKernel.terminateProcess(vmProcessId, vmGroupCounts); vmKernel.clearTerminatedProcesses(); assert(taskRegistry.remove(vmProcessId) && taskRegistry.size() == 1 && !taskRegistry.find(vmProcessId) && taskRegistry.find(spawnedProcessId) == registeredSwitchTask); struct SwitchScheduleContext { remorse::ProcessKernel* kernel; remorse::UsecodeTaskRegistry* tasks; remorse::u16 processId; unsigned runs = 0; } switchSchedule{&vmKernel, &taskRegistry, spawnedProcessId}; vmKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { auto& schedule = *static_cast(context); const remorse::u16 processId = static_cast( process.bytes[2] | (static_cast(process.bytes[3]) << 8)); if (processId != schedule.processId) { return; } ++schedule.runs; auto* task = schedule.tasks->find(processId); assert(task); remorse::UsecodeOpcodeServices services; services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) -> std::optional { return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; services.setInfo = [schedule, processId](remorse::u16 eventType, remorse::u16 sourceItem) { return schedule.kernel->setProcessInfo(processId, eventType, sourceItem); }; assert(task->step(services) == remorse::UsecodeStepResult::Advanced); assert(task->step(services) == remorse::UsecodeStepResult::Advanced); assert(task->step(services) == remorse::UsecodeStepResult::Advanced); assert(task->step(services) == remorse::UsecodeStepResult::SetInfo); }, &switchSchedule); assert(switchSchedule.runs == 1 && registeredSwitchTask->programCounter == 22 && vmKernel.processAt(spawnedProcessId)->bytes[0x04] == 0x34 && vmKernel.processAt(spawnedProcessId)->bytes[0x06] == 0x07); remorse::StagedFixedMapItem switchItem; switchItem.itemNumber = 0x1234; switchItem.data.shape = 0x216; switchItem.data.quality = 3; remorse::LiveFixedMapItems switchWorld({switchItem}); auto switchTask = remorse::UsecodeProcessTask::create(spawnedProcessId, 0x0a16, 0x21, switchItem.itemNumber, switchUse->bytes); assert(switchTask); const std::uint64_t heldKeycards = std::uint64_t{1} << switchItem.data.quality; remorse::UsecodeOpcodeServices switchServices; switchServices.readFarWord = [&switchTask](remorse::u16 offset, remorse::u16 segment) -> std::optional { return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; switchServices.setInfo = [&vmKernel, spawnedProcessId](remorse::u16 eventType, remorse::u16 sourceItem) { return vmKernel.setProcessInfo(spawnedProcessId, eventType, sourceItem); }; switchServices.callIntrinsic = [&switchTask, &switchWorld, heldKeycards](remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { const auto itemNumber = [&]() -> std::optional { if (argumentBytes < 4) return std::nullopt; const remorse::u16 offset = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); const remorse::u16 segment = static_cast(arguments[2] | (static_cast(arguments[3]) << 8)); return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0}; if (ordinal == 0xfd && argumentBytes == 2) { const remorse::u16 keycard = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); return static_cast((heldKeycards & (std::uint64_t{1} << (keycard & 0x1f))) != 0); } if (ordinal == 0x18 && argumentBytes == 4) return remorse::u16{0}; if (ordinal == 0x15 && argumentBytes == 6) return remorse::u16{0}; const auto source = itemNumber(); if (!source) return std::nullopt; const auto* item = switchWorld.findItem(*source); if (ordinal == 0xea && argumentBytes == 4 && item) { return static_cast(item->data.quality & 0xff); } if (ordinal == 0x01 && argumentBytes == 4 && item) { return static_cast(item->data.frame); } if (ordinal == 0x59 && argumentBytes == 6 && arguments[4] == 4 && item) { return switchWorld.setItemFrame(*source, arguments[4]) ? std::optional{remorse::u16{0}} : std::nullopt; } return std::nullopt; }; bool switchFrameChanged = false; for (unsigned instruction = 0; instruction < 100 && !switchFrameChanged; ++instruction) { const auto result = switchTask->step(switchServices); const auto* item = switchWorld.findItem(switchItem.itemNumber); switchFrameChanged = item && item->data.frame == 4; assert(result == remorse::UsecodeStepResult::Advanced || result == remorse::UsecodeStepResult::SetInfo); } assert(switchFrameChanged && switchTask->programCounter < switchUse->bytes.size() && switchTask->sourceItem == switchItem.itemNumber); const auto boxClass = remorse::loadUsecodeClass(*usecode, 0x0081); const auto boxUse = boxClass ? remorse::readUsecodeEventBody(*boxClass, 1) : std::nullopt; assert(boxClass && boxClass->name == "BOX_NS" && boxUse && boxItem); const std::array boxPrefix{ 0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00}; assert(hasRetailEventEntry(boxUse->bytes, boxPrefix)); remorse::LiveFixedMapItems boxWorld(*stagedItems); const auto& boxShape = (*typeFlags)[boxItem->data.shape]; const remorse::u8 boxHeight = boxShape.z == 0 && (boxShape.flags & 1) == 0 ? 1 : static_cast(boxShape.z * 8); assert(static_cast(boxItem->data.z) + boxHeight <= 0xff); remorse::StagedFixedMapItem boxSearchOrigin; boxSearchOrigin.itemNumber = 1; boxSearchOrigin.data.shape = 1; boxSearchOrigin.data.x = boxItem->data.x; boxSearchOrigin.data.y = boxItem->data.y; boxSearchOrigin.data.z = static_cast(boxItem->data.z + boxHeight); const auto boxCandidates = remorse::itemGrabSearchCandidates(boxSearchOrigin, boxWorld.mapItems(), *typeFlags); assert(boxCandidates); const auto boxCandidate = std::find_if(boxCandidates->begin(), boxCandidates->end(), [boxItem](const auto& candidate) { return candidate.itemNumber == boxItem->itemNumber; }); assert(boxCandidate != boxCandidates->end()); const auto* selectedBoxItem = boxWorld.findItem(boxCandidate->itemNumber); assert(selectedBoxItem && selectedBoxItem->data.shape < typeFlags->size()); const remorse::UsecodeItemIdentity boxIdentity{selectedBoxItem->itemNumber, selectedBoxItem->data.shape, selectedBoxItem->data.flags, selectedBoxItem->data.quality, (*typeFlags)[selectedBoxItem->data.shape].family, false}; const auto selectedBoxEvent = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, boxIdentity, retailBases, 0x02, 1); assert(selectedBoxEvent && selectedBoxEvent->classId == 0x0081 && selectedBoxEvent->className == "BOX_NS" && selectedBoxEvent->body.bytes == boxUse->bytes); remorse::UsecodeTaskRegistry boxTasks; auto boxContext = remorse::createUsecodeEventContext(boxTasks.runtimeMemory(), *retailOwnerRows, selectedBoxEvent->classId, 1, boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); assert(boxContext && boxContext->context.interpreter.callFrameCount == 1 && boxContext->ownedRegions.size() == 3 && boxTasks.runtimeMemory().allocationCount() == 5); const std::vector boxProcessIdBytes{0x40, 0x03}; assert(boxTasks.runtimeMemory().write(boxContext->processIdOutput, boxProcessIdBytes)); auto boxTaskValue = remorse::UsecodeProcessTask::create(0x0340, selectedBoxEvent->classId, 1, boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); assert(boxTaskValue && boxTasks.addWithContext(std::move(*boxTaskValue), std::move(*boxContext))); auto* boxTask = boxTasks.find(0x0340); const auto* registeredBoxContext = boxTasks.context(0x0340); assert(boxTask && registeredBoxContext && boxTask->sourceItem == boxItem->itemNumber && boxTask->interpreter.callFrameCount == 1 && registeredBoxContext->context.processBytes[ remorse::usecodeContextSlotIndexOffset] == 0x81); const auto freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c); const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt; auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1); assert(freeClass && freeTimerBody && boxRenderer); remorse::MapRenderOptions boxRenderOptions; boxRenderOptions.mapIndex = 1; boxRenderOptions.maxWidth = 320; boxRenderOptions.maxHeight = 200; boxRenderOptions.viewCenter = remorse::WorldPoint{ boxItem->data.x * 2, boxItem->data.y * 2, boxItem->data.z}; const auto boxBefore = boxRenderer->render(boxRenderOptions, &boxWorld); assert(boxBefore); remorse::UsecodeOpcodeServices boxServices; boxServices.readFarWord = [&boxTask](remorse::u16 offset, remorse::u16 segment) -> std::optional { return boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; boxServices.setInfo = [](remorse::u16, remorse::u16) { return true; }; boxServices.processCount = []() { return remorse::u16{2}; }; boxServices.currentProcessId = []() { return remorse::u16{0x0340}; }; boxServices.callIntrinsic = [&boxTask, &boxWorld](remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0}; if (argumentBytes < 4) return std::nullopt; const remorse::u16 offset = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); const remorse::u16 segment = static_cast(arguments[2] | (static_cast(arguments[3]) << 8)); const auto itemNumber = boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); if (!itemNumber) return std::nullopt; const auto* item = boxWorld.findItem(*itemNumber); if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame; if (ordinal == 0x02 && argumentBytes == 6 && item) { const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); return boxWorld.setItemFrame(*itemNumber, frame) ? std::optional{remorse::u16{0}} : std::nullopt; } if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber; return std::nullopt; }; remorse::u16 nextTimerProcessId = 0x0350; remorse::u32 timerTick = 100; remorse::u16 lastTimerDelay = 0; std::optional timerTask; boxServices.spawn = [&nextTimerProcessId, &timerTick, &lastTimerDelay, &timerTask, &freeTimerBody](remorse::u16 classId, remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, remorse::u16 itemArgument, const remorse::u8* extraArguments) -> std::optional { if (classId != 0x0a0c || eventSlot != 0x32 || extraArgumentBytes != 2 || itemArgumentSize != 0 || itemArgument != 0) return std::nullopt; lastTimerDelay = static_cast(extraArguments[0] | (static_cast(extraArguments[1]) << 8)); std::vector timerArguments(extraArguments, extraArguments + extraArgumentBytes); const remorse::u16 processId = nextTimerProcessId++; timerTask = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, itemArgument, freeTimerBody->bytes, itemArgumentSize, std::move(timerArguments)); if (!timerTask) return std::nullopt; timerTask->timerDelayProcess = true; timerTask->wakeTick = timerTick + lastTimerDelay; return processId; }; for (remorse::u8 expectedFrame = 0; expectedFrame < 6; ++expectedFrame) { bool yielded = false; for (unsigned instruction = 0; instruction < 500 && !yielded; ++instruction) { const auto result = boxTask->step(boxServices); if (result == remorse::UsecodeStepResult::Yielded) { yielded = true; break; } assert(result == remorse::UsecodeStepResult::Advanced || result == remorse::UsecodeStepResult::SetInfo || result == remorse::UsecodeStepResult::Spawned); } assert(yielded && lastTimerDelay == 5 && timerTask && boxTask->interpreter.impliedProcessId == timerTask->processId); assert(boxWorld.findItem(boxItem->itemNumber)->data.frame == expectedFrame); assert(timerTask->frame[remorse::usecodeFrameBaseOffset + 6] == 5 && timerTask->timerDelayProcess && timerTask->wakeTick == timerTick + 5); timerTick = timerTask->wakeTick; timerTask.reset(); boxTask->interpreter.impliedProcessId = 0; } const auto boxAfter = boxRenderer->render(boxRenderOptions, &boxWorld); assert(boxAfter && boxBefore->pixels.size() == boxAfter->pixels.size()); assert(!std::equal(boxBefore->pixels.begin(), boxBefore->pixels.end(), boxAfter->pixels.begin(), [](const auto& left, const auto& right) { return left.red == right.red && left.green == right.green && left.blue == right.blue; })); const auto boxProcessIdOutput = boxTasks.runtimeMemory().read(registeredBoxContext->processIdOutput, sizeof(remorse::u16)); assert(boxProcessIdOutput && (*boxProcessIdOutput)[0] == 0x40 && (*boxProcessIdOutput)[1] == 0x03 && boxTasks.runtimeMemory().allocationCount() == 5); assert(boxTasks.remove(0x0340) && boxTasks.size() == 0 && boxTasks.context(0x0340) == nullptr && boxTasks.runtimeMemory().allocationCount() == 0); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); ownerRows[13] = 0x00; ownerRows[14] = 0x02; ownerRows[16] = 0x01; assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x200)); assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x1000000)); assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0x400)); assert(!remorse::ownerRowAllowsEvent(ownerRows, 0, 0x200)); assert(!remorse::ownerRowAllowsEvent(ownerRows, 2, 0x200)); assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0)); return 0; }