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
|
|
@ -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));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue