Refactor usecode task management and enhance teleportation logic
- Improved the queueUsecodeTask function to streamline process termination and context management. - Added robust error handling for event context creation and memory writing. - Enhanced the loadSceneAsync function to better handle avatar teleportation, including a new teleporter process. - Expanded entity dispatch tests to cover movement and teleporter processes, ensuring correct behavior under various conditions. - Introduced new tests for usecode runtime memory allocation and context creation, validating edge cases and error handling. - Updated flex archive tests to ensure proper loading and unloading of usecode slot chunk caches.
This commit is contained in:
parent
8c23bb02c9
commit
0771c86043
12 changed files with 1091 additions and 253 deletions
|
|
@ -51,6 +51,11 @@ struct ControllerProcessEntry {
|
|||
u8 extra[0x0e];
|
||||
} CR_PACKED;
|
||||
|
||||
struct TeleporterProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x04];
|
||||
} CR_PACKED;
|
||||
|
||||
struct AnimPrimitiveProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x29];
|
||||
|
|
@ -84,6 +89,7 @@ static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry
|
|||
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(TeleporterProcessEntry) == 0x36, "TeleporterProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(EntityVmContextProcessEntry) == 0x124, "EntityVmContext process size must match allocation evidence");
|
||||
static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy");
|
||||
|
|
@ -119,6 +125,8 @@ public:
|
|||
KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
TeleporterProcessEntry* createTeleporterProcess(u8 activeGroup, u16 mapNumber, u16 teleportId,
|
||||
u16 (&groupCounts)[32]);
|
||||
AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber,
|
||||
u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]);
|
||||
EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
|
|
@ -174,6 +182,7 @@ private:
|
|||
std::vector<std::unique_ptr<StandProcessEntry>> ownedStandProcesses_;
|
||||
std::vector<std::unique_ptr<GravityProcessEntry>> ownedGravityProcesses_;
|
||||
std::vector<std::unique_ptr<AnimPrimitiveProcessEntry>> ownedAnimPrimitiveProcesses_;
|
||||
std::vector<std::unique_ptr<TeleporterProcessEntry>> ownedTeleporterProcesses_;
|
||||
std::vector<std::unique_ptr<EntityVmContextProcessEntry>> ownedUsecodeProcesses_;
|
||||
std::unique_ptr<SystemTimerProcessEntry> systemTimerProcess_;
|
||||
std::unique_ptr<KeyboardProcessEntry> keyboardProcess_;
|
||||
|
|
@ -237,6 +246,15 @@ public:
|
|||
static void increment(SystemTimerProcessEntry& entry);
|
||||
};
|
||||
|
||||
class TeleporterProcess {
|
||||
public:
|
||||
static constexpr u16 vtableOffset = 0x0f3a;
|
||||
static constexpr u16 mapNumberOffset = 0x32;
|
||||
static constexpr u16 teleportIdOffset = 0x34;
|
||||
static bool run(const TeleporterProcessEntry& process, LiveFixedMapItems& items,
|
||||
u16 currentMapNumber, const std::vector<ShapeTypeInfo>& shapes);
|
||||
};
|
||||
|
||||
class KeyboardProcess {
|
||||
public:
|
||||
static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
#include "remorse/flex_archive.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
|
@ -27,20 +29,69 @@ struct UsecodeEventBody {
|
|||
std::vector<u8> bytes;
|
||||
};
|
||||
|
||||
struct UsecodeLoadedChunkProcessLayout {
|
||||
u16 vtableOffset = 0;
|
||||
FarPtr16 previous{0, 0};
|
||||
FarPtr16 next{0, 0};
|
||||
FarPtr16 chunkBuffer{0, 0};
|
||||
FarPtr16 savedSource{0, 0};
|
||||
u16 slotIndex = 0;
|
||||
u16 chunkIndex = 0;
|
||||
};
|
||||
|
||||
static_assert(sizeof(UsecodeLoadedChunkProcessLayout) == 0x16);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, previous) == 0x02);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, next) == 0x06);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkBuffer) == 0x0a);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, savedSource) == 0x0e);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, slotIndex) == 0x12);
|
||||
static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkIndex) == 0x14);
|
||||
|
||||
struct UsecodeLoadedChunkProcess {
|
||||
FarPtr16 processAddress{0, 0};
|
||||
UsecodeLoadedChunkProcessLayout layout;
|
||||
UsecodeEventBody body;
|
||||
};
|
||||
|
||||
class UsecodeRuntimeMemory {
|
||||
public:
|
||||
std::optional<FarPtr16> allocate(std::size_t byteCount, u8 initialValue = 0);
|
||||
bool release(FarPtr16 address) noexcept;
|
||||
bool contains(FarPtr16 address, std::size_t byteCount) const noexcept;
|
||||
std::optional<std::vector<u8>> read(FarPtr16 address, std::size_t byteCount) const;
|
||||
bool write(FarPtr16 address, const std::vector<u8>& bytes);
|
||||
std::size_t allocationCount() const noexcept { return allocations_.size(); }
|
||||
|
||||
private:
|
||||
u32 nextSegment_ = 1;
|
||||
std::map<u16, std::vector<u8>> allocations_;
|
||||
};
|
||||
|
||||
class UsecodeSlotChunkCache {
|
||||
public:
|
||||
explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass);
|
||||
const UsecodeEventBody* ensureLoaded(u16 chunkIndex);
|
||||
bool release(u16 chunkIndex) noexcept;
|
||||
bool tryUnload(u16 chunkIndex) noexcept;
|
||||
bool tryUnload(u16 chunkIndex);
|
||||
u16 inUseCount(u16 chunkIndex) const noexcept;
|
||||
const UsecodeLoadedChunkProcess* loadedProcess(u16 chunkIndex) const noexcept;
|
||||
std::size_t loadedProcessCount() const noexcept;
|
||||
FarPtr16 loadedListHead() const noexcept { return loadedListHead_; }
|
||||
std::size_t chunkCount() const noexcept { return chunks_.size(); }
|
||||
const UsecodeSlotOwnerBuffers& ownerBuffers() const noexcept { return ownerBuffers_; }
|
||||
UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; }
|
||||
const UsecodeRuntimeMemory& runtimeMemory() const noexcept { return runtimeMemory_; }
|
||||
|
||||
private:
|
||||
UsecodeLoadedChunkProcess* findLoadedProcess(FarPtr16 processAddress) noexcept;
|
||||
bool unlinkLoadedProcess(FarPtr16 processAddress);
|
||||
|
||||
UsecodeClass usecodeClass_;
|
||||
UsecodeSlotOwnerBuffers ownerBuffers_;
|
||||
std::vector<std::optional<UsecodeEventBody>> chunks_;
|
||||
std::vector<std::optional<UsecodeLoadedChunkProcess>> chunks_;
|
||||
UsecodeRuntimeMemory runtimeMemory_;
|
||||
FarPtr16 loadedListHead_{0, 0};
|
||||
FarPtr16 loadedListTail_{0, 0};
|
||||
};
|
||||
|
||||
struct UsecodeClassBases {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
#include <vector>
|
||||
|
||||
#include "remorse/compat.h"
|
||||
#include "remorse/usecode_archive.h"
|
||||
|
||||
namespace remorse {
|
||||
|
||||
|
|
@ -15,12 +16,20 @@ constexpr std::size_t usecodeEventBytecodeOffset = 14;
|
|||
constexpr std::size_t usecodeFrameBaseOffset = 0x40;
|
||||
constexpr std::size_t usecodeInterpreterStackLimit = 199;
|
||||
constexpr std::size_t usecodeContextProcessSize = 0x124;
|
||||
constexpr std::size_t usecodeContextInterpreterOffset = 0x36;
|
||||
constexpr std::size_t usecodeContextSlotIndexOffset = 0x32;
|
||||
constexpr std::size_t usecodeContextValueAddOffset = 0x34;
|
||||
constexpr std::size_t usecodeContextStackPointerOffset = 0x102;
|
||||
constexpr std::size_t usecodeContextStackBaseOffset = 0x106;
|
||||
constexpr std::size_t usecodeContextStackLimitOffset = 0x10a;
|
||||
constexpr std::size_t usecodeContextCodeSourceOffset = 0x10c;
|
||||
constexpr std::size_t usecodeContextSelfPointerOffset = 0x110;
|
||||
constexpr std::size_t usecodeContextOwnerRowsOffset = 0x117;
|
||||
constexpr std::size_t usecodeContextOwnerSourceOffset = 0x11b;
|
||||
constexpr std::size_t usecodeContextParameterOffset = 0x11f;
|
||||
constexpr std::size_t usecodeContextModeFlagsOffset = 0x121;
|
||||
constexpr std::size_t usecodeContextActiveFlagOffset = 0x122;
|
||||
constexpr std::size_t usecodeInterpreterCallStackSize = 0x82;
|
||||
|
||||
struct UsecodeCallFrame {
|
||||
u16 offset = 0;
|
||||
|
|
@ -53,7 +62,7 @@ class UsecodeInterpreterState {
|
|||
public:
|
||||
static std::optional<UsecodeInterpreterState> initialize(
|
||||
const std::vector<u8>& itemParameter, const std::vector<u8>& contextParameter = {},
|
||||
u16 modeFlags = 0);
|
||||
u16 modeFlags = 0, bool contextParameterPresent = false);
|
||||
bool pushCodeAddress(u16 offset, u16 segment);
|
||||
bool pushWord(u16 value);
|
||||
bool pushDword(u32 value);
|
||||
|
|
@ -71,6 +80,7 @@ public:
|
|||
u16 stackLimit = usecodeInterpreterStackLimit;
|
||||
u16 temporaryWord = 0;
|
||||
std::optional<u16> contextParameterOffset;
|
||||
std::optional<u16> contextParameterStackTop;
|
||||
bool processExcluded = false;
|
||||
u16 currentProcessId = 0;
|
||||
u16 impliedProcessId = 0;
|
||||
|
|
@ -107,19 +117,57 @@ struct UsecodeContextFactoryFields {
|
|||
u16 parameterOffset = 0;
|
||||
};
|
||||
|
||||
struct UsecodeContextCreateRequest {
|
||||
FarPtr16 ownerSource{};
|
||||
FarPtr16 codeSource{};
|
||||
FarPtr16 ownerRows{};
|
||||
std::optional<std::vector<u8>> itemParameter;
|
||||
std::optional<std::vector<u8>> contextParameter;
|
||||
u16 modeFlags = 0;
|
||||
u16 slotIndex = 0;
|
||||
u16 valueAddOffset = 0;
|
||||
};
|
||||
|
||||
struct UsecodeContextInstance {
|
||||
FarPtr16 processAddress{0, 0};
|
||||
FarPtr16 callStackAddress{0, 0};
|
||||
std::array<u8, usecodeContextProcessSize> processBytes{};
|
||||
UsecodeInterpreterState interpreter;
|
||||
};
|
||||
|
||||
struct UsecodeEventContext {
|
||||
UsecodeContextInstance context;
|
||||
FarPtr16 processIdOutput{0, 0};
|
||||
std::vector<FarPtr16> ownedRegions;
|
||||
};
|
||||
|
||||
bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize,
|
||||
const UsecodeContextFactoryFields& fields);
|
||||
std::optional<UsecodeContextInstance> createUsecodeContext(UsecodeRuntimeMemory& memory,
|
||||
const UsecodeContextCreateRequest& request);
|
||||
bool destroyUsecodeContext(UsecodeRuntimeMemory& memory,
|
||||
const UsecodeContextInstance& context) noexcept;
|
||||
std::optional<UsecodeEventContext> createUsecodeEventContext(UsecodeRuntimeMemory& memory,
|
||||
const std::vector<u8>& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem,
|
||||
const std::vector<u8>& code, u8 itemArgumentSize);
|
||||
bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory,
|
||||
const UsecodeEventContext& eventContext) noexcept;
|
||||
|
||||
class UsecodeTaskRegistry {
|
||||
public:
|
||||
UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; }
|
||||
bool add(UsecodeProcessTask task);
|
||||
bool addWithContext(UsecodeProcessTask task, UsecodeEventContext context);
|
||||
UsecodeProcessTask* find(u16 processId);
|
||||
const UsecodeProcessTask* find(u16 processId) const;
|
||||
const UsecodeEventContext* context(u16 processId) const noexcept;
|
||||
bool remove(u16 processId);
|
||||
std::size_t size() const noexcept { return tasks_.size(); }
|
||||
|
||||
private:
|
||||
std::map<u16, UsecodeProcessTask> tasks_;
|
||||
std::map<u16, UsecodeEventContext> contexts_;
|
||||
UsecodeRuntimeMemory runtimeMemory_;
|
||||
};
|
||||
|
||||
} // namespace remorse
|
||||
|
|
@ -170,6 +170,47 @@ AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGr
|
|||
return result;
|
||||
}
|
||||
|
||||
TeleporterProcessEntry* ProcessKernel::createTeleporterProcess(u8 activeGroup, u16 mapNumber,
|
||||
u16 teleportId, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
processes_.reserve(processes_.size() + 30);
|
||||
allocationSizes_.reserve(allocationSizes_.size() + 30);
|
||||
processNames_.reserve(processNames_.size() + 30);
|
||||
}
|
||||
ownedTeleporterProcesses_.reserve(ownedTeleporterProcesses_.size() + 1);
|
||||
auto process = std::make_unique<TeleporterProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x00, TeleporterProcess::vtableOffset);
|
||||
writeLe16(process->base, TeleporterProcess::mapNumberOffset, mapNumber);
|
||||
writeLe16(process->base, TeleporterProcess::teleportIdOffset, teleportId);
|
||||
setLastAllocationSize(sizeof(TeleporterProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "Teleporter";
|
||||
TeleporterProcessEntry* result = process.get();
|
||||
ownedTeleporterProcesses_.push_back(std::move(process));
|
||||
return result;
|
||||
}
|
||||
|
||||
bool TeleporterProcess::run(const TeleporterProcessEntry& process, LiveFixedMapItems& items,
|
||||
u16 currentMapNumber, const std::vector<ShapeTypeInfo>& shapes)
|
||||
{
|
||||
const auto readWord = [&process](u16 offset) {
|
||||
return static_cast<u16>(process.base.bytes[offset] |
|
||||
(static_cast<u16>(process.base.bytes[offset + 1]) << 8));
|
||||
};
|
||||
const u16 targetMap = readWord(mapNumberOffset);
|
||||
if (targetMap != currentMapNumber) {
|
||||
return false;
|
||||
}
|
||||
const auto destination = findTeleportEgg(items.mapItems(), shapes,
|
||||
static_cast<u8>(readWord(teleportIdOffset)));
|
||||
return destination && items.teleportAvatar(*destination, static_cast<u8>(targetMap));
|
||||
}
|
||||
|
||||
EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup,
|
||||
u16 (&groupCounts)[32])
|
||||
{
|
||||
|
|
@ -676,6 +717,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id)
|
|||
ownedAnimPrimitiveProcesses_.erase(animation);
|
||||
return;
|
||||
}
|
||||
const auto teleporter = std::find_if(ownedTeleporterProcesses_.begin(), ownedTeleporterProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (teleporter != ownedTeleporterProcesses_.end()) {
|
||||
ownedTeleporterProcesses_.erase(teleporter);
|
||||
return;
|
||||
}
|
||||
const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (usecode != ownedUsecodeProcesses_.end()) {
|
||||
|
|
@ -721,6 +768,9 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
|
|||
const bool ownedUsecodeProcess = std::any_of(ownedUsecodeProcesses_.begin(),
|
||||
ownedUsecodeProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
const bool ownedTeleporterProcess = std::any_of(ownedTeleporterProcesses_.begin(),
|
||||
ownedTeleporterProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess &&
|
||||
!ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 ||
|
||||
readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 ||
|
||||
|
|
@ -728,7 +778,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
|
|||
throw std::logic_error("item process child cleanup is not ported");
|
||||
}
|
||||
if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess &&
|
||||
!ownedUsecodeProcess &&
|
||||
!ownedUsecodeProcess && !ownedTeleporterProcess &&
|
||||
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");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
#include "remorse/usecode_archive.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
|
||||
namespace remorse {
|
||||
|
|
@ -16,6 +18,34 @@ u32 readDword(const std::vector<u8>& bytes, std::size_t offset)
|
|||
(static_cast<u32>(bytes[offset + 2]) << 16) | (static_cast<u32>(bytes[offset + 3]) << 24);
|
||||
}
|
||||
|
||||
void writeWord(std::vector<u8>& bytes, std::size_t offset, u16 value)
|
||||
{
|
||||
bytes[offset] = static_cast<u8>(value);
|
||||
bytes[offset + 1] = static_cast<u8>(value >> 8);
|
||||
}
|
||||
|
||||
void writeDword(std::vector<u8>& bytes, std::size_t offset, u32 value)
|
||||
{
|
||||
writeWord(bytes, offset, static_cast<u16>(value));
|
||||
writeWord(bytes, offset + 2, static_cast<u16>(value >> 16));
|
||||
}
|
||||
|
||||
bool isNull(FarPtr16 address) noexcept
|
||||
{
|
||||
return address.offset == 0 && address.segment == 0;
|
||||
}
|
||||
|
||||
bool sameAddress(FarPtr16 left, FarPtr16 right) noexcept
|
||||
{
|
||||
return left.offset == right.offset && left.segment == right.segment;
|
||||
}
|
||||
|
||||
std::vector<u8> serialize(const UsecodeLoadedChunkProcessLayout& layout)
|
||||
{
|
||||
const auto* first = reinterpret_cast<const u8*>(&layout);
|
||||
return std::vector<u8>(first, first + sizeof(layout));
|
||||
}
|
||||
|
||||
std::optional<UsecodeEventBody> readEventBodyFromDescriptors(const UsecodeClass& usecodeClass,
|
||||
const std::vector<u8>& descriptors, std::size_t descriptorOffset, u32 eventId)
|
||||
{
|
||||
|
|
@ -41,6 +71,54 @@ std::optional<UsecodeEventBody> readEventBodyFromDescriptors(const UsecodeClass&
|
|||
|
||||
} // namespace
|
||||
|
||||
std::optional<FarPtr16> UsecodeRuntimeMemory::allocate(std::size_t byteCount, u8 initialValue)
|
||||
{
|
||||
constexpr std::size_t maxSegmentBytes = static_cast<std::size_t>(std::numeric_limits<u16>::max()) + 1;
|
||||
if (byteCount == 0 || byteCount > maxSegmentBytes || nextSegment_ > std::numeric_limits<u16>::max()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto segment = static_cast<u16>(nextSegment_++);
|
||||
allocations_.emplace(segment, std::vector<u8>(byteCount, initialValue));
|
||||
return FarPtr16{0, segment};
|
||||
}
|
||||
|
||||
bool UsecodeRuntimeMemory::release(FarPtr16 address) noexcept
|
||||
{
|
||||
return address.offset == 0 && address.segment != 0 && allocations_.erase(address.segment) != 0;
|
||||
}
|
||||
|
||||
bool UsecodeRuntimeMemory::contains(FarPtr16 address, std::size_t byteCount) const noexcept
|
||||
{
|
||||
const auto allocation = allocations_.find(address.segment);
|
||||
return address.segment != 0 && allocation != allocations_.end() &&
|
||||
address.offset <= allocation->second.size() &&
|
||||
byteCount <= allocation->second.size() - address.offset;
|
||||
}
|
||||
|
||||
std::optional<std::vector<u8>> UsecodeRuntimeMemory::read(FarPtr16 address, std::size_t byteCount) const
|
||||
{
|
||||
const auto allocation = allocations_.find(address.segment);
|
||||
if (address.segment == 0 || allocation == allocations_.end() ||
|
||||
address.offset > allocation->second.size() ||
|
||||
byteCount > allocation->second.size() - address.offset) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::vector<u8>(allocation->second.begin() + address.offset,
|
||||
allocation->second.begin() + address.offset + byteCount);
|
||||
}
|
||||
|
||||
bool UsecodeRuntimeMemory::write(FarPtr16 address, const std::vector<u8>& bytes)
|
||||
{
|
||||
const auto allocation = allocations_.find(address.segment);
|
||||
if (address.segment == 0 || allocation == allocations_.end() ||
|
||||
address.offset > allocation->second.size() ||
|
||||
bytes.size() > allocation->second.size() - address.offset) {
|
||||
return false;
|
||||
}
|
||||
std::copy(bytes.begin(), bytes.end(), allocation->second.begin() + address.offset);
|
||||
return true;
|
||||
}
|
||||
|
||||
u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases)
|
||||
{
|
||||
if (item.isNpc && (item.status & 2) == 0) {
|
||||
|
|
@ -141,17 +219,73 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex)
|
|||
if (chunkIndex >= chunks_.size()) {
|
||||
return nullptr;
|
||||
}
|
||||
auto& body = chunks_[chunkIndex];
|
||||
auto& process = chunks_[chunkIndex];
|
||||
auto& state = ownerBuffers_.chunkStates[chunkIndex];
|
||||
if (!body) {
|
||||
if (state != 0xffff) {
|
||||
if (!process) {
|
||||
if (state != 0xffff || usecodeClass_.classId > std::numeric_limits<u16>::max()) {
|
||||
return nullptr;
|
||||
}
|
||||
auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex);
|
||||
if (!loadedBody) {
|
||||
return nullptr;
|
||||
}
|
||||
chunks_[chunkIndex] = std::move(*loadedBody);
|
||||
|
||||
auto processAddress = runtimeMemory_.allocate(sizeof(UsecodeLoadedChunkProcessLayout));
|
||||
if (!processAddress) {
|
||||
return nullptr;
|
||||
}
|
||||
auto chunkBuffer = runtimeMemory_.allocate(loadedBody->bytes.size(), 0xff);
|
||||
if (!chunkBuffer) {
|
||||
runtimeMemory_.release(*processAddress);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
UsecodeLoadedChunkProcess loadedProcess;
|
||||
loadedProcess.processAddress = *processAddress;
|
||||
loadedProcess.layout.vtableOffset = 0x673c;
|
||||
loadedProcess.layout.previous = loadedListHead_;
|
||||
loadedProcess.layout.chunkBuffer = *chunkBuffer;
|
||||
const std::size_t descriptorOffset = static_cast<std::size_t>(chunkIndex) * 6;
|
||||
const u32 sourceOffset = readDword(ownerBuffers_.descriptors, descriptorOffset + 2);
|
||||
loadedProcess.layout.savedSource = FarPtr16{
|
||||
static_cast<u16>(sourceOffset), static_cast<u16>(sourceOffset >> 16)};
|
||||
loadedProcess.layout.slotIndex = static_cast<u16>(usecodeClass_.classId);
|
||||
loadedProcess.layout.chunkIndex = chunkIndex;
|
||||
loadedProcess.body = std::move(*loadedBody);
|
||||
|
||||
if (!runtimeMemory_.write(loadedProcess.layout.chunkBuffer, loadedProcess.body.bytes) ||
|
||||
!runtimeMemory_.write(loadedProcess.processAddress, serialize(loadedProcess.layout))) {
|
||||
runtimeMemory_.release(loadedProcess.layout.chunkBuffer);
|
||||
runtimeMemory_.release(loadedProcess.processAddress);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
chunks_[chunkIndex] = std::move(loadedProcess);
|
||||
if (isNull(loadedListHead_)) {
|
||||
loadedListTail_ = *processAddress;
|
||||
} else {
|
||||
auto* oldHead = findLoadedProcess(loadedListHead_);
|
||||
if (oldHead == nullptr) {
|
||||
runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer);
|
||||
runtimeMemory_.release(chunks_[chunkIndex]->processAddress);
|
||||
chunks_[chunkIndex].reset();
|
||||
return nullptr;
|
||||
}
|
||||
oldHead->layout.next = *processAddress;
|
||||
if (!runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout))) {
|
||||
oldHead->layout.next = FarPtr16{0, 0};
|
||||
runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout));
|
||||
runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer);
|
||||
runtimeMemory_.release(chunks_[chunkIndex]->processAddress);
|
||||
chunks_[chunkIndex].reset();
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
loadedListHead_ = *processAddress;
|
||||
const auto& loadedProcessState = *chunks_[chunkIndex];
|
||||
writeDword(ownerBuffers_.descriptors, descriptorOffset + 2,
|
||||
static_cast<u32>(loadedProcessState.layout.chunkBuffer.offset) |
|
||||
(static_cast<u32>(loadedProcessState.layout.chunkBuffer.segment) << 16));
|
||||
state = 1;
|
||||
} else {
|
||||
if (state >= 29999) {
|
||||
|
|
@ -159,7 +293,7 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex)
|
|||
}
|
||||
++state;
|
||||
}
|
||||
return &*chunks_[chunkIndex];
|
||||
return &chunks_[chunkIndex]->body;
|
||||
}
|
||||
|
||||
bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept
|
||||
|
|
@ -172,13 +306,28 @@ bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept
|
|||
return true;
|
||||
}
|
||||
|
||||
bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) noexcept
|
||||
bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex)
|
||||
{
|
||||
if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0) {
|
||||
if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0 || !chunks_[chunkIndex]) {
|
||||
return false;
|
||||
}
|
||||
chunks_[chunkIndex].reset();
|
||||
|
||||
auto& process = *chunks_[chunkIndex];
|
||||
const std::size_t descriptorOffset = static_cast<std::size_t>(chunkIndex) * 6;
|
||||
writeDword(ownerBuffers_.descriptors, descriptorOffset + 2,
|
||||
static_cast<u32>(process.layout.savedSource.offset) |
|
||||
(static_cast<u32>(process.layout.savedSource.segment) << 16));
|
||||
ownerBuffers_.chunkStates[chunkIndex] = 0xffff;
|
||||
if (!unlinkLoadedProcess(process.processAddress)) {
|
||||
writeDword(ownerBuffers_.descriptors, descriptorOffset + 2,
|
||||
static_cast<u32>(process.layout.chunkBuffer.offset) |
|
||||
(static_cast<u32>(process.layout.chunkBuffer.segment) << 16));
|
||||
ownerBuffers_.chunkStates[chunkIndex] = 0;
|
||||
return false;
|
||||
}
|
||||
runtimeMemory_.release(process.layout.chunkBuffer);
|
||||
runtimeMemory_.release(process.processAddress);
|
||||
chunks_[chunkIndex].reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -190,6 +339,65 @@ u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept
|
|||
return ownerBuffers_.chunkStates[chunkIndex];
|
||||
}
|
||||
|
||||
const UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::loadedProcess(u16 chunkIndex) const noexcept
|
||||
{
|
||||
if (chunkIndex >= chunks_.size() || !chunks_[chunkIndex]) {
|
||||
return nullptr;
|
||||
}
|
||||
return &*chunks_[chunkIndex];
|
||||
}
|
||||
|
||||
std::size_t UsecodeSlotChunkCache::loadedProcessCount() const noexcept
|
||||
{
|
||||
std::size_t count = 0;
|
||||
for (const auto& process : chunks_) {
|
||||
count += process.has_value() ? 1 : 0;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::findLoadedProcess(FarPtr16 processAddress) noexcept
|
||||
{
|
||||
for (auto& process : chunks_) {
|
||||
if (process && sameAddress(process->processAddress, processAddress)) {
|
||||
return &*process;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool UsecodeSlotChunkCache::unlinkLoadedProcess(FarPtr16 processAddress)
|
||||
{
|
||||
auto* process = findLoadedProcess(processAddress);
|
||||
if (process == nullptr) {
|
||||
return false;
|
||||
}
|
||||
auto* older = isNull(process->layout.previous) ? nullptr : findLoadedProcess(process->layout.previous);
|
||||
auto* newer = isNull(process->layout.next) ? nullptr : findLoadedProcess(process->layout.next);
|
||||
if ((!isNull(process->layout.previous) && older == nullptr) ||
|
||||
(!isNull(process->layout.next) && newer == nullptr)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (older != nullptr) {
|
||||
older->layout.next = process->layout.next;
|
||||
if (!runtimeMemory_.write(older->processAddress, serialize(older->layout))) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
loadedListTail_ = process->layout.next;
|
||||
}
|
||||
if (newer != nullptr) {
|
||||
newer->layout.previous = process->layout.previous;
|
||||
if (!runtimeMemory_.write(newer->processAddress, serialize(newer->layout))) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
loadedListHead_ = process->layout.previous;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<EligibleUsecodeEvent> selectEligibleUsecodeEvent(const FlexArchive& archive,
|
||||
const std::vector<u8>& ownerRows, const UsecodeItemIdentity& item,
|
||||
const UsecodeClassBases& bases, u32 eventMask, u16 eventId)
|
||||
|
|
|
|||
|
|
@ -1,14 +1,30 @@
|
|||
#include "remorse/usecode_vm.h"
|
||||
#include "remorse/usecode_archive.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace remorse {
|
||||
namespace {
|
||||
|
||||
void writeWord(u8* bytes, std::size_t offset, u16 value)
|
||||
{
|
||||
bytes[offset] = static_cast<u8>(value);
|
||||
bytes[offset + 1] = static_cast<u8>(value >> 8);
|
||||
}
|
||||
|
||||
void writeFarPointer(u8* bytes, std::size_t offset, FarPtr16 pointer)
|
||||
{
|
||||
writeWord(bytes, offset, pointer.offset);
|
||||
writeWord(bytes, offset + sizeof(u16), pointer.segment);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<UsecodeInterpreterState> UsecodeInterpreterState::initialize(
|
||||
const std::vector<u8>& itemParameter, const std::vector<u8>& contextParameter,
|
||||
u16 modeFlags)
|
||||
u16 modeFlags, bool contextParameterPresent)
|
||||
{
|
||||
const bool saveStackPointer = !contextParameter.empty() && modeFlags != 0;
|
||||
const bool saveStackPointer = (!contextParameter.empty() || contextParameterPresent) && modeFlags != 0;
|
||||
const std::size_t savedPointerBytes = saveStackPointer ? sizeof(FarPtr16) : 0;
|
||||
if (itemParameter.size() > usecodeInterpreterStackLimit ||
|
||||
contextParameter.size() > usecodeInterpreterStackLimit - itemParameter.size() ||
|
||||
|
|
@ -22,10 +38,12 @@ std::optional<UsecodeInterpreterState> UsecodeInterpreterState::initialize(
|
|||
std::copy(bytes.begin(), bytes.end(), state.valueStack.begin() + state.stackTop);
|
||||
};
|
||||
pushBytes(itemParameter);
|
||||
const std::size_t stackTopBeforeContextParameter = state.stackTop;
|
||||
pushBytes(contextParameter);
|
||||
if (saveStackPointer) {
|
||||
state.stackTop -= savedPointerBytes;
|
||||
state.contextParameterOffset = static_cast<u16>(state.stackTop - sizeof(u16) * 2);
|
||||
state.contextParameterStackTop = static_cast<u16>(stackTopBeforeContextParameter);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
|
@ -484,6 +502,190 @@ bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize,
|
|||
return true;
|
||||
}
|
||||
|
||||
std::optional<UsecodeContextInstance> createUsecodeContext(UsecodeRuntimeMemory& memory,
|
||||
const UsecodeContextCreateRequest& request)
|
||||
{
|
||||
const bool hasOwnerSource = request.ownerSource.offset != 0 || request.ownerSource.segment != 0;
|
||||
if (!memory.contains(request.codeSource, 1) || !memory.contains(request.ownerRows, 9) ||
|
||||
(hasOwnerSource && !memory.contains(request.ownerSource, 1))) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::vector<u8> itemParameter;
|
||||
if (request.modeFlags != 0 && request.itemParameter) {
|
||||
if (request.itemParameter->size() != request.modeFlags) {
|
||||
return std::nullopt;
|
||||
}
|
||||
itemParameter = *request.itemParameter;
|
||||
}
|
||||
const std::vector<u8> contextParameter = request.contextParameter.value_or(std::vector<u8>{});
|
||||
auto interpreter = UsecodeInterpreterState::initialize(itemParameter, contextParameter,
|
||||
request.modeFlags, request.contextParameter.has_value());
|
||||
if (!interpreter || !interpreter->pushCodeAddress(request.slotIndex, request.valueAddOffset)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const auto processAddress = memory.allocate(usecodeContextProcessSize);
|
||||
if (!processAddress) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto callStackAddress = memory.allocate(usecodeInterpreterCallStackSize);
|
||||
if (!callStackAddress) {
|
||||
memory.release(*processAddress);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
UsecodeContextInstance context;
|
||||
context.processAddress = *processAddress;
|
||||
context.callStackAddress = *callStackAddress;
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextInterpreterOffset, *callStackAddress);
|
||||
std::copy(interpreter->valueStack.begin() + interpreter->stackTop, interpreter->valueStack.end(),
|
||||
context.processBytes.begin() + usecodeContextInterpreterOffset + interpreter->stackTop);
|
||||
|
||||
const auto stackTopOffset = static_cast<u32>(processAddress->offset) +
|
||||
usecodeContextInterpreterOffset + static_cast<u32>(interpreter->stackTop);
|
||||
const auto stackBaseOffset = static_cast<u32>(processAddress->offset) + usecodeContextStackPointerOffset;
|
||||
if (stackTopOffset > 0xffff || stackBaseOffset > 0xffff) {
|
||||
memory.release(*callStackAddress);
|
||||
memory.release(*processAddress);
|
||||
return std::nullopt;
|
||||
}
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextStackPointerOffset,
|
||||
FarPtr16{static_cast<u16>(stackTopOffset), processAddress->segment});
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextStackBaseOffset,
|
||||
FarPtr16{static_cast<u16>(stackBaseOffset), processAddress->segment});
|
||||
writeWord(context.processBytes.data(), usecodeContextStackLimitOffset, interpreter->stackLimit);
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextCodeSourceOffset, request.codeSource);
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextSelfPointerOffset, *processAddress);
|
||||
writeFarPointer(context.processBytes.data(), usecodeContextOwnerRowsOffset, request.ownerRows);
|
||||
|
||||
const UsecodeContextFactoryFields fields{request.ownerSource, request.modeFlags,
|
||||
request.slotIndex, request.valueAddOffset, interpreter->contextParameterOffset.value_or(0)};
|
||||
if (!writeUsecodeContextFactoryFields(context.processBytes.data(), context.processBytes.size(), fields)) {
|
||||
memory.release(*callStackAddress);
|
||||
memory.release(*processAddress);
|
||||
return std::nullopt;
|
||||
}
|
||||
if (interpreter->contextParameterStackTop) {
|
||||
const std::size_t savedPointerOffset = usecodeContextInterpreterOffset + interpreter->stackTop;
|
||||
const u32 savedStackOffset = static_cast<u32>(processAddress->offset) +
|
||||
usecodeContextInterpreterOffset + *interpreter->contextParameterStackTop;
|
||||
if (savedPointerOffset > context.processBytes.size() - sizeof(FarPtr16) || savedStackOffset > 0xffff) {
|
||||
memory.release(*callStackAddress);
|
||||
memory.release(*processAddress);
|
||||
return std::nullopt;
|
||||
}
|
||||
writeFarPointer(context.processBytes.data(), savedPointerOffset,
|
||||
FarPtr16{static_cast<u16>(savedStackOffset), processAddress->segment});
|
||||
}
|
||||
|
||||
std::vector<u8> callStackBytes(usecodeInterpreterCallStackSize, 0);
|
||||
for (u16 index = 0; index < interpreter->callFrameCount; ++index) {
|
||||
const std::size_t frameOffset = static_cast<std::size_t>(index) * 2 * sizeof(u16);
|
||||
writeWord(callStackBytes.data(), frameOffset, interpreter->callFrames[index].offset);
|
||||
writeWord(callStackBytes.data(), frameOffset + sizeof(u16), interpreter->callFrames[index].segment);
|
||||
}
|
||||
writeWord(callStackBytes.data(), 0x80, interpreter->callFrameCount);
|
||||
|
||||
const std::vector<u8> processBytes(context.processBytes.begin(), context.processBytes.end());
|
||||
if (!memory.write(*processAddress, processBytes) || !memory.write(*callStackAddress, callStackBytes)) {
|
||||
memory.release(*callStackAddress);
|
||||
memory.release(*processAddress);
|
||||
return std::nullopt;
|
||||
}
|
||||
context.interpreter = std::move(*interpreter);
|
||||
return context;
|
||||
}
|
||||
|
||||
bool destroyUsecodeContext(UsecodeRuntimeMemory& memory, const UsecodeContextInstance& context) noexcept
|
||||
{
|
||||
const bool callStackReleased = memory.release(context.callStackAddress);
|
||||
const bool processReleased = memory.release(context.processAddress);
|
||||
return callStackReleased && processReleased;
|
||||
}
|
||||
|
||||
std::optional<UsecodeEventContext> createUsecodeEventContext(UsecodeRuntimeMemory& memory,
|
||||
const std::vector<u8>& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem,
|
||||
const std::vector<u8>& code, u8 itemArgumentSize)
|
||||
{
|
||||
constexpr std::size_t ownerRowSize = 13;
|
||||
const std::size_t ownerRowOffset = static_cast<std::size_t>(classId) * ownerRowSize;
|
||||
if (code.size() <= usecodeEventBytecodeOffset ||
|
||||
(itemArgumentSize != 0 && itemArgumentSize != sizeof(u16)) ||
|
||||
ownerRowOffset > ownerRows.size() || ownerRows.size() - ownerRowOffset < ownerRowSize) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
UsecodeEventContext eventContext;
|
||||
const auto allocateRegion = [&memory, &eventContext](const std::vector<u8>& bytes)
|
||||
-> std::optional<FarPtr16> {
|
||||
auto region = memory.allocate(bytes.size());
|
||||
if (!region) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!memory.write(*region, bytes)) {
|
||||
memory.release(*region);
|
||||
return std::nullopt;
|
||||
}
|
||||
eventContext.ownedRegions.push_back(*region);
|
||||
return region;
|
||||
};
|
||||
|
||||
const auto codeRegion = allocateRegion(code);
|
||||
const std::vector<u8> ownerRow(ownerRows.begin() + ownerRowOffset,
|
||||
ownerRows.begin() + ownerRowOffset + ownerRowSize);
|
||||
const auto ownerRowRegion = codeRegion ? allocateRegion(ownerRow) : std::nullopt;
|
||||
const auto outputRegion = ownerRowRegion ? memory.allocate(sizeof(u16)) : std::nullopt;
|
||||
if (!codeRegion || !ownerRowRegion || !outputRegion) {
|
||||
if (outputRegion) {
|
||||
memory.release(*outputRegion);
|
||||
}
|
||||
for (const auto region : eventContext.ownedRegions) {
|
||||
memory.release(region);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
eventContext.processIdOutput = *outputRegion;
|
||||
eventContext.ownedRegions.push_back(*outputRegion);
|
||||
|
||||
std::vector<u8> contextParameter{
|
||||
static_cast<u8>(outputRegion->offset),
|
||||
static_cast<u8>(outputRegion->offset >> 8),
|
||||
static_cast<u8>(outputRegion->segment),
|
||||
static_cast<u8>(outputRegion->segment >> 8)
|
||||
};
|
||||
UsecodeContextCreateRequest request;
|
||||
request.codeSource = *codeRegion;
|
||||
request.ownerRows = FarPtr16{4, ownerRowRegion->segment};
|
||||
if (itemArgumentSize == sizeof(u16)) {
|
||||
request.itemParameter = std::vector<u8>{static_cast<u8>(sourceItem),
|
||||
static_cast<u8>(sourceItem >> 8)};
|
||||
}
|
||||
request.contextParameter = std::move(contextParameter);
|
||||
request.modeFlags = itemArgumentSize;
|
||||
request.slotIndex = classId;
|
||||
request.valueAddOffset = eventSlot;
|
||||
auto context = createUsecodeContext(memory, request);
|
||||
if (!context) {
|
||||
for (const auto region : eventContext.ownedRegions) {
|
||||
memory.release(region);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
eventContext.context = std::move(*context);
|
||||
return eventContext;
|
||||
}
|
||||
|
||||
bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory,
|
||||
const UsecodeEventContext& eventContext) noexcept
|
||||
{
|
||||
bool released = destroyUsecodeContext(memory, eventContext.context);
|
||||
for (const auto region : eventContext.ownedRegions) {
|
||||
released = memory.release(region) && released;
|
||||
}
|
||||
return released;
|
||||
}
|
||||
|
||||
UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services)
|
||||
{
|
||||
if (halted) {
|
||||
|
|
@ -502,6 +704,19 @@ bool UsecodeTaskRegistry::add(UsecodeProcessTask task)
|
|||
return tasks_.emplace(task.processId, std::move(task)).second;
|
||||
}
|
||||
|
||||
bool UsecodeTaskRegistry::addWithContext(UsecodeProcessTask task, UsecodeEventContext context)
|
||||
{
|
||||
const u16 processId = task.processId;
|
||||
if (processId < 3 || tasks_.find(processId) != tasks_.end() || contexts_.find(processId) != contexts_.end()) {
|
||||
destroyUsecodeEventContext(runtimeMemory_, context);
|
||||
return false;
|
||||
}
|
||||
task.interpreter = context.context.interpreter;
|
||||
tasks_.emplace(processId, std::move(task));
|
||||
contexts_.emplace(processId, std::move(context));
|
||||
return true;
|
||||
}
|
||||
|
||||
UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId)
|
||||
{
|
||||
const auto found = tasks_.find(processId);
|
||||
|
|
@ -514,9 +729,25 @@ const UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) const
|
|||
return found == tasks_.end() ? nullptr : &found->second;
|
||||
}
|
||||
|
||||
const UsecodeEventContext* UsecodeTaskRegistry::context(u16 processId) const noexcept
|
||||
{
|
||||
const auto found = contexts_.find(processId);
|
||||
return found == contexts_.end() ? nullptr : &found->second;
|
||||
}
|
||||
|
||||
bool UsecodeTaskRegistry::remove(u16 processId)
|
||||
{
|
||||
return tasks_.erase(processId) != 0;
|
||||
const auto task = tasks_.find(processId);
|
||||
if (task == tasks_.end()) {
|
||||
return false;
|
||||
}
|
||||
const auto context = contexts_.find(processId);
|
||||
if (context != contexts_.end()) {
|
||||
destroyUsecodeEventContext(runtimeMemory_, context->second);
|
||||
contexts_.erase(context);
|
||||
}
|
||||
tasks_.erase(task);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
@ -156,21 +156,40 @@ std::optional<remorse::u16> queueUsecodeTask(AppState& state, remorse::u16 class
|
|||
state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts);
|
||||
const remorse::u16 processId = static_cast<remorse::u16>(process->base.bytes[2] |
|
||||
(static_cast<remorse::u16>(process->base.bytes[3]) << 8));
|
||||
|
||||
const auto terminateProcess = [&state, processId]() {
|
||||
state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts);
|
||||
state.diagnosticKernel.clearTerminatedProcesses();
|
||||
};
|
||||
auto eventContext = remorse::createUsecodeEventContext(state.usecodeTasks.runtimeMemory(),
|
||||
state.usecodeOwnerRows, classId, eventSlot, sourceItem, code, itemArgumentSize);
|
||||
if (!eventContext) {
|
||||
terminateProcess();
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::vector<remorse::u8> processIdBytes{
|
||||
static_cast<remorse::u8>(processId), static_cast<remorse::u8>(processId >> 8)};
|
||||
if (!state.usecodeTasks.runtimeMemory().write(eventContext->processIdOutput, processIdBytes)) {
|
||||
remorse::destroyUsecodeEventContext(state.usecodeTasks.runtimeMemory(), *eventContext);
|
||||
terminateProcess();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot,
|
||||
sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments));
|
||||
if (!task) {
|
||||
state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts);
|
||||
state.diagnosticKernel.clearTerminatedProcesses();
|
||||
if (!task || !state.usecodeTasks.addWithContext(std::move(*task), std::move(*eventContext))) {
|
||||
terminateProcess();
|
||||
return std::nullopt;
|
||||
}
|
||||
const remorse::UsecodeContextFactoryFields factoryFields{{0, 0}, itemArgumentSize,
|
||||
classId, eventSlot, task->interpreter.contextParameterOffset.value_or(0)};
|
||||
if (!remorse::writeUsecodeContextFactoryFields(reinterpret_cast<remorse::u8*>(process),
|
||||
sizeof(*process), factoryFields) || !state.usecodeTasks.add(std::move(*task))) {
|
||||
state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts);
|
||||
state.diagnosticKernel.clearTerminatedProcesses();
|
||||
const auto* registeredContext = state.usecodeTasks.context(processId);
|
||||
if (registeredContext == nullptr) {
|
||||
state.usecodeTasks.remove(processId);
|
||||
terminateProcess();
|
||||
return std::nullopt;
|
||||
}
|
||||
std::copy(registeredContext->context.processBytes.begin() + remorse::usecodeContextSlotIndexOffset,
|
||||
registeredContext->context.processBytes.end(),
|
||||
reinterpret_cast<remorse::u8*>(process) + remorse::usecodeContextSlotIndexOffset);
|
||||
return processId;
|
||||
}
|
||||
|
||||
|
|
@ -501,12 +520,32 @@ void loadSceneAsync(HWND window, AppState& state)
|
|||
options.viewCenter = spawn;
|
||||
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));
|
||||
if (startingEgg) {
|
||||
remorse::ProcessKernel teleporterKernel;
|
||||
remorse::u16 teleporterGroupCounts[32]{};
|
||||
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
|
||||
teleporterKernel.createProcess(1, teleporterGroupCounts);
|
||||
}
|
||||
auto* teleporter = teleporterKernel.createTeleporterProcess(1,
|
||||
static_cast<remorse::u16>(state.mapIndex), 0x1e, teleporterGroupCounts);
|
||||
const remorse::u16 processId = static_cast<remorse::u16>(teleporter->base.bytes[2] |
|
||||
(static_cast<remorse::u16>(teleporter->base.bytes[3]) << 8));
|
||||
const bool teleported = remorse::TeleporterProcess::run(*teleporter, liveItems,
|
||||
static_cast<remorse::u16>(state.mapIndex), *shapeTypes);
|
||||
teleporter->base.bytes[0x18] |= 4;
|
||||
teleporterKernel.terminateProcess(processId, teleporterGroupCounts);
|
||||
if (!teleported) {
|
||||
setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
remorse::StagedFixedMapItem diagnosticStart;
|
||||
diagnosticStart.data.x = static_cast<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(diagnosticStart, static_cast<remorse::u8>(state.mapIndex));
|
||||
}
|
||||
auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex);
|
||||
if (renderer) {
|
||||
hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn));
|
||||
|
|
|
|||
|
|
@ -1050,5 +1050,101 @@ int main()
|
|||
assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0);
|
||||
assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1));
|
||||
|
||||
remorse::ProcessKernel movementKernel;
|
||||
remorse::u16 movementGroups[32]{};
|
||||
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
|
||||
movementKernel.createProcess(1, movementGroups);
|
||||
}
|
||||
assert(movementKernel.createSystemTimerProcess(1, movementGroups));
|
||||
assert(movementKernel.createKeyboardProcess(1, movementGroups));
|
||||
assert(movementKernel.createControllerProcess(1, movementGroups));
|
||||
remorse::KeyEvent movementKey{};
|
||||
movementKey.scanCode = 0x48;
|
||||
movementKey.field8 = 1;
|
||||
assert(movementKernel.queuePendingKeyEvent(movementKey));
|
||||
remorse::ControllerMovementState movementController;
|
||||
movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process,
|
||||
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
|
||||
if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) {
|
||||
assert(selector == 0x10 && filter == 0);
|
||||
static_cast<remorse::ControllerMovementState*>(context)->handleDirectionalKey(
|
||||
event.scanCode, event.modifiers, event.field8 != 0);
|
||||
}
|
||||
}, &movementController);
|
||||
const auto movementRequest = movementController.request();
|
||||
assert(movementRequest.animation == 1 && movementRequest.direction == 14);
|
||||
|
||||
remorse::AnimationClip controllerWalk{};
|
||||
controllerWalk.header = {17, 4, 0, 0};
|
||||
controllerWalk.frameCount = 17;
|
||||
controllerWalk.frames.resize(17 * 8);
|
||||
auto& controllerStep = controllerWalk.frames[7 * 17 + 1];
|
||||
controllerStep.bytes[4] = 1;
|
||||
controllerStep.bytes[5] = 2;
|
||||
remorse::LiveFixedMapItems movementItems({});
|
||||
assert(movementItems.initializeAvatar());
|
||||
remorse::StagedFixedMapItem movementSpawn{};
|
||||
movementSpawn.data.x = 512;
|
||||
movementSpawn.data.y = 512;
|
||||
assert(movementItems.teleportAvatar(movementSpawn, 1));
|
||||
std::vector<remorse::ShapeTypeInfo> movementShapes(2);
|
||||
movementShapes[1].x = movementShapes[1].y = movementShapes[1].z = 2;
|
||||
auto* controllerAnimation = movementKernel.createAnimPrimitiveProcess(1, 1,
|
||||
movementRequest.animation, movementRequest.direction, controllerWalk, movementGroups);
|
||||
assert(controllerAnimation);
|
||||
const remorse::u16 controllerAnimationId = static_cast<remorse::u16>(
|
||||
controllerAnimation->base.bytes[2] | (static_cast<remorse::u16>(controllerAnimation->base.bytes[3]) << 8));
|
||||
assert(movementKernel.startAnimPrimitiveProcess(controllerAnimationId, movementItems, controllerWalk));
|
||||
struct ControllerTickContext {
|
||||
remorse::ProcessKernel* kernel;
|
||||
remorse::LiveFixedMapItems* items;
|
||||
const remorse::AnimationClip* clip;
|
||||
const std::vector<remorse::ShapeTypeInfo>* shapes;
|
||||
remorse::FastAreaRange fastArea;
|
||||
remorse::u16 processId;
|
||||
std::optional<bool> advanced;
|
||||
} controllerTick{&movementKernel, &movementItems, &controllerWalk, &movementShapes,
|
||||
remorse::calculateFastAreaRange({512, 512, 0}), controllerAnimationId};
|
||||
movementKernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& tick = *static_cast<ControllerTickContext*>(context);
|
||||
if (&process == tick.kernel->processAt(tick.processId)) {
|
||||
tick.advanced = tick.kernel->advanceGroundedAnimPrimitive(tick.processId,
|
||||
*tick.items, *tick.clip, *tick.shapes, tick.fastArea);
|
||||
}
|
||||
}, &controllerTick);
|
||||
assert(controllerTick.advanced == true && movementKernel.itemHasProcess(1));
|
||||
assert(movementItems.findItem(1)->data.x == 510 && movementItems.findItem(1)->data.y == 510 &&
|
||||
movementItems.findNpcAnimation(1)->frame == 1);
|
||||
movementKey.field8 = 0;
|
||||
assert(movementKernel.queuePendingKeyEvent(movementKey));
|
||||
movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process,
|
||||
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
|
||||
if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) {
|
||||
assert(selector == 0x10 && filter == 0);
|
||||
static_cast<remorse::ControllerMovementState*>(context)->handleDirectionalKey(
|
||||
event.scanCode, event.modifiers, event.field8 != 0);
|
||||
}
|
||||
}, &movementController);
|
||||
assert(movementController.request().animation == 0 && movementController.request().direction == 14);
|
||||
|
||||
remorse::ProcessKernel teleporterKernel;
|
||||
remorse::u16 teleporterGroups[32]{};
|
||||
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
|
||||
teleporterKernel.createProcess(1, teleporterGroups);
|
||||
}
|
||||
auto* teleporter = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups);
|
||||
const remorse::u16 teleporterProcessId = static_cast<remorse::u16>(
|
||||
teleporter->base.bytes[2] | (static_cast<remorse::u16>(teleporter->base.bytes[3]) << 8));
|
||||
assert(teleporterKernel.processAt(teleporterProcessId) == &teleporter->base &&
|
||||
teleporterKernel.allocationSizeAt(teleporterProcessId) == 0x36 &&
|
||||
std::strcmp(teleporterKernel.processNameAt(teleporterProcessId), "Teleporter") == 0);
|
||||
assert(teleporter->base.bytes[0] == 0x3a && teleporter->base.bytes[1] == 0x0f &&
|
||||
teleporter->base.bytes[0x32] == 1 && teleporter->base.bytes[0x33] == 0 &&
|
||||
teleporter->base.bytes[0x34] == 0x1e && teleporter->base.bytes[0x35] == 0);
|
||||
teleporter->base.bytes[0x18] |= 4;
|
||||
teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups);
|
||||
assert(teleporterKernel.processAt(teleporterProcessId) == nullptr &&
|
||||
teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,26 @@ int main()
|
|||
std::equal(prefix.begin(), prefix.end(), body.begin()) &&
|
||||
body[remorse::usecodeEventBytecodeOffset] == 0x0b;
|
||||
};
|
||||
const auto readDescriptorPointer = [](const std::vector<remorse::u8>& descriptors,
|
||||
std::size_t chunkIndex) {
|
||||
const std::size_t offset = chunkIndex * 6 + 2;
|
||||
return static_cast<remorse::u32>(descriptors[offset]) |
|
||||
(static_cast<remorse::u32>(descriptors[offset + 1]) << 8) |
|
||||
(static_cast<remorse::u32>(descriptors[offset + 2]) << 16) |
|
||||
(static_cast<remorse::u32>(descriptors[offset + 3]) << 24);
|
||||
};
|
||||
|
||||
remorse::UsecodeRuntimeMemory boundedMemory;
|
||||
assert(!boundedMemory.allocate(0));
|
||||
assert(!boundedMemory.allocate(0x10001));
|
||||
const auto fullSegment = boundedMemory.allocate(0x10000, 0x5a);
|
||||
assert(fullSegment);
|
||||
const auto finalSegmentByte = boundedMemory.read({0xffff, fullSegment->segment}, 1);
|
||||
assert(finalSegmentByte && finalSegmentByte->size() == 1 && finalSegmentByte->front() == 0x5a);
|
||||
assert(!boundedMemory.read({0xffff, fullSegment->segment}, 2));
|
||||
assert(!boundedMemory.read({0, 0xffff}, 1));
|
||||
assert(boundedMemory.release(*fullSegment) && boundedMemory.allocationCount() == 0);
|
||||
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
assert(root.has_value());
|
||||
|
||||
|
|
@ -66,6 +86,36 @@ int main()
|
|||
[](remorse::u16 state) { return state == 0xffff; }));
|
||||
assert(std::equal(npcTriggerOwnerBuffers->descriptors.begin(), npcTriggerOwnerBuffers->descriptors.end(),
|
||||
npcTriggerClass->bytes.begin() + 20));
|
||||
remorse::UsecodeSlotChunkCache npcTriggerChunkCache(*npcTriggerClass);
|
||||
const auto originalNpcTriggerDescriptors = npcTriggerChunkCache.ownerBuffers().descriptors;
|
||||
std::optional<remorse::u16> npcTriggerChunkIndex;
|
||||
for (remorse::u16 chunkIndex = 0; chunkIndex < npcTriggerChunkCache.chunkCount(); ++chunkIndex) {
|
||||
if (npcTriggerChunkCache.ensureLoaded(chunkIndex)) {
|
||||
npcTriggerChunkIndex = chunkIndex;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert(npcTriggerChunkIndex);
|
||||
const auto npcTriggerSourcePointer = readDescriptorPointer(
|
||||
originalNpcTriggerDescriptors, *npcTriggerChunkIndex);
|
||||
const auto* loadedNpcTriggerProcess = npcTriggerChunkCache.loadedProcess(*npcTriggerChunkIndex);
|
||||
assert(loadedNpcTriggerProcess && loadedNpcTriggerProcess->layout.slotIndex == 0x363 &&
|
||||
loadedNpcTriggerProcess->layout.chunkIndex == *npcTriggerChunkIndex &&
|
||||
loadedNpcTriggerProcess->layout.savedSource.offset == static_cast<remorse::u16>(npcTriggerSourcePointer) &&
|
||||
loadedNpcTriggerProcess->layout.savedSource.segment == static_cast<remorse::u16>(npcTriggerSourcePointer >> 16));
|
||||
const auto loadedNpcTriggerBytes = npcTriggerChunkCache.runtimeMemory().read(
|
||||
loadedNpcTriggerProcess->layout.chunkBuffer, loadedNpcTriggerProcess->body.length);
|
||||
assert(loadedNpcTriggerBytes && *loadedNpcTriggerBytes == loadedNpcTriggerProcess->body.bytes &&
|
||||
readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) ==
|
||||
(static_cast<remorse::u32>(loadedNpcTriggerProcess->layout.chunkBuffer.offset) |
|
||||
(static_cast<remorse::u32>(loadedNpcTriggerProcess->layout.chunkBuffer.segment) << 16)));
|
||||
assert(npcTriggerChunkCache.release(*npcTriggerChunkIndex));
|
||||
assert(npcTriggerChunkCache.tryUnload(*npcTriggerChunkIndex));
|
||||
assert(npcTriggerChunkCache.loadedProcessCount() == 0 &&
|
||||
npcTriggerChunkCache.runtimeMemory().allocationCount() == 0 &&
|
||||
readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) ==
|
||||
npcTriggerSourcePointer);
|
||||
|
||||
auto inconsistentOwnerHeader = *eventClass;
|
||||
inconsistentOwnerHeader.extraSlotCount = 1;
|
||||
assert(!remorse::initializeUsecodeSlotOwnerBuffers(inconsistentOwnerHeader));
|
||||
|
|
@ -74,9 +124,24 @@ int main()
|
|||
assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]);
|
||||
remorse::UsecodeSlotChunkCache eventChunkCache(*eventClass);
|
||||
assert(eventChunkCache.chunkCount() == 32);
|
||||
const auto sourceEventPointer = readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a);
|
||||
const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a);
|
||||
assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes &&
|
||||
eventChunkCache.inUseCount(0x0a) == 1);
|
||||
const auto* loadedEventProcess = eventChunkCache.loadedProcess(0x0a);
|
||||
assert(loadedEventProcess && loadedEventProcess->layout.vtableOffset == 0x673c &&
|
||||
loadedEventProcess->layout.slotIndex == 0x361 && loadedEventProcess->layout.chunkIndex == 0x0a &&
|
||||
loadedEventProcess->layout.savedSource.offset == static_cast<remorse::u16>(sourceEventPointer) &&
|
||||
loadedEventProcess->layout.savedSource.segment == static_cast<remorse::u16>(sourceEventPointer >> 16));
|
||||
const auto loadedEventBytes = eventChunkCache.runtimeMemory().read(
|
||||
loadedEventProcess->layout.chunkBuffer, loadedEventProcess->body.length);
|
||||
assert(loadedEventBytes && *loadedEventBytes == loadedEventProcess->body.bytes &&
|
||||
eventChunkCache.loadedListHead().offset == loadedEventProcess->processAddress.offset &&
|
||||
eventChunkCache.loadedListHead().segment == loadedEventProcess->processAddress.segment &&
|
||||
eventChunkCache.loadedProcessCount() == 1 && eventChunkCache.runtimeMemory().allocationCount() == 2);
|
||||
assert(readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) ==
|
||||
(static_cast<remorse::u32>(loadedEventProcess->layout.chunkBuffer.offset) |
|
||||
(static_cast<remorse::u32>(loadedEventProcess->layout.chunkBuffer.segment) << 16)));
|
||||
const auto* reusedEventChunk = eventChunkCache.ensureLoaded(0x0a);
|
||||
assert(reusedEventChunk == loadedEventChunk && eventChunkCache.inUseCount(0x0a) == 2);
|
||||
assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 1);
|
||||
|
|
@ -85,6 +150,9 @@ int main()
|
|||
assert(!eventChunkCache.release(0x0a));
|
||||
assert(eventChunkCache.tryUnload(0x0a));
|
||||
assert(eventChunkCache.ownerBuffers().chunkStates[0x0a] == 0xffff);
|
||||
assert(eventChunkCache.loadedProcessCount() == 0 && eventChunkCache.runtimeMemory().allocationCount() == 0 &&
|
||||
eventChunkCache.loadedListHead().offset == 0 && eventChunkCache.loadedListHead().segment == 0 &&
|
||||
readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == sourceEventPointer);
|
||||
const auto* reloadedEventChunk = eventChunkCache.ensureLoaded(0x0a);
|
||||
assert(reloadedEventChunk && reloadedEventChunk->bytes == eventBody->bytes &&
|
||||
eventChunkCache.inUseCount(0x0a) == 1);
|
||||
|
|
@ -95,6 +163,49 @@ int main()
|
|||
assert(eventChunkCache.inUseCount(0x0a) == 29999);
|
||||
assert(eventChunkCache.ensureLoaded(0x0a) == nullptr && eventChunkCache.inUseCount(0x0a) == 29999);
|
||||
assert(eventChunkCache.ensureLoaded(0x20) == nullptr && eventChunkCache.inUseCount(0x20) == 0);
|
||||
|
||||
remorse::UsecodeClass syntheticOwnerClass;
|
||||
syntheticOwnerClass.classId = 0x123;
|
||||
syntheticOwnerClass.name = "SYNTHETIC";
|
||||
syntheticOwnerClass.codeBase = 0xd4;
|
||||
syntheticOwnerClass.bytes.resize(syntheticOwnerClass.codeBase + 2);
|
||||
syntheticOwnerClass.bytes[20] = 1;
|
||||
syntheticOwnerClass.bytes[22] = 1;
|
||||
syntheticOwnerClass.bytes[26] = 1;
|
||||
syntheticOwnerClass.bytes[28] = 2;
|
||||
syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase] = 0xaa;
|
||||
syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase + 1] = 0xbb;
|
||||
remorse::UsecodeSlotChunkCache syntheticChunkCache(std::move(syntheticOwnerClass));
|
||||
const auto syntheticSourceDescriptors = syntheticChunkCache.ownerBuffers().descriptors;
|
||||
const auto* firstSyntheticBody = syntheticChunkCache.ensureLoaded(0);
|
||||
const auto* secondSyntheticBody = syntheticChunkCache.ensureLoaded(1);
|
||||
assert(firstSyntheticBody && firstSyntheticBody->bytes == std::vector<remorse::u8>{0xaa} &&
|
||||
secondSyntheticBody && secondSyntheticBody->bytes == std::vector<remorse::u8>{0xbb});
|
||||
const auto* firstSyntheticProcess = syntheticChunkCache.loadedProcess(0);
|
||||
const auto* secondSyntheticProcess = syntheticChunkCache.loadedProcess(1);
|
||||
assert(firstSyntheticProcess && secondSyntheticProcess &&
|
||||
secondSyntheticProcess->layout.previous.offset == firstSyntheticProcess->processAddress.offset &&
|
||||
secondSyntheticProcess->layout.previous.segment == firstSyntheticProcess->processAddress.segment &&
|
||||
firstSyntheticProcess->layout.next.offset == secondSyntheticProcess->processAddress.offset &&
|
||||
firstSyntheticProcess->layout.next.segment == secondSyntheticProcess->processAddress.segment &&
|
||||
syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset &&
|
||||
syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment);
|
||||
const auto firstSyntheticSourcePointer = readDescriptorPointer(
|
||||
syntheticSourceDescriptors, 0);
|
||||
const auto secondSyntheticSourcePointer = readDescriptorPointer(
|
||||
syntheticSourceDescriptors, 1);
|
||||
assert(syntheticChunkCache.release(0) && syntheticChunkCache.tryUnload(0));
|
||||
assert(syntheticChunkCache.loadedProcessCount() == 1 &&
|
||||
syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset &&
|
||||
syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment &&
|
||||
syntheticChunkCache.loadedProcess(1)->layout.previous.offset == 0 &&
|
||||
syntheticChunkCache.loadedProcess(1)->layout.previous.segment == 0 &&
|
||||
readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 0) == firstSyntheticSourcePointer);
|
||||
assert(syntheticChunkCache.release(1) && syntheticChunkCache.tryUnload(1));
|
||||
assert(syntheticChunkCache.loadedProcessCount() == 0 && syntheticChunkCache.runtimeMemory().allocationCount() == 0 &&
|
||||
syntheticChunkCache.loadedListHead().offset == 0 && syntheticChunkCache.loadedListHead().segment == 0 &&
|
||||
readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 1) == secondSyntheticSourcePointer);
|
||||
|
||||
assert(!remorse::readUsecodeEventBody(*eventClass, 0x20));
|
||||
assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount));
|
||||
auto truncated = *eventClass;
|
||||
|
|
@ -132,6 +243,48 @@ int main()
|
|||
assert(stagedItems && !stagedItems->empty());
|
||||
const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e);
|
||||
assert(spawnEgg);
|
||||
remorse::LiveFixedMapItems spawnSearchWorld(*stagedItems);
|
||||
assert(spawnSearchWorld.initializeAvatar());
|
||||
remorse::ProcessKernel teleporterKernel;
|
||||
remorse::u16 teleporterGroups[32]{};
|
||||
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
|
||||
teleporterKernel.createProcess(1, teleporterGroups);
|
||||
}
|
||||
auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups);
|
||||
const remorse::u16 teleporterProcessId = static_cast<remorse::u16>(
|
||||
teleporterProcess->base.bytes[2] | (static_cast<remorse::u16>(teleporterProcess->base.bytes[3]) << 8));
|
||||
assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags));
|
||||
assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0);
|
||||
assert(remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 1, *typeFlags));
|
||||
teleporterProcess->base.bytes[0x18] |= 4;
|
||||
teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups);
|
||||
assert(teleporterKernel.processAt(teleporterProcessId) == nullptr &&
|
||||
teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3);
|
||||
assert(spawnEgg->recordIndex < fixedMap->entries.size());
|
||||
const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex];
|
||||
const auto* spawnedAvatar = spawnSearchWorld.findItem(1);
|
||||
assert(spawnEgg->data.x == startingEggRecord.x / 2 &&
|
||||
spawnEgg->data.y == startingEggRecord.y / 2 && spawnEgg->data.z == startingEggRecord.z);
|
||||
assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 &&
|
||||
spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y &&
|
||||
spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1);
|
||||
const auto spawnUseCandidates = remorse::itemGrabSearchCandidates(
|
||||
*spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags);
|
||||
assert(spawnUseCandidates);
|
||||
unsigned eligibleSpawnUses = 0;
|
||||
for (const auto& candidate : *spawnUseCandidates) {
|
||||
const auto* item = spawnSearchWorld.findItem(candidate.itemNumber);
|
||||
if (!item || item->data.shape >= typeFlags->size()) continue;
|
||||
const auto& shape = (*typeFlags)[item->data.shape];
|
||||
const remorse::UsecodeItemIdentity spawnIdentity{item->itemNumber, item->data.shape,
|
||||
item->data.flags, item->data.quality, shape.family, false};
|
||||
const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
|
||||
spawnIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1);
|
||||
if (eligible) {
|
||||
++eligibleSpawnUses;
|
||||
}
|
||||
}
|
||||
assert(eligibleSpawnUses == 0);
|
||||
unsigned eligibleMapUseItems = 0;
|
||||
unsigned keycardUseItems = 0;
|
||||
std::optional<remorse::StagedFixedMapItem> boxItem;
|
||||
|
|
@ -448,9 +601,46 @@ int main()
|
|||
0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00};
|
||||
assert(hasRetailEventEntry(boxUse->bytes, boxPrefix));
|
||||
remorse::LiveFixedMapItems boxWorld(*stagedItems);
|
||||
auto boxTask = remorse::UsecodeProcessTask::create(0x0340, 0x0081, 1,
|
||||
boxItem->itemNumber, boxUse->bytes);
|
||||
assert(boxTask);
|
||||
const auto& boxShape = (*typeFlags)[boxItem->data.shape];
|
||||
const remorse::u8 boxHeight = boxShape.z == 0 && (boxShape.flags & 1) == 0
|
||||
? 1 : static_cast<remorse::u8>(boxShape.z * 8);
|
||||
assert(static_cast<unsigned>(boxItem->data.z) + boxHeight <= 0xff);
|
||||
remorse::StagedFixedMapItem boxSearchOrigin;
|
||||
boxSearchOrigin.itemNumber = 1;
|
||||
boxSearchOrigin.data.shape = 1;
|
||||
boxSearchOrigin.data.x = boxItem->data.x;
|
||||
boxSearchOrigin.data.y = boxItem->data.y;
|
||||
boxSearchOrigin.data.z = static_cast<remorse::u8>(boxItem->data.z + boxHeight);
|
||||
const auto boxCandidates = remorse::itemGrabSearchCandidates(boxSearchOrigin,
|
||||
boxWorld.mapItems(), *typeFlags);
|
||||
assert(boxCandidates);
|
||||
const auto boxCandidate = std::find_if(boxCandidates->begin(), boxCandidates->end(),
|
||||
[boxItem](const auto& candidate) { return candidate.itemNumber == boxItem->itemNumber; });
|
||||
assert(boxCandidate != boxCandidates->end());
|
||||
const auto* selectedBoxItem = boxWorld.findItem(boxCandidate->itemNumber);
|
||||
assert(selectedBoxItem && selectedBoxItem->data.shape < typeFlags->size());
|
||||
const remorse::UsecodeItemIdentity boxIdentity{selectedBoxItem->itemNumber, selectedBoxItem->data.shape,
|
||||
selectedBoxItem->data.flags, selectedBoxItem->data.quality,
|
||||
(*typeFlags)[selectedBoxItem->data.shape].family, false};
|
||||
const auto selectedBoxEvent = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
|
||||
boxIdentity, retailBases, 0x02, 1);
|
||||
assert(selectedBoxEvent && selectedBoxEvent->classId == 0x0081 &&
|
||||
selectedBoxEvent->className == "BOX_NS" && selectedBoxEvent->body.bytes == boxUse->bytes);
|
||||
remorse::UsecodeTaskRegistry boxTasks;
|
||||
auto boxContext = remorse::createUsecodeEventContext(boxTasks.runtimeMemory(), *retailOwnerRows,
|
||||
selectedBoxEvent->classId, 1, boxItem->itemNumber, selectedBoxEvent->body.bytes, 2);
|
||||
assert(boxContext && boxContext->context.interpreter.callFrameCount == 1 &&
|
||||
boxContext->ownedRegions.size() == 3 && boxTasks.runtimeMemory().allocationCount() == 5);
|
||||
const std::vector<remorse::u8> boxProcessIdBytes{0x40, 0x03};
|
||||
assert(boxTasks.runtimeMemory().write(boxContext->processIdOutput, boxProcessIdBytes));
|
||||
auto boxTaskValue = remorse::UsecodeProcessTask::create(0x0340, selectedBoxEvent->classId, 1,
|
||||
boxItem->itemNumber, selectedBoxEvent->body.bytes, 2);
|
||||
assert(boxTaskValue && boxTasks.addWithContext(std::move(*boxTaskValue), std::move(*boxContext)));
|
||||
auto* boxTask = boxTasks.find(0x0340);
|
||||
const auto* registeredBoxContext = boxTasks.context(0x0340);
|
||||
assert(boxTask && registeredBoxContext && boxTask->sourceItem == boxItem->itemNumber &&
|
||||
boxTask->interpreter.callFrameCount == 1 && registeredBoxContext->context.processBytes[
|
||||
remorse::usecodeContextSlotIndexOffset] == 0x81);
|
||||
const auto freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c);
|
||||
const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt;
|
||||
auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1);
|
||||
|
|
@ -540,6 +730,12 @@ int main()
|
|||
[](const auto& left, const auto& right) {
|
||||
return left.red == right.red && left.green == right.green && left.blue == right.blue;
|
||||
}));
|
||||
const auto boxProcessIdOutput = boxTasks.runtimeMemory().read(registeredBoxContext->processIdOutput,
|
||||
sizeof(remorse::u16));
|
||||
assert(boxProcessIdOutput && (*boxProcessIdOutput)[0] == 0x40 &&
|
||||
(*boxProcessIdOutput)[1] == 0x03 && boxTasks.runtimeMemory().allocationCount() == 5);
|
||||
assert(boxTasks.remove(0x0340) && boxTasks.size() == 0 && boxTasks.context(0x0340) == nullptr &&
|
||||
boxTasks.runtimeMemory().allocationCount() == 0);
|
||||
assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
|
||||
rechargeItem, retailBases, 0, 9));
|
||||
std::vector<remorse::u8> ownerRows(26);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
#include "remorse/usecode_vm.h"
|
||||
#include "remorse/usecode_archive.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
|
|
@ -66,6 +67,96 @@ int main()
|
|||
assert(!remorse::writeUsecodeContextFactoryFields(processContext.data(),
|
||||
processContext.size() - 1, factoryFields));
|
||||
|
||||
remorse::UsecodeRuntimeMemory contextMemory;
|
||||
const auto contextOwnerSource = contextMemory.allocate(8, 0x11);
|
||||
const auto contextCodeBytes = contextMemory.allocate(16, 0x22);
|
||||
const auto contextOwnerRows = contextMemory.allocate(13, 0x33);
|
||||
assert(contextOwnerSource && contextCodeBytes && contextOwnerRows &&
|
||||
contextMemory.contains({1, contextOwnerSource->segment}, 1) &&
|
||||
!contextMemory.contains({8, contextOwnerSource->segment}, 1));
|
||||
remorse::UsecodeContextCreateRequest contextRequest;
|
||||
contextRequest.ownerSource = remorse::FarPtr16{1, contextOwnerSource->segment};
|
||||
contextRequest.codeSource = remorse::FarPtr16{2, contextCodeBytes->segment};
|
||||
contextRequest.ownerRows = remorse::FarPtr16{4, contextOwnerRows->segment};
|
||||
contextRequest.itemParameter = std::vector<remorse::u8>{0x34, 0x12};
|
||||
contextRequest.contextParameter = contextParameter;
|
||||
contextRequest.modeFlags = 2;
|
||||
contextRequest.slotIndex = 0x000a;
|
||||
contextRequest.valueAddOffset = 0x0020;
|
||||
const auto contextInstance = remorse::createUsecodeContext(contextMemory, contextRequest);
|
||||
assert(contextInstance && contextMemory.allocationCount() == 5 &&
|
||||
contextInstance->interpreter.callFrameCount == 1 &&
|
||||
contextInstance->interpreter.callFrames[0].offset == 0x000a &&
|
||||
contextInstance->interpreter.callFrames[0].segment == 0x0020);
|
||||
const auto contextMemoryBytes = contextMemory.read(contextInstance->processAddress,
|
||||
remorse::usecodeContextProcessSize);
|
||||
assert(contextMemoryBytes && std::equal(contextMemoryBytes->begin(), contextMemoryBytes->end(),
|
||||
contextInstance->processBytes.begin()));
|
||||
const auto contextCallStack = contextMemory.read(contextInstance->callStackAddress,
|
||||
remorse::usecodeInterpreterCallStackSize);
|
||||
assert(contextCallStack && (*contextCallStack)[0] == 0x0a && (*contextCallStack)[1] == 0 &&
|
||||
(*contextCallStack)[2] == 0x20 && (*contextCallStack)[3] == 0 &&
|
||||
(*contextCallStack)[0x80] == 1 && (*contextCallStack)[0x81] == 0);
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextInterpreterOffset] ==
|
||||
static_cast<remorse::u8>(contextInstance->callStackAddress.offset) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextInterpreterOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextInstance->callStackAddress.segment));
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset] == 2 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 1] == 0 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextCodeBytes->segment) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 3] == 0);
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset] ==
|
||||
static_cast<remorse::u8>(contextInstance->processAddress.offset) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextInstance->processAddress.segment));
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset] == 4 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 1] == 0 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextOwnerRows->segment) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 3] == 0);
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset] == 1 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextOwnerSource->segment) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextParameterOffset] == 190 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextModeFlagsOffset] == 2 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextActiveFlagOffset] == 0);
|
||||
const std::size_t savedPointerLocation = remorse::usecodeContextInterpreterOffset +
|
||||
contextInstance->interpreter.stackTop;
|
||||
assert(contextInstance->processBytes[savedPointerLocation] == 0x00 &&
|
||||
contextInstance->processBytes[savedPointerLocation + 1] == 0x01 &&
|
||||
contextInstance->processBytes[savedPointerLocation + 2] ==
|
||||
static_cast<remorse::u8>(contextInstance->processAddress.segment) &&
|
||||
contextInstance->processBytes[savedPointerLocation + 3] == 0 &&
|
||||
contextInstance->processBytes[0x100] == 0x34 && contextInstance->processBytes[0x101] == 0x12 &&
|
||||
contextInstance->processBytes[0xfc] == 0xa1 && contextInstance->processBytes[0xfd] == 0xb2 &&
|
||||
contextInstance->processBytes[0xfe] == 0xc3 && contextInstance->processBytes[0xff] == 0xd4);
|
||||
assert(contextInstance->processBytes[remorse::usecodeContextStackPointerOffset] == 0xf8 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextStackPointerOffset + 2] ==
|
||||
static_cast<remorse::u8>(contextInstance->processAddress.segment) &&
|
||||
contextInstance->processBytes[remorse::usecodeContextStackBaseOffset] == 0x02 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextStackBaseOffset + 1] == 0x01 &&
|
||||
contextInstance->processBytes[remorse::usecodeContextStackLimitOffset] == 199);
|
||||
assert(remorse::destroyUsecodeContext(contextMemory, *contextInstance) &&
|
||||
contextMemory.allocationCount() == 3);
|
||||
|
||||
remorse::UsecodeContextCreateRequest emptyContextRequest = contextRequest;
|
||||
emptyContextRequest.contextParameter = std::vector<remorse::u8>{};
|
||||
const auto emptyContextInstance = remorse::createUsecodeContext(contextMemory, emptyContextRequest);
|
||||
assert(emptyContextInstance && emptyContextInstance->interpreter.contextParameterOffset == 194 &&
|
||||
emptyContextInstance->processBytes[remorse::usecodeContextParameterOffset] == 194);
|
||||
assert(remorse::destroyUsecodeContext(contextMemory, *emptyContextInstance));
|
||||
remorse::UsecodeContextCreateRequest invalidContextRequest = contextRequest;
|
||||
invalidContextRequest.itemParameter = std::vector<remorse::u8>{0x34};
|
||||
assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) &&
|
||||
contextMemory.allocationCount() == 3);
|
||||
invalidContextRequest = contextRequest;
|
||||
invalidContextRequest.codeSource = remorse::FarPtr16{0xffff, 0xfffe};
|
||||
assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) &&
|
||||
contextMemory.allocationCount() == 3);
|
||||
assert(contextMemory.release(*contextOwnerSource) && contextMemory.release(*contextCodeBytes) &&
|
||||
contextMemory.release(*contextOwnerRows) && contextMemory.allocationCount() == 0);
|
||||
|
||||
std::vector<remorse::u8> code(remorse::usecodeEventBytecodeOffset, 0);
|
||||
code.insert(code.end(), {
|
||||
0x0a, 0x07,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue