Add extensive tests for animation, input handling, and map rendering

- Enhanced animation archive tests to validate frame metadata and start frame selection logic.
- Introduced new tests for entity dispatch entry handling, including key event queuing and processing.
- Added tests for fixed map item interactions, including glob egg hatching and item movement.
- Expanded flex archive tests to cover teleport egg spawning and usecode event selection.
- Implemented isometric controls tests to verify directional key handling and animation state changes.
- Improved map renderer tests to ensure correct rendering of map previews and collision detection.
This commit is contained in:
Maddo 2026-09-27 11:48:14 +02:00
commit e757bb33d0
20 changed files with 1247 additions and 142 deletions

View file

@ -18,6 +18,7 @@ add_library(remorse_core
src/shape_archive.cpp
src/type_flags.cpp
src/usecode_archive.cpp
src/usecode_vm.cpp
)
target_compile_features(remorse_core PUBLIC cxx_std_17)

View file

@ -39,6 +39,13 @@ std::optional<AnimationFrameMetadata> getAnimationFrame(
u8 frameIndex);
u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept;
bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept;
u8 selectAnimationStartFrame(
const AnimationClip& clip,
bool returningFromTwoStep,
bool sameAsLastAnimation,
bool controlledAvatar,
bool entirelyOnScreen,
u8 frameSkip) noexcept;
std::optional<AnimationDisplacement> decodeAnimationDisplacement(
const AnimationFrameMetadata& metadata,
u8 direction,

View file

@ -2,13 +2,16 @@
#include "remorse/compat.h"
#include <array>
#include <cstddef>
#include <memory>
#include <optional>
#include <vector>
namespace remorse {
class LiveFixedMapItems;
struct AnimationClip;
struct ShapeTypeInfo;
struct WorldPoint;
struct FastAreaRange;
@ -43,6 +46,16 @@ struct KeyDaemonProcessEntry {
u8 extra[0x0e];
} CR_PACKED;
struct ControllerProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x0e];
} CR_PACKED;
struct AnimPrimitiveProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x29];
} CR_PACKED;
struct KeyEvent {
u8 character;
u8 scanCode;
@ -65,6 +78,8 @@ static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size mus
static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence");
static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence");
static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence");
static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence");
static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence");
static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy");
struct NpcBehaviorServices {
@ -97,6 +112,20 @@ public:
SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]);
KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]);
ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber,
u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]);
bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items,
const AnimationClip& clip, u8 frameSkip = 0);
std::optional<bool> advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items,
const AnimationClip& clip, const std::vector<ShapeTypeInfo>& shapes,
const FastAreaRange& fastArea);
bool queuePendingKeyEvent(const KeyEvent& event);
std::optional<KeyEvent> popPendingKeyEvent();
u8 pendingKeyEventCount() const;
bool pendingKeyEventOverflowed() const;
void dispatchPendingKeyEvents(
void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context);
void deliverSystemTimerEvent();
u32 systemTimerTick() const;
void setSyncContext(bool enabled, u16 currentProcessId);
@ -136,9 +165,16 @@ private:
std::vector<std::unique_ptr<EntityDispatchEntryBase>> ownedProcesses_;
std::vector<std::unique_ptr<StandProcessEntry>> ownedStandProcesses_;
std::vector<std::unique_ptr<GravityProcessEntry>> ownedGravityProcesses_;
std::vector<std::unique_ptr<AnimPrimitiveProcessEntry>> ownedAnimPrimitiveProcesses_;
std::unique_ptr<SystemTimerProcessEntry> systemTimerProcess_;
std::unique_ptr<KeyboardProcessEntry> keyboardProcess_;
std::unique_ptr<KeyDaemonProcessEntry> keyDaemonProcess_;
std::unique_ptr<ControllerProcessEntry> controllerProcess_;
std::vector<u16> keyboardSubscriberIds_;
std::array<KeyEvent, 32> pendingKeyEvents_{};
u8 nextKeyEventOffset_ = 0;
u8 keyEventOffset_ = 0;
bool pendingKeyEventOverflowed_ = false;
u16 systemTimerProcessId_ = 0xffff;
std::vector<u8> itemProcessPresence_;
std::vector<u8> itemProcessTypes_;

View file

@ -10,6 +10,7 @@ namespace remorse {
struct ShapeTypeInfo;
struct WorldRect;
struct GlobObject;
class ProcessKernel;
struct FixedMapEntry {
@ -77,6 +78,8 @@ struct FixedMapArchive {
std::optional<FixedMapArchive> loadFixedMapArchive(const std::filesystem::path& path);
std::optional<FixedMap> loadFixedMap(const FixedMapArchive& archive, u32 mapIndex);
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map);
std::optional<StagedFixedMapItem> findTeleportEgg(
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 eggId);
std::optional<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes);
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(
@ -99,16 +102,30 @@ std::optional<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem&
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes,
ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick);
struct NpcAnimationState {
u16 lastAnimation = 0xffff;
u8 frame = 0;
u8 moreFlags = 0;
};
class LiveFixedMapItems {
public:
explicit LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems = {});
bool initializeAvatar();
bool teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber);
const StagedFixedMapItem* findItem(u16 itemNumber) const;
const std::vector<StagedFixedMapItem>& mapItems() const noexcept { return items_; }
const NpcAnimationState* findNpcAnimation(u16 itemNumber) const;
NpcAnimationState* editNpcAnimation(u16 itemNumber);
u16 containedParent(u16 itemNumber) const;
std::optional<StagedFixedMapItem> nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const;
std::optional<std::vector<u16>> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const;
std::optional<u16> allocateItem(StagedFixedMapItem item);
bool insertItem(StagedFixedMapItem item);
std::optional<std::vector<u16>> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob,
const std::vector<ShapeTypeInfo>& shapes);
bool isGlobHatched(u16 eggItemNumber) const;
bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z);
std::optional<std::vector<u16>> grabItem(u16 itemNumber, const std::vector<ShapeTypeInfo>& shapes,
ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const;
@ -118,7 +135,10 @@ public:
private:
std::vector<StagedFixedMapItem> items_;
std::optional<StagedFixedMapItem> avatar_;
std::vector<NpcAnimationState> npcAnimations_;
std::vector<bool> allocatedIds_;
std::vector<bool> hatchedGlobIds_;
std::vector<u16> parentById_;
u16 nextFreeItemNumber_ = 0x100;
};

View file

@ -3,6 +3,9 @@
#include "remorse/animation_archive.h"
#include "remorse/compat.h"
#include <algorithm>
#include <vector>
namespace remorse {
struct WorldPositionD {
@ -33,6 +36,46 @@ inline std::optional<u8> controllerDirectionFromScan(u8 scanCode)
}
}
struct ControllerMovementRequest {
u8 animation = 0;
u8 direction = 14;
};
class ControllerMovementState {
public:
void handleDirectionalKey(u8 scanCode, u16 modifiers, bool pressed)
{
modifiers_ = modifiers;
const auto direction = controllerDirectionFromScan(scanCode);
if (!direction) {
return;
}
const auto held = std::find(heldScans_.begin(), heldScans_.end(), scanCode);
if (held != heldScans_.end()) {
heldScans_.erase(held);
}
if (pressed && (modifiers & 0x20) == 0) {
heldScans_.push_back(scanCode);
}
}
ControllerMovementRequest request() const
{
if (heldScans_.empty()) {
return {0, lastDirection_};
}
lastDirection_ = *controllerDirectionFromScan(heldScans_.back());
return {static_cast<u8>(controllerWalkRequested(modifiers_) ? 1 : 3), lastDirection_};
}
void clear() { heldScans_.clear(); }
private:
std::vector<u8> heldScans_;
u16 modifiers_ = 0;
mutable u8 lastDirection_ = 14;
};
inline std::optional<AnimationDisplacement> hostMovementStep(
const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection)
{

View file

@ -6,7 +6,13 @@
#include "remorse/compat.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/palette.h"
#include "remorse/shape_archive.h"
#include "remorse/type_flags.h"
#include <map>
namespace remorse {
@ -17,6 +23,8 @@ struct WorldRect {
s32 maxY = 0;
};
class LiveFixedMapItems;
struct WorldPoint {
s32 x = 0;
s32 y = 0;
@ -53,7 +61,22 @@ struct RenderedMapImage {
std::vector<RgbColor> pixels;
};
struct MapSceneRenderer {
FixedMap map;
std::vector<GlobObject> globs;
ShapeArchive shapes;
Palette256 palette;
std::vector<ShapeTypeInfo> typeFlags;
std::map<std::pair<u32, u32>, DecodedShapeFrame> decodedFrames;
std::optional<RenderedMapImage> render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems = nullptr);
};
std::optional<MapSceneRenderer> loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex);
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options);
std::optional<RenderedMapImage> renderLiveMapPreview(const GameDataRoot& root,
const MapRenderOptions& options, const LiveFixedMapItems& items);
ScreenPoint projectToScreen(const WorldPoint& point);
bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image);

View file

