#define NOMINMAX #define WIN32_LEAN_AND_MEAN #include #include "remorse/animation_archive.h" #include "remorse/collision.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" #include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" #include "remorse/palette.h" #include "remorse/runtime.h" #include "remorse/shape_archive.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 #include #include namespace { constexpr wchar_t windowClassName[] = L"CrusaderRemorseGameWindow"; constexpr UINT timerId = 1; constexpr UINT sceneReadyMessage = WM_APP + 1; constexpr remorse::u32 backingWidth = 2560; constexpr remorse::u32 backingHeight = 1440; constexpr int initialClientWidth = 1280; constexpr int initialClientHeight = 760; constexpr double simulationTickSeconds = 0.025; constexpr remorse::s32 diagnosticItemRange = 48; struct AppState { remorse::GameDataRoot root; remorse::u32 mapIndex = 1; bool diagnostics = false; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; remorse::UsecodeTaskRegistry usecodeTasks; bool useRequested = false; bool usecodeWorldMutationPending = false; std::uint64_t heldKeycards = 0; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; remorse::ControllerMovementState controllerMovement; remorse::u16 animationProcessId = 0; std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; remorse::u16 diagnosticReleaseProcessId = 0; std::string diagnosticReleaseClass; std::size_t diagnosticReleaseBodyBytes = 0; bool diagnosticItemCompleted = false; remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; std::mutex sceneMutex; std::condition_variable renderWake; bool renderRequested = false; bool renderStop = false; std::optional scene; std::optional renderer; std::optional standAnimation; std::optional walkAnimation; std::optional runAnimation; std::vector> playerFrames; remorse::CollisionBody playerCollisionBody{}; std::vector collisionBodies; std::vector shapeTypes; std::optional usecodeArchive; std::vector usecodeOwnerRows; remorse::Palette256 playerPalette{}; std::vector dibPixels; std::vector viewPixels; remorse::WorldPoint spawn{}; remorse::FastAreaRange fastArea{}; remorse::s32 minWorldX = 0; remorse::s32 minWorldY = 0; remorse::s32 maxWorldX = 0; remorse::s32 maxWorldY = 0; double playerOffsetX = 0.0; double playerOffsetY = 0.0; double simulationAccumulator = 0.0; remorse::u8 playerAnimation = 0; remorse::u8 playerDirection = 14; remorse::u8 playerFrame = 0; std::wstring loadError; bool sceneLoaded = false; std::thread sceneThread; std::thread renderThread; HDC backBufferDc = nullptr; HBITMAP backBufferBitmap = nullptr; HBITMAP previousBackBufferBitmap = nullptr; int backBufferWidth = 0; int backBufferHeight = 0; LARGE_INTEGER lastTick{}; LARGE_INTEGER ticksPerSecond{}; }; remorse::u32 standSleepStart(const remorse::StandProcessEntry& stand) { const auto& bytes = stand.base.bytes; return bytes[0x0a] | (static_cast(bytes[0x0b]) << 8) | (static_cast(bytes[0x0c]) << 16) | (static_cast(bytes[0x0d]) << 24); } std::wstring widen(const std::string& value) { if (value.empty()) { return {}; } const int length = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), nullptr, 0); if (length <= 0) { return L"Map loading failed."; } std::wstring result(static_cast(length), L'\0'); MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), result.data(), length); return result; } void setLoadFailure(AppState& state, const std::wstring& message) { std::lock_guard lock(state.sceneMutex); state.loadError = message; state.sceneLoaded = true; } remorse::WorldPoint avatarWorld(const AppState& state) { const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr; return avatar ? remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z} : state.spawn; } bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); std::optional queueUsecodeTask(AppState& state, remorse::u16 classId, remorse::u16 eventSlot, remorse::u16 sourceItem, std::vector code, remorse::u8 itemArgumentSize = 2, std::vector extraArguments = {}) { auto* process = state.diagnosticKernel.createUsecodeProcess( state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); const remorse::u16 processId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); const auto terminateProcess = [&state, processId]() { state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); state.diagnosticKernel.clearTerminatedProcesses(); }; auto eventContext = remorse::createUsecodeEventContext(state.usecodeTasks.runtimeMemory(), state.usecodeOwnerRows, classId, eventSlot, sourceItem, code, itemArgumentSize); if (!eventContext) { terminateProcess(); return std::nullopt; } const std::vector processIdBytes{ static_cast(processId), static_cast(processId >> 8)}; if (!state.usecodeTasks.runtimeMemory().write(eventContext->processIdOutput, processIdBytes)) { remorse::destroyUsecodeEventContext(state.usecodeTasks.runtimeMemory(), *eventContext); terminateProcess(); return std::nullopt; } auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments)); if (!task || !state.usecodeTasks.addWithContext(std::move(*task), std::move(*eventContext))) { terminateProcess(); return std::nullopt; } const auto* registeredContext = state.usecodeTasks.context(processId); if (registeredContext == nullptr) { state.usecodeTasks.remove(processId); terminateProcess(); return std::nullopt; } std::copy(registeredContext->context.processBytes.begin() + remorse::usecodeContextSlotIndexOffset, registeredContext->context.processBytes.end(), reinterpret_cast(process) + remorse::usecodeContextSlotIndexOffset); return processId; } bool startNearbyUsecode(AppState& state) { if (!state.liveItems || !state.usecodeArchive || state.usecodeOwnerRows.empty()) { return false; } const auto* origin = state.liveItems->findItem(1); if (origin == nullptr || origin->data.shape >= state.shapeTypes.size()) { return false; } const auto candidates = remorse::itemGrabSearchCandidates(*origin, state.liveItems->mapItems(), state.shapeTypes); if (!candidates) { return false; } for (const auto& candidate : *candidates) { const auto* item = state.liveItems->findItem(candidate.itemNumber); if (item == nullptr || item->data.shape >= state.shapeTypes.size()) { continue; } const auto& shape = state.shapeTypes[item->data.shape]; const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*state.usecodeArchive, state.usecodeOwnerRows, identity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (eligible) { return queueUsecodeTask(state, eligible->classId, 1, item->itemNumber, eligible->body.bytes).has_value(); } } return false; } void runUsecodeTasks(AppState& state) { state.diagnosticKernel.scanRunnableProcesses(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* context) { auto& app = *static_cast(context); const remorse::u16 processId = static_cast(process.bytes[2] | (static_cast(process.bytes[3]) << 8)); auto* task = app.usecodeTasks.find(processId); if (!task || task->halted) { return; } if (task->timerDelayProcess) { if (app.diagnosticKernel.systemTimerTick() >= task->wakeTick) { app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); } return; } if (task->interpreter.impliedProcessId != 0) { if (app.diagnosticKernel.processAt(task->interpreter.impliedProcessId) != nullptr) { return; } task->interpreter.impliedProcessId = 0; } remorse::UsecodeOpcodeServices services; services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) -> std::optional { return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); }; services.setInfo = [&app, processId](remorse::u16 eventType, remorse::u16 sourceItem) { return app.diagnosticKernel.setProcessInfo(processId, eventType, sourceItem); }; services.processCount = [&app]() { return app.diagnosticKernel.processCount(); }; services.currentProcessId = [processId]() { return processId; }; services.callIntrinsic = [&app, task](remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { 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(keycard < 64 && (app.heldKeycards & (std::uint64_t{1} << keycard)) != 0); } if (ordinal == 0x15 && argumentBytes == 6) { return remorse::u16{0}; } if (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 = task->readMappedItemWord(remorse::FarPtr16{offset, segment}); if (!itemNumber) { return std::nullopt; } if (ordinal == 0xea && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{static_cast(item->data.quality & 0xff)} : std::nullopt; } if (ordinal == 0x01 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.frame} : std::nullopt; } if (ordinal == 0x03 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.mapNumber} : std::nullopt; } if (ordinal == 0x59 && argumentBytes == 6) { std::lock_guard lock(app.sceneMutex); const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { return std::nullopt; } app.usecodeWorldMutationPending = true; return remorse::u16{0}; } return std::nullopt; }; services.spawn = [&app](remorse::u16 classId, remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, remorse::u16 itemArgument, const remorse::u8* extraArguments) -> std::optional { if (!app.usecodeArchive) { return std::nullopt; } const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); const auto body = usecodeClass ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; if (!body) { return std::nullopt; } std::vector arguments; if (extraArgumentBytes != 0) { arguments.assign(extraArguments, extraArguments + extraArgumentBytes); } const auto childId = queueUsecodeTask(app, classId, eventSlot, itemArgument, body->bytes, itemArgumentSize, std::move(arguments)); if (!childId) { return std::nullopt; } auto* registeredChild = app.usecodeTasks.find(*childId); if (registeredChild && classId == 0x0a0c && eventSlot == 0x32 && itemArgumentSize == 0 && extraArgumentBytes == 2) { const remorse::u16 delay = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); registeredChild->timerDelayProcess = true; registeredChild->wakeTick = app.diagnosticKernel.systemTimerTick() + delay; } return childId; }; for (std::size_t instructionCount = 0; instructionCount < 256; ++instructionCount) { const auto result = task->step(services); if (result == remorse::UsecodeStepResult::Returned) { app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); break; } if (result == remorse::UsecodeStepResult::Yielded) { break; } if (result != remorse::UsecodeStepResult::Advanced && result != remorse::UsecodeStepResult::SetInfo && result != remorse::UsecodeStepResult::Spawned) { task->halted = true; break; } } }, &state, state.diagnosticKernel.systemTimerTick()); state.diagnosticKernel.clearTerminatedProcesses(); for (std::size_t processId = 3; processId < 1020; ++processId) { const auto id = static_cast(processId); if (state.usecodeTasks.find(id) && state.diagnosticKernel.processAt(id) == nullptr) { state.usecodeTasks.remove(id); } } } void loadSceneAsync(HWND window, AppState& state) { state.sceneThread = std::thread([window, &state]() { try { const auto fixedPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "FIXED.DAT"); const auto typeFlagsPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); const auto globPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "GLOB.FLX"); if (!fixedPath) { setLoadFailure(state, L"STATIC\\FIXED.DAT was not found under the game data root."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } if (!typeFlagsPath || !globPath) { setLoadFailure(state, L"STATIC\\TYPEFLAG.DAT or STATIC\\GLOB.FLX was not found."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto archive = remorse::loadFixedMapArchive(*fixedPath); const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt; if (!map || map->entries.empty()) { setLoadFailure(state, L"The selected map could not be loaded or contains no records."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto stagedItems = remorse::stageFixedMapItems(*map); if (!stagedItems) { setLoadFailure(state, L"The fixed-map item cache could not be initialized."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); const auto globObjects = remorse::loadGlobObjects(*globPath); if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) { setLoadFailure(state, L"Collision shape metadata could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } std::vector containedItems; if (map->index != 0) { const auto contained = remorse::stageContainedFixedMapItems(*map, *shapeTypes); if (!contained) { setLoadFailure(state, L"Contained map items could not be staged."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } containedItems = std::move(*contained); } auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects); const auto usecodePath = remorse::resolveGameDataPath( state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt; const auto usecodeOwnerRows = usecodeArchive ? remorse::loadUsecodeOwnerRows(*usecodeArchive) : std::nullopt; const auto animationPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "ANIM.DAT"); const auto shapesPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "SHAPES.FLX"); const auto palettePath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); if (!animationPath || !shapesPath || !palettePath) { setLoadFailure(state, L"The player animation, shape, or palette resource is missing."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto animationArchive = remorse::loadAnimationArchive(*animationPath); const auto shapeArchive = remorse::loadShapeArchive(*shapesPath); const auto palette = remorse::loadPalette256(*palettePath); const auto standAnimation = animationArchive ? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt; const auto walkAnimation = animationArchive ? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt; const auto runAnimation = animationArchive ? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt; const auto shapeFrames = shapeArchive ? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt; if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) { setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } std::vector> playerFrames(shapeFrames->size()); const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) { for (remorse::u8 direction = 0; direction < 16; ++direction) { for (remorse::u32 frameIndex = 0; frameIndex < clip.frameCount; ++frameIndex) { const auto metadata = remorse::getAnimationFrame( clip, direction, static_cast(frameIndex)); if (!metadata) { return false; } const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); if (shapeFrame >= playerFrames.size()) { return false; } if (!playerFrames[shapeFrame]) { auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame); if (!decoded) { return false; } playerFrames[shapeFrame] = std::move(*decoded); } } } return true; }; if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) || !cacheAnimationFrames(*runAnimation)) { setLoadFailure(state, L"A player animation references a missing shape frame."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } remorse::s32 minX = map->entries.front().x; remorse::s32 minY = map->entries.front().y; remorse::s32 maxX = minX; remorse::s32 maxY = minY; for (const remorse::FixedMapEntry& entry : map->entries) { minX = std::min(minX, static_cast(entry.x)); minY = std::min(minY, static_cast(entry.y)); maxX = std::max(maxX, static_cast(entry.x)); maxY = std::max(maxY, static_cast(entry.y)); } const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); if (state.mapIndex == 1 && !startingEgg) { setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } if (state.mapIndex != 1 && !state.diagnostics) { setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const remorse::WorldPoint spawn = startingEgg ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options; options.mapIndex = state.mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; options.viewCenter = spawn; remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); liveItems.initializeAvatar(); if (startingEgg) { remorse::ProcessKernel teleporterKernel; remorse::u16 teleporterGroupCounts[32]{}; for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { teleporterKernel.createProcess(1, teleporterGroupCounts); } auto* teleporter = teleporterKernel.createTeleporterProcess(1, static_cast(state.mapIndex), 0x1e, teleporterGroupCounts); const remorse::u16 processId = static_cast(teleporter->base.bytes[2] | (static_cast(teleporter->base.bytes[3]) << 8)); const bool teleported = remorse::TeleporterProcess::run(*teleporter, liveItems, static_cast(state.mapIndex), *shapeTypes); teleporter->base.bytes[0x18] |= 4; teleporterKernel.terminateProcess(processId, teleporterGroupCounts); if (!teleported) { setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } } else { remorse::StagedFixedMapItem diagnosticStart; diagnosticStart.data.x = static_cast(spawn.x / 2); diagnosticStart.data.y = static_cast(spawn.y / 2); diagnosticStart.data.z = static_cast(spawn.z); liveItems.teleportAvatar(diagnosticStart, static_cast(state.mapIndex)); } auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); if (renderer) { hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); } auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt; if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } std::vector dibPixels(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { dibPixels[index * 3] = scene->pixels[index].blue; dibPixels[index * 3 + 1] = scene->pixels[index].green; dibPixels[index * 3 + 2] = scene->pixels[index].red; } { std::lock_guard lock(state.sceneMutex); state.spawn = spawn; state.fastArea = remorse::calculateFastAreaRange(spawn); state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); state.collisionBodies = std::move(collisionBodies); state.shapeTypes = *shapeTypes; state.usecodeArchive = std::move(usecodeArchive); if (usecodeOwnerRows) { state.usecodeOwnerRows = *usecodeOwnerRows; } state.minWorldX = minX; state.minWorldY = minY; state.maxWorldX = maxX; state.maxWorldY = maxY; state.scene = std::move(scene); state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); state.standAnimation = *standAnimation; state.walkAnimation = *walkAnimation; state.runAnimation = *runAnimation; state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; state.liveItems.emplace(std::move(liveItems)); state.sceneLoaded = true; } } catch (const std::exception& error) { setLoadFailure(state, widen(error.what())); } catch (...) { setLoadFailure(state, L"An unexpected error occurred while building the map scene."); } PostMessageW(window, sceneReadyMessage, 0, 0); }); } bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range) { std::vector eggIds; for (const auto& item : items.mapItems()) { if (item.data.shape < renderer.typeFlags.size() && renderer.typeFlags[item.data.shape].family == 3 && !items.isGlobHatched(item.itemNumber) && remorse::isWorldPointInFastArea( item.data.x * 2, item.data.y * 2, range)) { eggIds.push_back(item.itemNumber); } } bool changed = false; for (const remorse::u16 eggId : eggIds) { const auto* egg = items.findItem(eggId); const auto glob = std::find_if(renderer.globs.begin(), renderer.globs.end(), [egg](const auto& object) { return object.index == egg->data.quality; }); if (glob != renderer.globs.end()) { changed = items.hatchGlobEgg(eggId, *glob, renderer.typeFlags).has_value() || changed; } } return changed; } void startLiveRenderer(HWND window, AppState& state) { state.renderThread = std::thread([window, &state]() { for (;;) { std::optional snapshot; remorse::WorldPoint center{}; { std::unique_lock lock(state.sceneMutex); state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); if (state.renderStop) { return; } state.renderRequested = false; snapshot.emplace(*state.liveItems); center = avatarWorld(state); } remorse::MapRenderOptions options; options.mapIndex = state.mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; options.viewCenter = center; const remorse::s32 radius = static_cast( backingWidth + backingHeight * 2 + 512); options.worldRect = remorse::WorldRect{ center.x - radius, center.y - radius, center.x + radius, center.y + radius}; auto scene = state.renderer->render(options, &*snapshot); if (!scene) { continue; } std::vector pixels(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { pixels[index * 3] = scene->pixels[index].blue; pixels[index * 3 + 1] = scene->pixels[index].green; pixels[index * 3 + 2] = scene->pixels[index].red; } { std::lock_guard lock(state.sceneMutex); if (state.renderStop) { return; } state.scene = std::move(scene); state.dibPixels = std::move(pixels); } PostMessageW(window, sceneReadyMessage, 0, 0); } }); } void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font) { const int saved = SaveDC(device); SetBkMode(device, TRANSPARENT); SetTextColor(device, color); SelectObject(device, font); DrawTextW(device, text, -1, const_cast(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE); RestoreDC(device, saved); } void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, int sourceLeft, int sourceTop, std::size_t viewStride) { const remorse::AnimationClip* clip = nullptr; if (state.playerAnimation == 1 && state.walkAnimation) { clip = &*state.walkAnimation; } else if (state.playerAnimation == 3 && state.runAnimation) { clip = &*state.runAnimation; } else if (state.standAnimation) { clip = &*state.standAnimation; } if (!clip || state.playerFrames.empty()) { return; } const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); if (!metadata) { return; } const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) { return; } const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame]; const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft; const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop; const int spriteLeft = actorX + sprite.frame.xOffset; const int spriteTop = actorY + sprite.frame.yOffset; const bool flipped = remorse::isAnimationFrameFlipped(*metadata); for (remorse::u32 y = 0; y < sprite.frame.height; ++y) { const int destinationY = spriteTop + static_cast(y); if (destinationY < 0 || destinationY >= viewHeight) { continue; } for (remorse::u32 x = 0; x < sprite.frame.width; ++x) { const int destinationX = spriteLeft + static_cast(x); if (destinationX < 0 || destinationX >= viewWidth) { continue; } const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x; const remorse::s16 paletteIndex = sprite.pixels[ static_cast(y) * sprite.frame.width + sourceX]; if (paletteIndex < 0) { continue; } const remorse::RgbColor& color = state.playerPalette.colors[ static_cast(paletteIndex)]; const std::size_t pixelOffset = static_cast(destinationY) * viewStride + static_cast(destinationX) * 3; state.viewPixels[pixelOffset] = static_cast(color.blue * 255 / 63); state.viewPixels[pixelOffset + 1] = static_cast(color.green * 255 / 63); state.viewPixels[pixelOffset + 2] = static_cast(color.red * 255 / 63); } } BITMAPINFO bitmap{}; bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmap.bmiHeader.biWidth = viewWidth; bitmap.bmiHeader.biHeight = -viewHeight; bitmap.bmiHeader.biPlanes = 1; bitmap.bmiHeader.biBitCount = 24; bitmap.bmiHeader.biCompression = BI_RGB; StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight, state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY); } void drawLoadingScreen(HDC device, const RECT& client, const AppState& state) { HBRUSH background = CreateSolidBrush(RGB(13, 23, 28)); FillRect(device, &client, background); DeleteObject(background); RECT title = client; title.bottom = title.top + 70; HFONT titleFont = CreateFontW(-30, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Bahnschrift"); drawCenteredText(device, title, L"CRUSADER / NO REMORSE", RGB(228, 220, 191), titleFont); DeleteObject(titleFont); RECT status = client; status.top = title.bottom; HFONT bodyFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); const std::wstring message = state.loadError.empty() ? L"Building the retail map scene..." : state.loadError; drawCenteredText(device, status, message.c_str(), state.loadError.empty() ? RGB(74, 207, 184) : RGB(245, 157, 119), bodyFont); DeleteObject(bodyFont); } void paintWindow(HWND window, AppState& state) { PAINTSTRUCT paint{}; HDC paintDc = BeginPaint(window, &paint); RECT client{}; GetClientRect(window, &client); const int clientWidth = static_cast(std::max(1L, client.right - client.left)); const int clientHeight = static_cast(std::max(1L, client.bottom - client.top)); if (state.backBufferWidth != clientWidth || state.backBufferHeight != clientHeight) { if (state.backBufferDc) { SelectObject(state.backBufferDc, state.previousBackBufferBitmap); DeleteObject(state.backBufferBitmap); DeleteDC(state.backBufferDc); state.backBufferDc = nullptr; state.backBufferBitmap = nullptr; state.previousBackBufferBitmap = nullptr; } state.backBufferDc = CreateCompatibleDC(paintDc); if (state.backBufferDc) { state.backBufferBitmap = CreateCompatibleBitmap(paintDc, clientWidth, clientHeight); if (state.backBufferBitmap) { state.previousBackBufferBitmap = static_cast( SelectObject(state.backBufferDc, state.backBufferBitmap)); state.backBufferWidth = clientWidth; state.backBufferHeight = clientHeight; } else { DeleteDC(state.backBufferDc); state.backBufferDc = nullptr; } } } HDC device = state.backBufferDc ? state.backBufferDc : paintDc; const auto finishPaint = [&]() { if (device != paintDc) { BitBlt(paintDc, 0, 0, clientWidth, clientHeight, device, 0, 0, SRCCOPY); } EndPaint(window, &paint); }; std::lock_guard lock(state.sceneMutex); if (!state.sceneLoaded || !state.scene) { drawLoadingScreen(device, client, state); finishPaint(); return; } if (!state.loadError.empty()) { drawLoadingScreen(device, client, state); finishPaint(); return; } HBRUSH clearBrush = CreateSolidBrush(RGB(10, 17, 22)); FillRect(device, &client, clearBrush); DeleteObject(clearBrush); const int viewWidth = std::min(clientWidth, static_cast(state.scene->width)); const int viewHeight = std::min(clientHeight, static_cast(state.scene->height)); const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2; const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); const std::size_t viewStride = (static_cast(viewWidth) * 3 + 3) & ~std::size_t(3); state.viewPixels.resize(viewStride * static_cast(viewHeight)); const std::size_t sceneStride = static_cast(state.scene->width) * 3; for (int row = 0; row < viewHeight; ++row) { const std::size_t sceneOffset = static_cast(sourceTop + row) * sceneStride + static_cast(sourceLeft) * 3; const std::size_t viewOffset = static_cast(row) * viewStride; std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset, static_cast(viewWidth) * 3); } compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); if (!state.diagnostics) { finishPaint(); return; } RECT hud{0, 0, viewWidth, 80}; HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29)); FillRect(device, &hud, hudBrush); DeleteObject(hudBrush); HPEN hudLine = CreatePen(PS_SOLID, 1, RGB(43, 204, 178)); HGDIOBJ oldPen = SelectObject(device, hudLine); MoveToEx(device, 0, hud.bottom - 1, nullptr); LineTo(device, viewWidth, hud.bottom - 1); SelectObject(device, oldPen); DeleteObject(hudLine); std::wostringstream label; const remorse::WorldPoint playerWorld = avatarWorld(state); label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex << L" X " << playerWorld.x << L" Y " << playerWorld.y << L" Z " << static_cast(playerWorld.z) << L" DIR " << std::setw(2) << static_cast(state.playerDirection) << L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE") << L" WASD / KEYPAD SHIFT RUN"; HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); RECT labelBounds{20, 0, viewWidth - 12, 30}; const int saved = SaveDC(device); SetBkMode(device, TRANSPARENT); SetTextColor(device, RGB(224, 229, 214)); SelectObject(device, hudFont); DrawTextW(device, label.str().c_str(), -1, &labelBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE); const remorse::EntityDispatchEntryBase& stand = state.diagnosticStand->base; const remorse::u32 sleepStart = standSleepStart(*state.diagnosticStand); const remorse::u32 sleepLength = stand.bytes[0x0e] | (static_cast(stand.bytes[0x0f]) << 8); std::wostringstream diagnostics; diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick() << L" | STAND #" << static_cast(stand.bytes[0x02]) << L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ") << ((stand.bytes[0x19] & 0x10) != 0 ? static_cast(sleepStart + sleepLength - state.diagnosticKernel.systemTimerTick() + 1) : 0) << L" | WAKEUPS " << state.standWakeCount << L" | KEY EVENTS " << state.diagnosticKeyEvents; RECT diagnosticsBounds{20, 30, viewWidth - 12, 54}; SetTextColor(device, RGB(74, 207, 184)); DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem( playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; const auto* releaseTask = state.diagnosticReleaseProcessId != 0 ? state.usecodeTasks.find(state.diagnosticReleaseProcessId) : nullptr; const std::wstring releaseStatus = state.diagnosticReleaseProcessId == 0 ? L"NOT QUEUED" : releaseTask == nullptr ? L"COMPLETE" : releaseTask->halted ? L"HALTED" : releaseTask->programCounter == remorse::usecodeEventBytecodeOffset ? L"QUEUED" : L"RUNNING"; std::wostringstream itemStatus; itemStatus << L"MAP ITEM " << displayItem->itemNumber << L" | SHAPE " << displayItem->data.shape << L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem << L" | " << (state.diagnosticReleaseBodyBytes != 0 ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (" + releaseStatus + L")" : L"NO RELEASE SCRIPT") << L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" : state.diagnosticItemProcessId != 0 ? L"QUEUED" : displayItem->itemNumber > remorse::ProcessKernel::maxTrackedItemNumber ? L"ITEM OUT OF RANGE" : !remorse::itemGrabCanCreateProcess(*displayItem) ? L"ITEM FLAG BLOCKS" : L"F: TEST RELEASE"); RECT itemBounds{20, 54, viewWidth - 12, hud.bottom - 1}; DrawTextW(device, itemStatus.str().c_str(), -1, &itemBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } RestoreDC(device, saved); DeleteObject(hudFont); finishPaint(); } void updatePlayer(HWND window, AppState& state) { LARGE_INTEGER now{}; QueryPerformanceCounter(&now); const double elapsed = std::clamp( static_cast(now.QuadPart - state.lastTick.QuadPart) / static_cast(state.ticksPerSecond.QuadPart), 0.0, 0.25); state.lastTick = now; if (GetForegroundWindow() != window) { return; } std::lock_guard lock(state.sceneMutex); if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) { return; } state.simulationAccumulator += elapsed; bool changed = false; while (state.simulationAccumulator >= simulationTickSeconds) { state.simulationAccumulator -= simulationTickSeconds; state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry, remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { auto& app = *static_cast(context); if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); } }, &state); if (state.useRequested) { state.useRequested = false; changed = startNearbyUsecode(state) || changed; } runUsecodeTasks(state); const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); if (state.diagnostics) { const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { auto& app = *static_cast(context); if (&entry == &app.diagnosticStand->base) { remorse::StandProcess::run(entry, [](const remorse::EntityDispatchEntryBase&, void*) { return false; }, nullptr, app.diagnosticKernel.systemTimerTick()); } else if (entry.bytes[0] == 0x2f && entry.bytes[1] == 0x10) { remorse::ItemProcess::run(entry, app.diagnosticKernel, app.diagnosticGroupCounts, [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { auto& app = *static_cast(releaseContext); app.diagnosticReleaseEventItem = itemNumber; app.diagnosticReleaseProcessId = 0; app.diagnosticReleaseClass.clear(); app.diagnosticReleaseBodyBytes = 0; const auto* item = app.liveItems ? app.liveItems->findItem(itemNumber) : nullptr; if (item && app.usecodeArchive && item->data.shape < app.shapeTypes.size()) { const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, app.shapeTypes[item->data.shape].family, false}; const remorse::UsecodeClassBases bases{0, 0x800, 0x900}; const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive, app.usecodeOwnerRows, identity, bases, eventMask, eventId); if (eligible) { app.diagnosticReleaseClass = eligible->className; app.diagnosticReleaseBodyBytes = eligible->body.bytes.size(); app.diagnosticReleaseProcessId = queueUsecodeTask(app, eligible->classId, eventId, itemNumber, eligible->body.bytes).value_or(0); } } }, &app); } else if (entry.bytes[0] == 0x10 && entry.bytes[1] == 0x06 && app.liveItems) { const remorse::u16 processId = static_cast(entry.bytes[2] | (static_cast(entry.bytes[3]) << 8)); app.diagnosticKernel.runResolvedGravity(processId, *app.liveItems, app.shapeTypes, app.fastArea, 1, app.diagnosticKernel.systemTimerTick(), app.diagnosticGroupCounts); } }, &state); state.diagnosticKernel.refreshActiveGroup(state.diagnosticGroupCounts); if (state.diagnosticItemProcessId != 0 && state.diagnosticKernel.processAt(state.diagnosticItemProcessId) == nullptr) { state.diagnosticItemCompleted = true; } if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { ++state.standWakeCount; } } changed = changed || state.diagnostics; if (movement.animation == 0) { if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); process->bytes[0x18] |= 4; state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); state.animationProcessId = 0; } changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; continue; } const remorse::u8 requestedAnimation = movement.animation; const remorse::AnimationClip& clip = requestedAnimation == 1 ? *state.walkAnimation : *state.runAnimation; if (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation || state.playerDirection != movement.direction) { if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); process->bytes[0x18] |= 4; state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); } auto* process = state.diagnosticKernel.createAnimPrimitiveProcess( state.diagnosticKernel.activeGroup(), 1, requestedAnimation, movement.direction, clip, state.diagnosticGroupCounts); state.animationProcessId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); state.diagnosticKernel.startAnimPrimitiveProcess(state.animationProcessId, *state.liveItems, clip); state.playerAnimation = requestedAnimation; } state.playerDirection = movement.direction; const auto* avatar = state.liveItems->findItem(1); const remorse::WorldPoint beforeMove{avatar->data.x, avatar->data.y, avatar->data.z}; const auto fastArea = remorse::calculateFastAreaRange( {avatar->data.x, avatar->data.y, avatar->data.z}); state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { auto& app = *static_cast(context); if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) { const remorse::AnimationClip& activeClip = app.playerAnimation == 1 ? *app.walkAnimation : *app.runAnimation; const auto* item = app.liveItems->findItem(1); app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, *app.liveItems, activeClip, app.shapeTypes, remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z})); } }, &state); state.fastArea = fastArea; state.playerFrame = state.liveItems->findNpcAnimation(1)->frame; const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(avatarWorld(state)); const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); state.playerOffsetX = destinationScreen.x - spawnScreen.x; state.playerOffsetY = destinationScreen.y - spawnScreen.y; const bool moved = avatar->data.x != beforeMove.x || avatar->data.y != beforeMove.y || avatar->data.z != beforeMove.z; const bool hatched = moved && hatchGlobsInFastArea( *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; if (state.renderThread.joinable() && (moved || hatched || usecodeMutation)) { state.renderRequested = true; state.renderWake.notify_one(); } changed = true; } if (changed) { InvalidateRect(window, nullptr, FALSE); } } LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { AppState* state = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); if (message == WM_NCCREATE) { const auto* create = reinterpret_cast(lParam); state = static_cast(create->lpCreateParams); SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(state)); } if (!state) { return DefWindowProcW(window, message, wParam, lParam); } switch (message) { case WM_CREATE: QueryPerformanceFrequency(&state->ticksPerSecond); QueryPerformanceCounter(&state->lastTick); SetTimer(window, timerId, 16, nullptr); loadSceneAsync(window, *state); return 0; case WM_TIMER: if (wParam == timerId) { updatePlayer(window, *state); } return 0; case WM_KILLFOCUS: state->controllerMovement.clear(); while (state->diagnosticKernel.popPendingKeyEvent()) {} return 0; case WM_KEYDOWN: case WM_KEYUP: if (wParam == VK_ESCAPE && message == WM_KEYDOWN) { DestroyWindow(window); return 0; } if (wParam == 'E' && message == WM_KEYDOWN) { state->useRequested = true; } { remorse::KeyEvent event{}; event.scanCode = static_cast((lParam >> 16) & 0xff); switch (wParam) { case 'W': event.scanCode = 0x48; break; case 'A': event.scanCode = 0x4b; break; case 'S': event.scanCode = 0x50; break; case 'D': event.scanCode = 0x4d; break; case 'Q': event.scanCode = 0x47; break; case 'E': event.scanCode = 0x49; break; case 'Z': event.scanCode = 0x4f; break; case 'C': event.scanCode = 0x51; break; } event.modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; if (GetKeyState(VK_NUMLOCK) & 1) event.modifiers |= 0x20; if ((lParam & (1L << 24)) != 0 || wParam == 'W' || wParam == 'A' || wParam == 'S' || wParam == 'D' || wParam == 'Q' || wParam == 'E' || wParam == 'Z' || wParam == 'C') event.modifiers &= ~0x20; if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; event.field8 = message == WM_KEYDOWN ? 1 : 0; state->diagnosticKernel.queuePendingKeyEvent(event); } if (message == WM_KEYUP) return 0; if (state->diagnostics && wParam == 'F') { std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { const remorse::WorldPoint playerWorld = avatarWorld(*state); state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; } if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && remorse::itemGrabCanCreateProcess(*state->diagnosticItem)) { auto* itemProcess = state->diagnosticKernel.createItemProcess( state->diagnosticKernel.activeGroup(), state->diagnosticItem->itemNumber, state->diagnosticGroupCounts); state->diagnosticItemProcessId = static_cast( itemProcess->bytes[2] | (static_cast(itemProcess->bytes[3]) << 8)); InvalidateRect(window, nullptr, FALSE); } } return 0; case WM_CHAR: if (state->diagnostics && wParam > 0 && wParam <= 0xff) { remorse::KeyEvent lastEvent{}; lastEvent.character = static_cast(wParam); lastEvent.scanCode = static_cast((lParam >> 16) & 0xff); lastEvent.field8 = 1; remorse::KeyEvent event = lastEvent; if (remorse::KeyboardProcess::handleKeyEvent(*state->diagnosticKeyboard, 0x10, 0, event, lastEvent)) { ++state->diagnosticKeyEvents; InvalidateRect(window, nullptr, FALSE); } } return 0; case WM_SIZE: InvalidateRect(window, nullptr, FALSE); return 0; case WM_ERASEBKGND: return 1; case WM_PAINT: paintWindow(window, *state); return 0; case sceneReadyMessage: { { std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->renderer && !state->renderThread.joinable()) { startLiveRenderer(window, *state); } } InvalidateRect(window, nullptr, FALSE); return 0; } case WM_DESTROY: KillTimer(window, timerId); if (state->sceneThread.joinable()) { state->sceneThread.join(); } { std::lock_guard lock(state->sceneMutex); state->renderStop = true; } state->renderWake.notify_one(); if (state->renderThread.joinable()) { state->renderThread.join(); } if (state->backBufferDc) { SelectObject(state->backBufferDc, state->previousBackBufferBitmap); DeleteObject(state->backBufferBitmap); DeleteDC(state->backBufferDc); } PostQuitMessage(0); return 0; default: return DefWindowProcW(window, message, wParam, lParam); } } } // namespace int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCommand) { remorse::installCrashDiagnostics(); remorse::u32 mapIndex = 1; bool diagnostics = false; std::wistringstream arguments(commandLine ? commandLine : L""); std::wstring argument; while (arguments >> argument) { if (argument == L"--diagnostics") { diagnostics = true; } else { wchar_t* end = nullptr; const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0); if (end != argument.c_str() && *end == L'\0' && parsed <= 255) { mapIndex = static_cast(parsed); } } } wchar_t executablePath[MAX_PATH]{}; GetModuleFileNameW(nullptr, executablePath, MAX_PATH); auto root = remorse::findGameDataRoot(std::filesystem::path(executablePath).parent_path()); if (!root) { root = remorse::findGameDataRoot(std::filesystem::current_path()); } if (!root) { MessageBoxW(nullptr, L"Could not locate CRUSADER.EXE, STATIC, and USECODE. Place this application below the game data folder or launch it from that folder.", L"Crusader Rebuild", MB_OK | MB_ICONERROR); return 2; } AppState state; state.root = *root; state.mapIndex = mapIndex; state.diagnostics = diagnostics; for (int index = 0; index < 3; ++index) { state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts); } state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts); state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts); state.diagnosticKernel.createControllerProcess(1, state.diagnosticGroupCounts); if (diagnostics) { state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); } WNDCLASSEXW windowClass{}; windowClass.cbSize = sizeof(windowClass); windowClass.style = CS_HREDRAW | CS_VREDRAW; windowClass.lpfnWndProc = windowProcedure; windowClass.hInstance = instance; windowClass.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); windowClass.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512)); windowClass.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); windowClass.lpszClassName = windowClassName; if (!RegisterClassExW(&windowClass)) { MessageBoxW(nullptr, L"Could not register the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR); return 3; } RECT bounds{0, 0, initialClientWidth, initialClientHeight}; AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE); HWND window = CreateWindowExW(0, windowClassName, diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr, instance, &state); if (!window) { MessageBoxW(nullptr, L"Could not create the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR); return 4; } ShowWindow(window, showCommand); UpdateWindow(window); MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { TranslateMessage(&message); DispatchMessageW(&message); } return static_cast(message.wParam); }