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

@ -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) {