@ -0,0 +1,30 @@
#pragma once
#include <array>
#include <cstddef>
#include <optional>
#include <vector>
#include "remorse/compat.h"
namespace remorse {
struct UsecodeCallFrame {
u16 offset = 0;
u16 segment = 0;
};
class UsecodeInterpreterState {
public:
static std::optional<UsecodeInterpreterState> initialize(
const std::vector<u8>& itemParameter);
bool pushCodeAddress(u16 offset, u16 segment);
std::array<u8, 0xcc> valueStack{};
std::size_t stackTop = 0xcc;
std::array<UsecodeCallFrame, 32> callFrames{};
u16 callFrameCount = 0;
u16 stackLimit = 199;
};
} // namespace remorse

View file

@ -104,6 +104,29 @@ bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept
return (metadata.bytes[1] & 0x80) != 0;
}
u8 selectAnimationStartFrame(
const AnimationClip& clip,
bool returningFromTwoStep,
bool sameAsLastAnimation,
bool controlledAvatar,
bool entirelyOnScreen,
u8 frameSkip) noexcept
{
const u8 flags = clip.header[1];
if ((flags & 1) != 0) {
if (!returningFromTwoStep) {
return static_cast<u8>(clip.frameCount / 2);
}
return (flags & 4) != 0 ? static_cast<u8>(clip.frameCount - 1) : 0;
}
if ((flags & 4) == 0 || !sameAsLastAnimation) {
return 0;
}
const bool skipFrame = controlledAvatar ? frameSkip == 3 :
frameSkip >= 2 || !entirelyOnScreen;
return skipFrame ? 2 : 1;
}
std::optional<AnimationDisplacement> decodeAnimationDisplacement(
const AnimationFrameMetadata& metadata,
u8 direction,

View file

@ -1,4 +1,5 @@
#include "remorse/entity_dispatch_entry.h"
#include "remorse/animation_archive.h"
#include "remorse/collision.h"
#include "remorse/fixed_map.h"
@ -138,6 +139,115 @@ EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 it
return result;
}
AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber,
u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32])
{
if (itemNumber == 0 || itemNumber > maxTrackedItemNumber || animationNumber > 0x3f ||
direction > 15 || clip.frameCount == 0) {
throw std::out_of_range("invalid animation process request");
}
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
throw std::overflow_error("process table exhausted");
}
auto process = std::make_unique<AnimPrimitiveProcessEntry>();
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
writeLe16(process->base, 0x00, 0x2a57);
setProcessSourceType(process->base, itemNumber);
setProcessEventTypeChecked(process->base, 0xf0);
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x800));
writeLe16(process->base, 0x22, 0xf0);
process->extra[0] = 1;
process->extra[4] = static_cast<u8>(animationNumber);
process->extra[5] = static_cast<u8>(animationNumber >> 8);
process->extra[6] = direction;
process->extra[7] = clip.frameCount;
std::copy(clip.header.begin(), clip.header.end(), process->extra + 0x18);
setLastAllocationSize(sizeof(AnimPrimitiveProcessEntry));
const u16 id = addProcess(process->base);
processNames_[id] = "AnimPrimitive";
AnimPrimitiveProcessEntry* result = process.get();
ownedAnimPrimitiveProcesses_.push_back(std::move(process));
return result;
}
bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items,
const AnimationClip& clip, u8 frameSkip)
{
auto* process = processAt(processId);
if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) ||
(readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] != 0 ||
std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(),
[process](const auto& owned) { return &owned->base == process; }) ||
clip.frameCount != process->bytes[0x39] ||
!std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) {
return false;
}
auto* npc = items.editNpcAnimation(readLe16(*process, 0x04));
if (npc == nullptr) {
return false;
}
const u16 animation = readLe16(*process, 0x36);
npc->frame = selectAnimationStartFrame(clip, (npc->moreFlags & 4) != 0,
npc->lastAnimation == animation, readLe16(*process, 0x04) == 1, true, frameSkip);
npc->lastAnimation = animation;
process->bytes[0x3a] = 1;
return true;
}
std::optional<bool> ProcessKernel::advanceGroundedAnimPrimitive(u16 processId,
LiveFixedMapItems& items, const AnimationClip& clip,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea)
{
auto* process = processAt(processId);
if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) ||
(readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] == 0 ||
std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(),
[process](const auto& owned) { return &owned->base == process; }) ||
clip.frameCount != process->bytes[0x39] ||
!std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) {
return std::nullopt;
}
const u16 itemNumber = readLe16(*process, 0x04);
auto* npc = items.editNpcAnimation(itemNumber);
const auto* item = items.findItem(itemNumber);
if (npc == nullptr || item == nullptr || item->data.shape >= shapes.size() ||
npc->lastAnimation != readLe16(*process, 0x36)) {
return std::nullopt;
}
u8 nextFrame = static_cast<u8>(npc->frame + 1);
if ((clip.header[1] & 1) != 0 && (npc->moreFlags & 4) != 0 &&
nextFrame == clip.frameCount / 2) {
return std::nullopt;
}
if (nextFrame >= clip.frameCount && (clip.header[1] & 5) == 5) {
nextFrame = 1;
}
if (nextFrame >= clip.frameCount) {
return std::nullopt;
}
const u8 direction = process->bytes[0x38];
const auto metadata = getAnimationFrame(clip, direction, nextFrame);
if (!metadata || (metadata->bytes[5] & 2) == 0) {
return std::nullopt;
}
const auto step = decodeAnimationDisplacement(*metadata, direction, (clip.header[2] & 0x10) != 0);
if (!step) {
return std::nullopt;
}
const WorldPoint destination{static_cast<s32>(item->data.x) + step->x,
static_cast<s32>(item->data.y) + step->y,
static_cast<s32>(item->data.z) + step->z};
const auto sweep = resolveSolidLiveSweep(items, itemNumber, destination, shapes, fastArea);
if (!sweep || sweep->failed || sweep->failedDirections != 0 ||
!items.moveItem(itemNumber, static_cast<u16>(sweep->destination.x),
static_cast<u16>(sweep->destination.y), static_cast<u8>(sweep->destination.z))) {
process->bytes[0x3c] = 1;
return false;
}
npc->frame = nextFrame;
return true;
}
u16 ProcessKernel::hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity,
u32 timerTick, u16 (&groupCounts)[32])
{
@ -350,6 +460,7 @@ KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 (
const u16 id = addProcess(process->base);
processNames_[id] = "KeyboardProcess";
writeLe16(process->base, 0x18, static_cast<u16>(readLe16(process->base, 0x18) | 0x180));
keyboardSubscriberIds_.push_back(id);
keyboardProcess_ = std::move(process);
return keyboardProcess_.get();
}
@ -375,6 +486,30 @@ KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16
return keyDaemonProcess_.get();
}
ControllerProcessEntry* ProcessKernel::createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32])
{
if (controllerProcess_ != nullptr) {
throw std::logic_error("controller process already exists");
}
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
throw std::overflow_error("process table exhausted");
}
auto process = std::make_unique<ControllerProcessEntry>();
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
writeLe16(process->base, 0x00, 0x3aa6);
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
writeLe16(process->base, 0x18, static_cast<u16>(readLe16(process->base, 0x18) | 0x80));
process->extra[0] = 0x15;
process->extra[1] = 0x01;
process->extra[4] = 0x3c;
setLastAllocationSize(sizeof(ControllerProcessEntry));
const u16 id = addProcess(process->base);
processNames_[id] = "Controller";
keyboardSubscriberIds_.push_back(id);
controllerProcess_ = std::move(process);
return controllerProcess_.get();
}
void ProcessKernel::deliverSystemTimerEvent()
{
if (systemTimerProcess_ == nullptr) {
@ -504,6 +639,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id)
ownedGravityProcesses_.erase(gravity);
return;
}
const auto animation = std::find_if(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(),
[entry](const auto& process) { return &process->base == entry; });
if (animation != ownedAnimPrimitiveProcesses_.end()) {
ownedAnimPrimitiveProcesses_.erase(animation);
return;
}
const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(),
[entry](const auto& process) { return process.get() == entry; });
ownedProcesses_.erase(owned);
@ -526,6 +667,12 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) {
throw std::logic_error("key daemon process teardown is not ported");
}
if (controllerProcess_ != nullptr && entry == &controllerProcess_->base) {
throw std::logic_error("controller process teardown is not ported");
}
const bool ownedAnimationProcess = std::any_of(ownedAnimPrimitiveProcesses_.begin(),
ownedAnimPrimitiveProcesses_.end(),
[entry](const auto& process) { return &process->base == entry; });
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
[entry](const auto& process) { return &process->base == entry; });
const bool ownedGravityProcess = readLe16(*entry, 0x00) == 0x0610 &&
@ -534,12 +681,13 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset &&
std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(),
[entry](const auto& process) { return process.get() == entry; });
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess || id < 3 ||
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess &&
!ownedGravityProcess && !ownedAnimationProcess || id < 3 ||
readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 ||
readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) {
throw std::logic_error("item process child cleanup is not ported");
}
if (stand == ownedStandProcesses_.end() && !ownedGravityProcess &&
if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess &&
std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(),
[entry](const auto& process) { return process.get() == entry; })) {
throw std::logic_error("external process ownership is not ported");
@ -928,4 +1076,57 @@ bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector
return true;
}
bool ProcessKernel::queuePendingKeyEvent(const KeyEvent& event)
{
if ((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size() == keyEventOffset_) {
pendingKeyEventOverflowed_ = true;
return false;
}
pendingKeyEvents_[nextKeyEventOffset_] = event;
nextKeyEventOffset_ = static_cast<u8>((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size());
return true;
}
std::optional<KeyEvent> ProcessKernel::popPendingKeyEvent()
{
if (keyEventOffset_ == nextKeyEventOffset_) {
return std::nullopt;
}
const KeyEvent event = pendingKeyEvents_[keyEventOffset_];
keyEventOffset_ = static_cast<u8>((keyEventOffset_ + 1) % pendingKeyEvents_.size());
pendingKeyEventOverflowed_ = false;
return event;
}
u8 ProcessKernel::pendingKeyEventCount() const
{
return static_cast<u8>((nextKeyEventOffset_ + pendingKeyEvents_.size() - keyEventOffset_) %
pendingKeyEvents_.size());
}
bool ProcessKernel::pendingKeyEventOverflowed() const
{
return pendingKeyEventOverflowed_;
}
void ProcessKernel::dispatchPendingKeyEvents(
void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context)
{
while (auto event = popPendingKeyEvent()) {
const std::size_t subscriberCount = keyboardSubscriberIds_.size();
for (std::size_t index = 0; index < subscriberCount; ++index) {
const u16 id = keyboardSubscriberIds_[index];
auto* process = processAt(id);
if (!process || allocationSizeAt(id) < 0x34 ||
(readLe16(*process, 0x16) & 0x08) != 0 ||
(readLe16(*process, 0x18) & 0x180) != 0x80 ||
(reinterpret_cast<const u8*>(process)[0x32] & 0x10) == 0) {
continue;
}
KeyEvent copy = *event;
deliver(*process, 0x10, 0, copy, context);
}
}
}
} // namespace remorse

View file

@ -1,4 +1,5 @@
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
@ -153,6 +154,23 @@ std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap
return items;
}
std::optional<StagedFixedMapItem> findTeleportEgg(
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 eggId)
{
std::optional<StagedFixedMapItem> match;
for (const auto& item : items) {
if (item.data.shape >= shapes.size() || shapes[item.data.shape].family != 8 ||
item.data.frame != 1 || (item.data.quality & 0xff) != eggId) {
continue;
}
if (match) {
return std::nullopt;
}
match = item;
}
return match;
}
std::optional<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes)
{
@ -415,7 +433,7 @@ std::optional<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem&
LiveFixedMapItems::LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems)
: items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800)
: items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800)
{
if (!buildStagedItemBlockChains(items_)) {
throw std::invalid_argument("invalid live item IDs or coordinates");
@ -439,8 +457,36 @@ LiveFixedMapItems::LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
}
}
bool LiveFixedMapItems::initializeAvatar()
{
if (avatar_) {
return false;
}
avatar_.emplace();
avatar_->itemNumber = 1;
avatar_->data.shape = 1;
avatar_->data.npcNumber = 1;
npcAnimations_.resize(2);
return true;
}
bool LiveFixedMapItems::teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber)
{
if (!avatar_) {
return false;
}
avatar_->data.x = egg.data.x;
avatar_->data.y = egg.data.y;
avatar_->data.z = egg.data.z;
avatar_->data.mapNumber = mapNumber;
return true;
}
const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const
{
if (itemNumber == 1) {
return avatar_ ? &*avatar_ : nullptr;
}
for (const auto& item : items_) {
if (item.itemNumber == itemNumber) {
return &item;
@ -449,6 +495,19 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const
return nullptr;
}
const NpcAnimationState* LiveFixedMapItems::findNpcAnimation(u16 itemNumber) const
{
const auto* item = findItem(itemNumber);
return itemNumber < npcAnimations_.size() && item != nullptr && item->data.npcNumber != 0
? &npcAnimations_[itemNumber] : nullptr;
}
NpcAnimationState* LiveFixedMapItems::editNpcAnimation(u16 itemNumber)
{
return const_cast<NpcAnimationState*>(
static_cast<const LiveFixedMapItems*>(this)->findNpcAnimation(itemNumber));
}
u16 LiveFixedMapItems::containedParent(u16 itemNumber) const
{
return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0;
@ -517,11 +576,64 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item)
return true;
}
std::optional<std::vector<u16>> LiveFixedMapItems::hatchGlobEgg(u16 eggItemNumber,
const GlobObject& glob, const std::vector<ShapeTypeInfo>& shapes)
{
const auto* egg = findItem(eggItemNumber);
if (!egg || egg->data.shape >= shapes.size() || shapes[egg->data.shape].family != 3 ||
egg->data.quality == 0 || egg->data.quality != glob.index ||
isGlobHatched(eggItemNumber)) {
return std::nullopt;
}
std::vector<StagedFixedMapItem> children;
children.reserve(glob.entries.size());
for (const auto& entry : glob.entries) {
StagedFixedMapItem child;
child.recordIndex = static_cast<std::size_t>(-1);
child.data.x = static_cast<u16>((egg->data.x & ~0x1ff) + entry.x * 2 + 1);
child.data.y = static_cast<u16>((egg->data.y & ~0x1ff) + entry.y * 2 + 1);
child.data.z = static_cast<u8>(egg->data.z + entry.z);
child.data.shape = entry.shape;
child.data.frame = entry.frame;
child.data.flags = 0x82;
if (entry.shape == 0 || child.data.x > 0x7fff || child.data.y > 0x7fff) {
return std::nullopt;
}
children.push_back(child);
}
const std::size_t freeCount = static_cast<std::size_t>(std::count(
allocatedIds_.begin() + nextFreeItemNumber_, allocatedIds_.end(), false));
if (freeCount < children.size()) {
return std::nullopt;
}
std::vector<u16> childIds;
childIds.reserve(children.size());
for (auto& child : children) {
childIds.push_back(*allocateItem(child));
}
hatchedGlobIds_[eggItemNumber] = true;
return childIds;
}
bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const
{
return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber];
}
bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z)
{
if (x > 0x7fff || y > 0x7fff) {
return false;
}
if (itemNumber == 1) {
if (!avatar_) {
return false;
}
avatar_->data.x = x;
avatar_->data.y = y;
avatar_->data.z = std::min<u8>(z, 0xfa);
return true;
}
const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) {
return candidate.itemNumber == itemNumber;
});

View file

@ -39,7 +39,7 @@ struct SceneItem {
struct RenderNode {
SceneItem item;
DecodedShapeFrame decoded;
const DecodedShapeFrame* decoded = nullptr;
s32 left = 0;
s32 top = 0;
s32 right = 0;
@ -82,14 +82,27 @@ std::vector<SceneItem> collectSceneItems(
const FixedMap& fixedMap,
const std::vector<ShapeTypeInfo>& typeFlags,
const std::vector<GlobObject>& globs,
const MapRenderOptions& options)
const MapRenderOptions& options,
const LiveFixedMapItems* liveItems)
{
std::vector<SceneItem> pending;
pending.reserve(fixedMap.entries.size());
for (const FixedMapEntry& entry : fixedMap.entries) {
std::vector<const StagedFixedMapItem*> liveByRecord;
if (liveItems != nullptr) {
liveByRecord.resize(fixedMap.entries.size(), nullptr);
for (const auto& item : liveItems->mapItems()) {
if (item.recordIndex < liveByRecord.size()) {
liveByRecord[item.recordIndex] = &item;
}
}
}
for (std::size_t recordIndex = 0; recordIndex < fixedMap.entries.size(); ++recordIndex) {
const FixedMapEntry& entry = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr
? fixedMap.entries[recordIndex] : liveByRecord[recordIndex]->data;
const s32 scale = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr ? 1 : 2;
pending.push_back(SceneItem{
static_cast<s32>(entry.x),
static_cast<s32>(entry.y),
static_cast<s32>(entry.x) * scale,
static_cast<s32>(entry.y) * scale,
static_cast<s32>(entry.z),
entry.shape,
entry.frame,
@ -98,6 +111,16 @@ std::vector<SceneItem> collectSceneItems(
entry.mapNumber,
true});
}
if (liveItems != nullptr) {
for (const auto& item : liveItems->mapItems()) {
if (item.recordIndex == static_cast<std::size_t>(-1)) {
pending.push_back(SceneItem{static_cast<s32>(item.data.x) * 2,
static_cast<s32>(item.data.y) * 2, item.data.z, item.data.shape,
item.data.frame, item.data.flags, item.data.quality, item.data.mapNumber,
false});
}
}
}
std::vector<SceneItem> items;
for (std::size_t index = 0; index < pending.size(); ++index) {
@ -116,7 +139,10 @@ std::vector<SceneItem> collectSceneItems(
continue;
}
if (options.expandGlobs && info.family == 3 && item.fromFixed) {
const auto glob = findGlobObject(globs, item.quality);
const auto* stagedEgg = liveByRecord.empty() || index >= liveByRecord.size()
? nullptr : liveByRecord[index];
const auto glob = stagedEgg && liveItems->isGlobHatched(stagedEgg->itemNumber)
? std::nullopt : findGlobObject(globs, item.quality);
if (glob) {
for (const GlobObjectEntry& entry : glob->entries) {
pending.push_back(SceneItem{
@ -153,7 +179,7 @@ s32 screenY(const SceneItem& item)
return projectToScreen(WorldPoint{item.x, item.y, item.z}).y;
}
std::optional<DecodedShapeFrame> cachedDecode(
const DecodedShapeFrame* cachedDecode(
const ShapeArchive& archive,
std::map<std::pair<u32, u32>, DecodedShapeFrame>& cache,
u32 shape,
@ -162,28 +188,27 @@ std::optional<DecodedShapeFrame> cachedDecode(
const auto key = std::make_pair(shape, frame);
const auto found = cache.find(key);
if (found != cache.end()) {
return found->second;
return &found->second;
}
const auto decoded = decodeShapeFrame(archive, shape, frame);
if (!decoded) {
return std::nullopt;
return nullptr;
}
cache.emplace(key, *decoded);
return decoded;
return &cache.emplace(key, std::move(*decoded)).first->second;
}
std::vector<RenderNode> prepareRenderNodes(
const std::vector<SceneItem>& items,
const ShapeArchive& shapeArchive,
const std::vector<ShapeTypeInfo>& typeFlags)
const std::vector<ShapeTypeInfo>& typeFlags,
std::map<std::pair<u32, u32>, DecodedShapeFrame>& cache)
{
std::map<std::pair<u32, u32>, DecodedShapeFrame> cache;
std::vector<RenderNode> nodes;
std::vector<detail::RenderSortItem> sortItems;
nodes.reserve(items.size());
sortItems.reserve(items.size());
for (const SceneItem& item : items) {
const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame);
const auto* decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame);
if (!decoded) {
continue;
}
@ -193,13 +218,13 @@ std::vector<RenderNode> prepareRenderNodes(
const bool flipped = (item.flags & flagFlipped) != 0;
RenderNode node;
node.item = item;
node.decoded = *decoded;
node.decoded = decoded;
node.left = flipped
? bottomX + node.decoded.frame.xOffset - static_cast<s32>(node.decoded.frame.width)
: bottomX - node.decoded.frame.xOffset;
node.top = bottomY - node.decoded.frame.yOffset;
node.right = node.left + static_cast<s32>(node.decoded.frame.width);
node.bottom = node.top + static_cast<s32>(node.decoded.frame.height);
? bottomX + decoded->frame.xOffset - static_cast<s32>(decoded->frame.width)
: bottomX - decoded->frame.xOffset;
node.top = bottomY - decoded->frame.yOffset;
node.right = node.left + static_cast<s32>(decoded->frame.width);
node.bottom = node.top + static_cast<s32>(decoded->frame.height);
const ShapeTypeInfo& info = typeFlags[item.shape];
const s32 xDimension = static_cast<s32>(flipped ? info.y : info.x) * 32;
@ -251,15 +276,15 @@ std::vector<RenderNode> prepareRenderNodes(
void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette)
{
const bool flipped = (node.item.flags & flagFlipped) != 0;
for (u32 sourceY = 0; sourceY < node.decoded.frame.height; ++sourceY) {
for (u32 sourceY = 0; sourceY < node.decoded->frame.height; ++sourceY) {
const s32 destY = node.top - image.sourceTop + static_cast<s32>(sourceY);
if (destY < 0 || destY >= static_cast<s32>(image.height)) {
continue;
}
const std::size_t sourceRow = static_cast<std::size_t>(sourceY) * node.decoded.frame.width;
for (u32 sourceX = 0; sourceX < node.decoded.frame.width; ++sourceX) {
const u32 actualSourceX = flipped ? node.decoded.frame.width - 1 - sourceX : sourceX;
const s16 colorIndex = node.decoded.pixels[sourceRow + actualSourceX];
const std::size_t sourceRow = static_cast<std::size_t>(sourceY) * node.decoded->frame.width;
for (u32 sourceX = 0; sourceX < node.decoded->frame.width; ++sourceX) {
const u32 actualSourceX = flipped ? node.decoded->frame.width - 1 - sourceX : sourceX;
const s16 colorIndex = node.decoded->pixels[sourceRow + actualSourceX];
if (colorIndex < 0 || colorIndex >= 256) {
continue;
}
@ -293,7 +318,7 @@ ScreenPoint projectToScreen(const WorldPoint& point)
return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z};
}
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options)
std::optional<MapSceneRenderer> loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex)
{
const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT");
const auto globPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "GLOB.FLX");
@ -305,7 +330,7 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
}
const auto fixedArchive = loadFixedMapArchive(*fixedPath);
const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, options.mapIndex) : std::nullopt;
const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, mapIndex) : std::nullopt;
const auto globs = loadGlobObjects(*globPath);
const auto shapeArchive = loadShapeArchive(*shapePath);
const auto palette = loadPalette256(*palettePath);
@ -313,9 +338,15 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
if (!fixedMap || !globs || !shapeArchive || !palette || !typeFlags) {
return std::nullopt;
}
return MapSceneRenderer{std::move(*fixedMap), std::move(*globs), std::move(*shapeArchive),
*palette, std::move(*typeFlags), {}};
}
const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options);
auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags);
std::optional<RenderedMapImage> MapSceneRenderer::render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems)
{
const auto items = collectSceneItems(map, typeFlags, globs, options, liveItems);
auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames);
if (nodes.empty()) {
return std::nullopt;
}
@ -332,7 +363,7 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
}
RenderedMapImage image;
image.rawItemCount = static_cast<u32>(fixedMap->entries.size());
image.rawItemCount = static_cast<u32>(map.entries.size());
image.renderItemCount = static_cast<u32>(items.size());
image.decodedItemCount = static_cast<u32>(nodes.size());
image.fullWidth = maxRight - minLeft;
@ -361,12 +392,25 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
node.top >= image.sourceTop + static_cast<s32>(image.height)) {
continue;
}
paintNode(image, node, *palette);
paintNode(image, node, palette);
++image.paintedItemCount;
}
return image;
}
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options)
{
auto renderer = loadMapSceneRenderer(root, options.mapIndex);
return renderer ? renderer->render(options) : std::nullopt;
}
std::optional<RenderedMapImage> renderLiveMapPreview(const GameDataRoot& root,
const MapRenderOptions& options, const LiveFixedMapItems& items)
{
auto renderer = loadMapSceneRenderer(root, options.mapIndex);
return renderer ? renderer->render(options, &items) : std::nullopt;
}
bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image)
{
if (image.width == 0 || image.height == 0 || image.pixels.size() != static_cast<std::size_t>(image.width) * image.height) {

View file

@ -0,0 +1,29 @@
#include "remorse/usecode_vm.h"
#include <algorithm>
namespace remorse {
std::optional<UsecodeInterpreterState> UsecodeInterpreterState::initialize(
const std::vector<u8>& itemParameter)
{
if (itemParameter.size() > 0xcc) {
return std::nullopt;
}
UsecodeInterpreterState state;
state.stackTop -= itemParameter.size();
std::copy(itemParameter.begin(), itemParameter.end(),
state.valueStack.begin() + state.stackTop);
return state;
}
bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment)
{
if (callFrameCount >= 0x1f) {
return false;
}
callFrames[callFrameCount++] = UsecodeCallFrame{offset, segment};
return true;
}
} // namespace remorse

View file

@ -18,6 +18,7 @@
#include <algorithm>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <iomanip>
@ -43,10 +44,13 @@ constexpr remorse::s32 diagnosticItemRange = 48;
struct AppState {
remorse::GameDataRoot root;
remorse::u32 mapIndex = 1;
bool diagnostics = false;
remorse::ProcessKernel diagnosticKernel;
remorse::u16 diagnosticGroupCounts[32]{};
remorse::StandProcessEntry* diagnosticStand = nullptr;
remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr;
remorse::ControllerMovementState controllerMovement;
remorse::u16 animationProcessId = 0;
std::optional<remorse::LiveFixedMapItems> liveItems;
std::optional<remorse::StagedFixedMapItem> diagnosticItem;
remorse::u16 diagnosticItemProcessId = 0;
@ -57,7 +61,11 @@ struct AppState {
remorse::u32 standWakeCount = 0;
remorse::u32 diagnosticKeyEvents = 0;
std::mutex sceneMutex;
std::condition_variable renderWake;
bool renderRequested = false;
bool renderStop = false;
std::optional<remorse::RenderedMapImage> scene;
std::optional<remorse::MapSceneRenderer> renderer;
std::optional<remorse::AnimationClip> standAnimation;
std::optional<remorse::AnimationClip> walkAnimation;
std::optional<remorse::AnimationClip> runAnimation;
@ -71,7 +79,6 @@ struct AppState {
std::vector<std::uint8_t> dibPixels;
std::vector<std::uint8_t> viewPixels;
remorse::WorldPoint spawn{};
remorse::WorldPoint playerWorld{};
remorse::FastAreaRange fastArea{};
remorse::s32 minWorldX = 0;
remorse::s32 minWorldY = 0;
@ -86,6 +93,7 @@ struct AppState {
std::wstring loadError;
bool sceneLoaded = false;
std::thread sceneThread;
std::thread renderThread;
HDC backBufferDc = nullptr;
HBITMAP backBufferBitmap = nullptr;
HBITMAP previousBackBufferBitmap = nullptr;
@ -124,6 +132,16 @@ void setLoadFailure(AppState& state, const std::wstring& message)
state.sceneLoaded = true;
}
remorse::WorldPoint avatarWorld(const AppState& state)
{
const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr;
return avatar ? remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z}
: state.spawn;
}
bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items,
const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range);
void loadSceneAsync(HWND window, AppState& state)
{
state.sceneThread = std::thread([window, &state]() {
@ -153,6 +171,11 @@ void loadSceneAsync(HWND window, AppState& state)
return;
}
const auto stagedItems = remorse::stageFixedMapItems(*map);
if (!stagedItems) {
setLoadFailure(state, L"The fixed-map item cache could not be initialized.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath);
const auto globObjects = remorse::loadGlobObjects(*globPath);
@ -249,13 +272,38 @@ void loadSceneAsync(HWND window, AppState& state)
maxY = std::max(maxY, static_cast<remorse::s32>(entry.y));
}
const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0};
const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e);
if (state.mapIndex == 1 && !startingEgg) {
setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
if (state.mapIndex != 1 && !state.diagnostics) {
setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const remorse::WorldPoint spawn = startingEgg
? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z}
: remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0};
remorse::MapRenderOptions options;
options.mapIndex = state.mapIndex;
options.maxWidth = backingWidth;
options.maxHeight = backingHeight;
options.viewCenter = spawn;
auto scene = remorse::renderMapPreview(state.root, options);
remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems));
liveItems.initializeAvatar();
remorse::StagedFixedMapItem diagnosticStart;
diagnosticStart.data.x = static_cast<remorse::u16>(spawn.x / 2);
diagnosticStart.data.y = static_cast<remorse::u16>(spawn.y / 2);
diagnosticStart.data.z = static_cast<remorse::u8>(spawn.z);
liveItems.teleportAvatar(startingEgg ? *startingEgg : diagnosticStart,
static_cast<remorse::u8>(state.mapIndex));
auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex);
if (renderer) {
hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn));
}
auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt;
if (!scene) {
setLoadFailure(state, L"Map graphics or palette data could not be loaded.");
PostMessageW(window, sceneReadyMessage, 0, 0);
@ -272,7 +320,6 @@ void loadSceneAsync(HWND window, AppState& state)
{
std::lock_guard<std::mutex> lock(state.sceneMutex);
state.spawn = spawn;
state.playerWorld = spawn;
state.fastArea = remorse::calculateFastAreaRange(spawn);
state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
state.collisionBodies = std::move(collisionBodies);
@ -286,15 +333,14 @@ void loadSceneAsync(HWND window, AppState& state)
state.maxWorldX = maxX;
state.maxWorldY = maxY;
state.scene = std::move(scene);
state.renderer = std::move(renderer);
state.dibPixels = std::move(dibPixels);
state.standAnimation = *standAnimation;
state.walkAnimation = *walkAnimation;
state.runAnimation = *runAnimation;
state.playerFrames = std::move(playerFrames);
state.playerPalette = *palette;
if (stagedItems) {
state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems));
}
state.liveItems.emplace(std::move(liveItems));
state.sceneLoaded = true;
}
} catch (const std::exception& error) {
@ -306,6 +352,78 @@ void loadSceneAsync(HWND window, AppState& state)
});
}
bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items,
const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range)
{
std::vector<remorse::u16> 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<remorse::LiveFixedMapItems> snapshot;
remorse::WorldPoint center{};
{
std::unique_lock<std::mutex> 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<remorse::s32>(
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<std::uint8_t> 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<std::mutex> lock(state.sceneMutex);
if (state.renderStop) {
return;
}
state.scene = std::move(scene);
state.dibPixels = std::move(pixels);
}
PostMessageW(window, sceneReadyMessage, 0, 0);
}
});
}
void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font)
{
const int saved = SaveDC(device);
@ -316,41 +434,6 @@ void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLOR
RestoreDC(device, saved);
}
bool isKeyDown(int key)
{
return (GetAsyncKeyState(key) & 0x8000) != 0;
}
std::optional<remorse::u8> readMovementDirection()
{
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return remorse::controllerDirectionFromScan(0x47);
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return remorse::controllerDirectionFromScan(0x49);
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return remorse::controllerDirectionFromScan(0x4f);
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return remorse::controllerDirectionFromScan(0x51);
const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8);
const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6);
const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2);
const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4);
if (up && left) return remorse::controllerDirectionFromScan(0x47);
if (up && right) return remorse::controllerDirectionFromScan(0x49);
if (down && left) return remorse::controllerDirectionFromScan(0x4f);
if (down && right) return remorse::controllerDirectionFromScan(0x51);
if (up) return remorse::controllerDirectionFromScan(0x48);
if (right) return remorse::controllerDirectionFromScan(0x4d);
if (down) return remorse::controllerDirectionFromScan(0x50);
if (left) return remorse::controllerDirectionFromScan(0x4b);
return std::nullopt;
}
bool isWalkRequested()
{
remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0;
if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01;
if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02;
return remorse::controllerWalkRequested(modifiers);
}
void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
int sourceLeft, int sourceTop, std::size_t viewStride)
{
@ -377,10 +460,9 @@ void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
}
const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame];
const int actorX = static_cast<int>(state.scene->width / 2) +
static_cast<int>(std::lround(state.playerOffsetX)) - sourceLeft;
const int actorY = static_cast<int>(state.scene->height / 2) +
static_cast<int>(std::lround(state.playerOffsetY)) - sourceTop;
const auto avatarScreen = remorse::projectToScreen(avatarWorld(state));
const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft;
const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop;
const int spriteLeft = actorX + sprite.frame.xOffset;
const int spriteTop = actorY + sprite.frame.yOffset;
const bool flipped = remorse::isAnimationFrameFlipped(*metadata);
@ -507,10 +589,9 @@ void paintWindow(HWND window, AppState& state)
const int viewWidth = std::min(clientWidth, static_cast<int>(state.scene->width));
const int viewHeight = std::min(clientHeight, static_cast<int>(state.scene->height));
const int centeredLeft = static_cast<int>(state.scene->width / 2) +
static_cast<int>(std::lround(state.playerOffsetX)) - viewWidth / 2;
const int centeredTop = static_cast<int>(state.scene->height / 2) +
static_cast<int>(std::lround(state.playerOffsetY)) - viewHeight / 2;
const auto avatarScreen = remorse::projectToScreen(avatarWorld(state));
const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2;
const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2;
const int sourceLeft = std::clamp(centeredLeft, 0, static_cast<int>(state.scene->width) - viewWidth);
const int sourceTop = std::clamp(centeredTop, 0, static_cast<int>(state.scene->height) - viewHeight);
@ -525,6 +606,10 @@ void paintWindow(HWND window, AppState& state)
static_cast<std::size_t>(viewWidth) * 3);
}
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
if (!state.diagnostics) {
finishPaint();
return;
}
RECT hud{0, 0, viewWidth, 80};
HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29));
@ -538,10 +623,11 @@ void paintWindow(HWND window, AppState& state)
DeleteObject(hudLine);
std::wostringstream label;
const remorse::WorldPoint playerWorld = avatarWorld(state);
label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex
<< L" X " << state.playerWorld.x
<< L" Y " << state.playerWorld.y
<< L" Z " << static_cast<int>(state.playerWorld.z)
<< L" X " << playerWorld.x
<< L" Y " << playerWorld.y
<< L" Z " << static_cast<int>(playerWorld.z)
<< L" DIR " << std::setw(2) << static_cast<int>(state.playerDirection)
<< L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE")
<< L" WASD / KEYPAD SHIFT RUN";
@ -570,7 +656,7 @@ void paintWindow(HWND window, AppState& state)
SetTextColor(device, RGB(74, 207, 184));
DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem(
state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt;
playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt;
if (state.diagnosticItem || nearbyItem) {
const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem;
std::wostringstream itemStatus;
@ -603,10 +689,6 @@ void updatePlayer(HWND window, AppState& state)
0.0, 0.25);
state.lastTick = now;
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
DestroyWindow(window);
return;
}
if (GetForegroundWindow() != window) {
return;
}
@ -616,11 +698,19 @@ void updatePlayer(HWND window, AppState& state)
}
state.simulationAccumulator += elapsed;
const auto direction = readMovementDirection();
bool changed = false;
while (state.simulationAccumulator >= simulationTickSeconds) {
state.simulationAccumulator -= simulationTickSeconds;
state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry,
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
auto& app = *static_cast<AppState*>(context);
if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) {
app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0);
}
}, &state);
const auto movement = state.controllerMovement.request();
state.diagnosticKernel.deliverSystemTimerEvent();
if (state.diagnostics) {
const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0;
const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand);
state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) {
@ -664,53 +754,69 @@ void updatePlayer(HWND window, AppState& state)
if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) {
++state.standWakeCount;
}
changed = true;
if (!direction) {
}
changed = changed || state.diagnostics;
if (movement.animation == 0) {
if (state.animationProcessId != 0) {
auto* process = state.diagnosticKernel.processAt(state.animationProcessId);
process->bytes[0x18] |= 4;
state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts);
state.animationProcessId = 0;
}
changed = changed || state.playerAnimation != 0 || state.playerFrame != 0;
state.playerAnimation = 0;
state.playerFrame = 0;
continue;
}
const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3;
const remorse::u8 requestedAnimation = movement.animation;
const remorse::AnimationClip& clip = requestedAnimation == 1
? *state.walkAnimation : *state.runAnimation;
if (state.playerAnimation != requestedAnimation) {
state.playerAnimation = requestedAnimation;
state.playerFrame = 0;
} else {
state.playerFrame = static_cast<remorse::u8>(
(state.playerFrame + 1) % clip.frameCount);
}
state.playerDirection = *direction;
const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame);
if (metadata) {
const auto step = remorse::hostMovementStep(
*metadata, state.playerDirection, (clip.header[2] & 0x10) != 0);
if (step) {
const remorse::WorldPoint destination{
state.playerWorld.x + step->x,
state.playerWorld.y + step->y,
state.playerWorld.z + step->z};
const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination);
const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn);
const double nextOffsetX = destinationScreen.x - spawnScreen.x;
const double nextOffsetY = destinationScreen.y - spawnScreen.y;
const bool withinMapBounds = destination.x >= state.minWorldX &&
destination.x <= state.maxWorldX && destination.y >= state.minWorldY &&
destination.y <= state.maxWorldY;
const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 &&
std::abs(nextOffsetY) <= backingHeight / 2 - 16;
if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody(
state.playerCollisionBody, destination, state.collisionBodies)) {
state.playerWorld = destination;
state.fastArea = remorse::calculateFastAreaRange(destination);
state.playerCollisionBody.location = destination;
state.playerOffsetX = nextOffsetX;
state.playerOffsetY = nextOffsetY;
}
if (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation ||
state.playerDirection != movement.direction) {
if (state.animationProcessId != 0) {
auto* process = state.diagnosticKernel.processAt(state.animationProcessId);
process->bytes[0x18] |= 4;
state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts);
}
auto* process = state.diagnosticKernel.createAnimPrimitiveProcess(
state.diagnosticKernel.activeGroup(), 1, requestedAnimation, movement.direction,
clip, state.diagnosticGroupCounts);
state.animationProcessId = static_cast<remorse::u16>(process->base.bytes[2] |
(static_cast<remorse::u16>(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<AppState*>(context);
if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) {
const remorse::AnimationClip& activeClip = app.playerAnimation == 1
? *app.walkAnimation : *app.runAnimation;
const auto* item = app.liveItems->findItem(1);
app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId,
*app.liveItems, activeClip, app.shapeTypes,
remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z}));
}
}, &state);
state.fastArea = fastArea;
state.playerFrame = state.liveItems->findNpcAnimation(1)->frame;
const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(avatarWorld(state));
const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn);
state.playerOffsetX = destinationScreen.x - spawnScreen.x;
state.playerOffsetY = destinationScreen.y - spawnScreen.y;
const bool moved = avatar->data.x != beforeMove.x || avatar->data.y != beforeMove.y ||
avatar->data.z != beforeMove.z;
const bool hatched = moved && hatchGlobsInFastArea(
*state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state)));
if (state.renderThread.joinable() && (moved || hatched)) {
state.renderRequested = true;
state.renderWake.notify_one();
}
changed = true;
}
@ -743,13 +849,47 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
updatePlayer(window, *state);
}
return 0;
case WM_KILLFOCUS:
state->controllerMovement.clear();
while (state->diagnosticKernel.popPendingKeyEvent()) {}
return 0;
case WM_KEYDOWN:
if (wParam == 'F') {
case WM_KEYUP:
if (wParam == VK_ESCAPE && message == WM_KEYDOWN) {
DestroyWindow(window);
return 0;
}
{
remorse::KeyEvent event{};
event.scanCode = static_cast<remorse::u8>((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<std::mutex> lock(state->sceneMutex);
if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted &&
state->diagnosticItemProcessId == 0) {
const remorse::WorldPoint playerWorld = avatarWorld(*state);
state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem(
state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt;
playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt;
}
if (state->diagnosticItem && state->diagnosticItemProcessId == 0 &&
state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber &&
@ -764,7 +904,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
}
return 0;
case WM_CHAR:
if (wParam > 0 && wParam <= 0xff) {
if (state->diagnostics && wParam > 0 && wParam <= 0xff) {
remorse::KeyEvent lastEvent{};
lastEvent.character = static_cast<remorse::u8>(wParam);
lastEvent.scanCode = static_cast<remorse::u8>((lParam >> 16) & 0xff);
@ -785,6 +925,12 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
paintWindow(window, *state);
return 0;
case sceneReadyMessage: {
{
std::lock_guard<std::mutex> lock(state->sceneMutex);
if (state->sceneLoaded && state->renderer && !state->renderThread.joinable()) {
startLiveRenderer(window, *state);
}
}
InvalidateRect(window, nullptr, FALSE);
return 0;
}
@ -793,6 +939,14 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
if (state->sceneThread.joinable()) {
state->sceneThread.join();
}
{
std::lock_guard<std::mutex> lock(state->sceneMutex);
state->renderStop = true;
}
state->renderWake.notify_one();
if (state->renderThread.joinable()) {
state->renderThread.join();
}
if (state->backBufferDc) {
SelectObject(state->backBufferDc, state->previousBackBufferBitmap);
DeleteObject(state->backBufferBitmap);
@ -811,11 +965,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
{
remorse::installCrashDiagnostics();
remorse::u32 mapIndex = 1;
if (commandLine && *commandLine) {
wchar_t* end = nullptr;
const unsigned long parsed = std::wcstoul(commandLine, &end, 0);
if (end != commandLine && parsed <= 255) {
mapIndex = static_cast<remorse::u32>(parsed);
bool diagnostics = false;
std::wistringstream arguments(commandLine ? commandLine : L"");
std::wstring argument;
while (arguments >> argument) {
if (argument == L"--diagnostics") {
diagnostics = true;
} else {
wchar_t* end = nullptr;
const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0);
if (end != argument.c_str() && *end == L'\0' && parsed <= 255) {
mapIndex = static_cast<remorse::u32>(parsed);
}
}
}
@ -835,13 +996,17 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
AppState state;
state.root = *root;
state.mapIndex = mapIndex;
state.diagnostics = diagnostics;
for (int index = 0; index < 3; ++index) {
state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts);
}
state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts);
state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts);
state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts);
state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts);
state.diagnosticKernel.createControllerProcess(1, state.diagnosticGroupCounts);
if (diagnostics) {
state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts);
state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts);
}
WNDCLASSEXW windowClass{};
windowClass.cbSize = sizeof(windowClass);
@ -859,7 +1024,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
RECT bounds{0, 0, initialClientWidth, initialClientHeight};
AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE);
HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW,
HWND window = CreateWindowExW(0, windowClassName,
diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top,
nullptr, nullptr, instance, &state);
if (!window) {

View file

@ -100,6 +100,29 @@ int main()
assert(stand.has_value() && stand->frameCount > 0);
assert(walk.has_value() && walk->frameCount == 17);
assert(run.has_value() && run->frameCount == 12);
for (const remorse::AnimationClip* clip : {&*walk, &*run}) {
assert(clip->header[1] == 5);
for (remorse::u8 direction = 0; direction < 16; ++direction) {
for (remorse::u8 frame = 1; frame < clip->frameCount; ++frame) {
const auto metadata = remorse::getAnimationFrame(*clip, direction, frame);
assert(metadata && (metadata->bytes[5] & 2) != 0);
}
}
}
auto startClip = *walk;
startClip.header[1] = 1;
assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 8);
assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 0);
startClip.header[1] = 5;
assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 16);
startClip.header[1] = 4;
assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 0);
assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 1);
assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 3) == 2);
assert(remorse::selectAnimationStartFrame(startClip, false, true, false, false, 0) == 2);
assert(remorse::selectAnimationStartFrame(startClip, false, true, false, true, 2) == 2);
startClip.header[1] = 0;
assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 0);
assert(remorse::getAnimationFrame(*walk, 0, 0).has_value());
assert(remorse::getAnimationFrame(*run, 15, 11).has_value());
for (remorse::u8 direction : {remorse::u8{6}, remorse::u8{7}, remorse::u8{10}, remorse::u8{11}}) {

View file

@ -1,6 +1,8 @@
#include "remorse/animation_archive.h"
#include "remorse/collision.h"
#include "remorse/entity_dispatch_entry.h"
#include "remorse/fixed_map.h"
#include "remorse/isometric_controls.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
@ -877,8 +879,139 @@ int main()
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
keyboardEvent.character = 0x41;
assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
remorse::ProcessKernel inputKernel;
assert(!inputKernel.popPendingKeyEvent());
for (remorse::u8 index = 0; index < 31; ++index) {
remorse::KeyEvent queued{};
queued.scanCode = index;
assert(inputKernel.queuePendingKeyEvent(queued));
}
assert(inputKernel.pendingKeyEventCount() == 31);
assert(!inputKernel.queuePendingKeyEvent({}));
assert(inputKernel.pendingKeyEventOverflowed());
for (remorse::u8 index = 0; index < 31; ++index) {
const auto queued = inputKernel.popPendingKeyEvent();
assert(queued && queued->scanCode == index);
}
assert(inputKernel.pendingKeyEventCount() == 0 && !inputKernel.pendingKeyEventOverflowed());
remorse::KeyEvent wrapped{};
wrapped.scanCode = 0x47;
assert(inputKernel.queuePendingKeyEvent(wrapped));
assert(inputKernel.popPendingKeyEvent()->scanCode == 0x47);
remorse::u16 inputGroups[32]{};
auto* inputKeyboard = inputKernel.createKeyboardProcess(1, inputGroups);
auto* inputController = inputKernel.createControllerProcess(1, inputGroups);
assert(inputController && inputController->base.bytes[0x00] == 0xa6 &&
inputController->base.bytes[0x01] == 0x3a);
assert(inputController->base.bytes[0x17] == 0x03 && inputController->extra[4] == 0x3c);
assert(!inputKeyboard->extra[0]);
assert(inputKernel.queuePendingKeyEvent(wrapped));
wrapped.scanCode = 0x48;
assert(inputKernel.queuePendingKeyEvent(wrapped));
std::vector<remorse::u8> deliveredScans;
inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process,
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
assert(selector == 0x10 && filter == 0);
assert(process.bytes[0x00] == 0xa6);
static_cast<std::vector<remorse::u8>*>(context)->push_back(event.scanCode);
}, &deliveredScans);
assert((deliveredScans == std::vector<remorse::u8>{0x47, 0x48}));
assert(inputKernel.pendingKeyEventCount() == 0);
remorse::ControllerMovementState deliveredMovement;
wrapped.scanCode = 0x48;
wrapped.field8 = 1;
assert(inputKernel.queuePendingKeyEvent(wrapped));
inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process,
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
assert(process.bytes[0] == 0xa6 && selector == 0x10 && filter == 0);
static_cast<remorse::ControllerMovementState*>(context)->handleDirectionalKey(
event.scanCode, event.modifiers, event.field8 != 0);
}, &deliveredMovement);
assert(deliveredMovement.request().animation == 1 && deliveredMovement.request().direction == 14);
wrapped.field8 = 0;
assert(inputKernel.queuePendingKeyEvent(wrapped));
inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&,
remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) {
static_cast<remorse::ControllerMovementState*>(context)->handleDirectionalKey(
event.scanCode, event.modifiers, event.field8 != 0);
}, &deliveredMovement);
assert(deliveredMovement.request().animation == 0);
assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0);
assert(keyboard->extra[0] == 0x21);
remorse::ProcessKernel animationKernel;
remorse::u16 animationGroups[32]{};
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
animationKernel.createProcess(1, animationGroups);
}
remorse::AnimationClip walking{};
walking.header = {17, 4, 0, 0};
walking.frameCount = 17;
auto* animation = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups);
assert(animationKernel.processAt(3) == &animation->base);
assert(animationKernel.allocationSizeAt(3) == 0x5b && animationGroups[1] == 4);
assert(animationKernel.findProcessForItemAndType(1, 0xf0) == &animation->base);
assert(animation->base.bytes[0] == 0x57 && animation->base.bytes[1] == 0x2a);
assert(animation->base.bytes[0x16] == 0 && animation->base.bytes[0x17] == 0x08);
assert(animation->extra[0] == 1 && animation->extra[4] == 1 && animation->extra[6] == 6);
assert(animation->extra[7] == 17 && animation->extra[0x18] == 17 && animation->extra[0x19] == 4);
remorse::LiveFixedMapItems animationItems({});
assert(animationItems.initializeAvatar());
assert(animationKernel.startAnimPrimitiveProcess(3, animationItems, walking));
const auto* npcAnimation = animationItems.findNpcAnimation(1);
assert(npcAnimation && npcAnimation->lastAnimation == 1 && npcAnimation->frame == 0);
assert(!animationKernel.startAnimPrimitiveProcess(3, animationItems, walking));
auto* repeatedWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups);
assert(animationKernel.startAnimPrimitiveProcess(4, animationItems, walking));
assert(repeatedWalk->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 1);
auto* turning = animationKernel.createAnimPrimitiveProcess(1, 1, 0, 6, walking, animationGroups);
assert(animationKernel.startAnimPrimitiveProcess(5, animationItems, walking));
assert(turning->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 0);
remorse::StagedFixedMapItem animationSpawn{};
animationSpawn.data.x = 512;
animationSpawn.data.y = 512;
assert(animationItems.teleportAvatar(animationSpawn, 1));
walking.frames.resize(17 * 8);
auto& nextWalkFrame = walking.frames[3 * 17 + 1];
nextWalkFrame.bytes[4] = 1;
nextWalkFrame.bytes[5] = 2;
std::vector<remorse::ShapeTypeInfo> animationShapes(2);
animationShapes[1].x = animationShapes[1].y = animationShapes[1].z = 2;
auto& movingNpc = *animationItems.editNpcAnimation(1);
movingNpc.lastAnimation = 1;
movingNpc.frame = 0;
const auto animationArea = remorse::calculateFastAreaRange({512, 512, 0});
assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems,
walking, animationShapes, animationArea) == true);
assert(animationItems.findItem(1)->data.x == 514 && animationItems.findItem(1)->data.y == 514);
assert(movingNpc.frame == 1);
nextWalkFrame.bytes[4] = 100;
movingNpc.frame = 0;
remorse::StagedFixedMapItem animationWall{};
animationWall.itemNumber = 0x100;
animationWall.data.shape = 2;
animationWall.data.x = 650;
animationWall.data.y = 650;
animationShapes.push_back(animationShapes[1]);
animationShapes[2].flags = 2;
assert(animationItems.insertItem(animationWall));
assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems,
walking, animationShapes, animationArea) == false);
assert(animationItems.findItem(1)->data.x == 514 && movingNpc.frame == 0);
assert(animation->extra[0x0a] == 1);
walking.header[1] = 5;
nextWalkFrame.bytes[4] = 1;
auto* twoStepWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups);
assert(animationKernel.startAnimPrimitiveProcess(6, animationItems, walking));
assert(movingNpc.frame == 8 && twoStepWalk->extra[7] == 17);
movingNpc.frame = 16;
assert(animationKernel.advanceGroundedAnimPrimitive(6, animationItems,
walking, animationShapes, animationArea) == true);
assert(movingNpc.frame == 1 && animationItems.findItem(1)->data.x == 516);
twoStepWalk->base.bytes[0x18] |= 4;
animationKernel.terminateProcess(6, animationGroups);
assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0);
assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1));
return 0;
}

View file

@ -1,6 +1,7 @@
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
@ -235,6 +236,24 @@ int main()
assert(allocatedItems.allocateItem(newItem) == 0x107);
newItem.data.x = 0x8000;
assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108));
remorse::StagedFixedMapItem globEgg;
globEgg.itemNumber = 0x100;
globEgg.data.x = 0x403;
globEgg.data.y = 0x601;
globEgg.data.z = 12;
globEgg.data.shape = 3;
globEgg.data.quality = 7;
remorse::LiveFixedMapItems hatchedItems({globEgg});
std::vector<remorse::ShapeTypeInfo> globShapes(4);
globShapes[3].family = 3;
remorse::GlobObject glob{7, {{2, 5, 3, 1, 2}}};
const auto childIds = hatchedItems.hatchGlobEgg(0x100, glob, globShapes);
assert(childIds && *childIds == std::vector<remorse::u16>{0x101});
const auto* child = hatchedItems.findItem(0x101);
assert(child && child->recordIndex == static_cast<std::size_t>(-1));
assert(child->data.x == 0x405 && child->data.y == 0x60b && child->data.z == 15);
assert(child->data.flags == 0x82 && child->data.frame == 2);
assert(hatchedItems.isGlobHatched(0x100) && !hatchedItems.hatchGlobEgg(0x100, glob, globShapes));
remorse::LiveFixedMapItems movingItems(blockItems);
remorse::ProcessKernel movingKernel;
remorse::u16 movingGroups[32]{};
@ -266,7 +285,18 @@ int main()
candidate.itemNumber = 0;
assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0);
assert(cachedItems->front().recordIndex < retailMap->entries.size());
const remorse::LiveFixedMapItems retailLiveItems(*cachedItems);
remorse::LiveFixedMapItems retailLiveItems(*cachedItems);
assert(!retailLiveItems.findItem(1));
assert(retailLiveItems.initializeAvatar());
assert(!retailLiveItems.initializeAvatar());
assert(retailLiveItems.findItem(1)->data.shape == 1);
assert(retailLiveItems.findItem(1)->data.frame == 0);
assert(retailLiveItems.findItem(1)->data.npcNumber == 1);
assert(retailLiveItems.teleportAvatar(cachedItems->front(), 1));
assert(retailLiveItems.findItem(1)->data.x == cachedItems->front().data.x);
assert(retailLiveItems.findItem(1)->data.mapNumber == 1);
assert(retailLiveItems.moveItem(1, 100, 200, 5));
assert(retailLiveItems.findItem(1)->data.x == 100 && retailLiveItems.findItem(1)->data.y == 200);
assert(retailLiveItems.findItem(cachedItems->front().itemNumber)->recordIndex ==
cachedItems->front().recordIndex);
for (const auto& item : *cachedItems) {

View file

@ -1,8 +1,11 @@
#include "remorse/collision.h"
#include "remorse/file_system.h"
#include "remorse/flex_archive.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include "remorse/usecode_vm.h"
#include <cassert>
#include <filesystem>
@ -69,6 +72,38 @@ int main()
assert(fixedMap && typeFlags);
const auto stagedItems = remorse::stageFixedMapItems(*fixedMap);
assert(stagedItems && !stagedItems->empty());
const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e);
assert(spawnEgg);
const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX");
const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt;
assert(globs);
remorse::LiveFixedMapItems spawnedItems(*stagedItems);
const auto fastArea = remorse::calculateFastAreaRange({
spawnEgg->data.x * 2, spawnEgg->data.y * 2, spawnEgg->data.z});
unsigned hatched = 0;
for (const auto& egg : *stagedItems) {
if (egg.data.shape >= typeFlags->size() || (*typeFlags)[egg.data.shape].family != 3 ||
!remorse::isWorldPointInFastArea(egg.data.x * 2, egg.data.y * 2, fastArea)) continue;
for (const auto& glob : *globs) {
if (glob.index == egg.data.quality) {
const auto children = spawnedItems.hatchGlobEgg(egg.itemNumber, glob, *typeFlags);
if (children) hatched += static_cast<unsigned>(children->size());
break;
}
}
}
unsigned scriptChildren = 0;
for (const auto& item : spawnedItems.mapItems()) {
if (item.recordIndex != static_cast<std::size_t>(-1) || item.data.shape >= typeFlags->size()) continue;
const remorse::UsecodeItemIdentity childIdentity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false};
const auto use = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, childIdentity,
remorse::UsecodeClassBases{0, 0x800, 0x900}, 2, 1);
if (use) {
++scriptChildren;
}
}
assert(hatched == 4 && scriptChildren == 0);
const auto& staged = stagedItems->front();
assert(staged.data.shape < typeFlags->size());
const remorse::UsecodeItemIdentity stagedIdentity{staged.itemNumber, staged.data.shape,
@ -100,6 +135,18 @@ int main()
rechargeItem, retailBases, 0x200, 9);
assert(eligibleRelease && eligibleRelease->classId == 0x138 &&
eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102);
auto interpreter = remorse::UsecodeInterpreterState::initialize({0x00, 0x01});
assert(interpreter && interpreter->stackTop == 0xca && interpreter->stackLimit == 199);
assert(interpreter->valueStack[0xca] == 0x00 && interpreter->valueStack[0xcb] == 0x01);
assert(interpreter->pushCodeAddress(eligibleRelease->classId, 9));
assert(interpreter->callFrameCount == 1 && interpreter->callFrames[0].offset == 0x138 &&
interpreter->callFrames[0].segment == 9);
for (unsigned index = 1; index < 0x1f; ++index) {
assert(interpreter->pushCodeAddress(static_cast<remorse::u16>(index), 0));
}
assert(!interpreter->pushCodeAddress(0xffff, 0));
assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0);
assert(!remorse::UsecodeInterpreterState::initialize(std::vector<remorse::u8>(0xcd)));
assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
rechargeItem, retailBases, 0, 9));
std::vector<remorse::u8> ownerRows(26);

View file

@ -5,6 +5,22 @@
int main()
{
remorse::ControllerMovementState controller;
assert(controller.request().animation == 0);
controller.handleDirectionalKey(0x48, 0, true);
assert(controller.request().animation == 1 && controller.request().direction == 14);
controller.handleDirectionalKey(0x4d, 1, true);
assert(controller.request().animation == 3 && controller.request().direction == 2);
controller.handleDirectionalKey(0x4d, 1, false);
assert(controller.request().animation == 3 && controller.request().direction == 14);
controller.handleDirectionalKey(0x48, 0, false);
assert(controller.request().animation == 0 && controller.request().direction == 14);
controller.handleDirectionalKey(0x49, 0x20, true);
assert(controller.request().animation == 0);
controller.handleDirectionalKey(0x47, 0x40, true);
assert(controller.request().animation == 3 && controller.request().direction == 12);
controller.clear();
assert(controller.request().animation == 0);
assert(remorse::controllerWalkRequested(0));
assert(!remorse::controllerWalkRequested(0x01));
assert(!remorse::controllerWalkRequested(0x02));

View file

@ -1,10 +1,14 @@
#include "remorse/collision.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
#include <algorithm>
#include <cassert>
#include <filesystem>
#include <utility>
int main()
{
@ -51,5 +55,100 @@ int main()
const remorse::ScreenPoint center = remorse::projectToScreen(*options.viewCenter);
assert(centeredImage->sourceLeft == center.x - static_cast<remorse::s32>(options.maxWidth / 2));
assert(centeredImage->sourceTop == center.y - static_cast<remorse::s32>(options.maxHeight / 2));
const auto typesPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX");
assert(typesPath && globPath);
const auto shapeTypes = remorse::loadTypeFlags(*typesPath);
const auto globs = remorse::loadGlobObjects(*globPath);
assert(shapeTypes && shapeTypes->size() > 1 && globs);
const auto stagedItems = remorse::stageFixedMapItems(*fixedMap);
assert(stagedItems);
const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e);
assert(startingEgg && startingEgg->itemNumber >= 0x100);
assert((startingEgg->data.quality & 0xff) == 0x1e && startingEgg->data.frame == 1);
assert(startingEgg->data.x > 0 && startingEgg->data.y > 0);
assert(startingEgg->data.x * 2 == fixedMap->entries[startingEgg->recordIndex].x);
assert(startingEgg->data.y * 2 == fixedMap->entries[startingEgg->recordIndex].y);
const auto obstacles = remorse::collectMapCollisionBodies(*fixedMap, *shapeTypes, *globs);
const remorse::WorldPoint spawn{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z};
options.maxWidth = 320;
options.maxHeight = 200;
options.viewCenter = spawn;
const auto startingScene = remorse::renderMapPreview(*root, options);
assert(startingScene && startingScene->paintedItemCount > 0);
remorse::LiveFixedMapItems liveSceneItems(*stagedItems);
auto cachedRenderer = remorse::loadMapSceneRenderer(*root, 1);
assert(cachedRenderer);
const auto liveBefore = cachedRenderer->render(options, &liveSceneItems);
const auto samePixels = [](const auto& left, const auto& right) {
return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(),
[](const auto& lhs, const auto& rhs) {
return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue;
});
};
assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels));
const remorse::s32 redrawRadius = static_cast<remorse::s32>(
options.maxWidth + options.maxHeight * 2 + 512);
options.worldRect = remorse::WorldRect{spawn.x - redrawRadius, spawn.y - redrawRadius,
spawn.x + redrawRadius, spawn.y + redrawRadius};
const auto boundedScene = cachedRenderer->render(options, &liveSceneItems);
assert(boundedScene && samePixels(boundedScene->pixels, liveBefore->pixels));
options.worldRect.reset();
const auto nearEgg = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) {
return item.data.shape < shapeTypes->size() &&
(*shapeTypes)[item.data.shape].family == 3 && item.data.quality != 0 &&
std::any_of(globs->begin(), globs->end(), [&](const auto& object) {
return object.index == item.data.quality;
});
});
assert(nearEgg != stagedItems->end());
{
options.viewCenter = remorse::WorldPoint{
nearEgg->data.x * 2, nearEgg->data.y * 2, nearEgg->data.z};
const auto unhatchedScene = cachedRenderer->render(options, &liveSceneItems);
assert(unhatchedScene);
const auto glob = std::find_if(globs->begin(), globs->end(), [&](const auto& object) {
return object.index == nearEgg->data.quality;
});
assert(glob != globs->end());
const auto childIds = liveSceneItems.hatchGlobEgg(nearEgg->itemNumber, *glob, *shapeTypes);
assert(childIds && childIds->size() == glob->entries.size());
const auto hatchedScene = cachedRenderer->render(options, &liveSceneItems);
assert(hatchedScene && samePixels(hatchedScene->pixels, unhatchedScene->pixels));
for (const remorse::u16 childId : *childIds) {
const auto* child = liveSceneItems.findItem(childId);
assert(child && liveSceneItems.moveItem(childId,
static_cast<remorse::u16>(child->data.x + 512),
static_cast<remorse::u16>(child->data.y + 512), child->data.z));
}
const auto movedScene = cachedRenderer->render(options, &liveSceneItems);
assert(movedScene && !samePixels(movedScene->pixels, hatchedScene->pixels));
}
options.viewCenter = spawn;
auto visibleItem = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) {
if (item.data.shape >= shapeTypes->size() || (item.data.flags & 0x10) != 0 ||
((*shapeTypes)[item.data.shape].flags & 0x400) != 0) {
return false;
}
const auto family = (*shapeTypes)[item.data.shape].family;
if (family == 3 || family == 4 || family == 7 || family == 8) {
return false;
}
return true;
});
assert(visibleItem != stagedItems->end());
assert(liveSceneItems.moveItem(visibleItem->itemNumber, startingEgg->data.x,
startingEgg->data.y, 16));
const auto liveAfter = cachedRenderer->render(options, &liveSceneItems);
assert(liveAfter && !samePixels(liveAfter->pixels, liveBefore->pixels));
assert(!cachedRenderer->decodedFrames.empty());
const auto actor = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
bool canLeaveSpawn = false;
for (const auto [deltaX, deltaY] : {std::pair{32, 0}, {0, 32}, {-32, 0}, {0, -32}}) {
canLeaveSpawn |= remorse::canMoveCollisionBody(actor,
{spawn.x + deltaX, spawn.y + deltaY, spawn.z}, obstacles);
}
assert(canLeaveSpawn);
return 0;
}