Add comprehensive tests for collision detection, entity dispatch, file system, isometric controls, map rendering, and sorting
- Implemented collision tests to verify overlap and movement logic for collision bodies. - Enhanced entity dispatch entry tests to cover initialization, group ID management, and process handling. - Expanded file system tests to include crash diagnostics and ensure proper game data root detection. - Created isometric controls tests to validate movement requests and screen projection calculations. - Added map renderer tests to check fixed map loading and rendering functionality. - Introduced map sorter tests to confirm correct rendering order for various items.
This commit is contained in:
parent
8907604b84
commit
202679f857
27 changed files with 3530 additions and 81 deletions
|
|
@ -3,13 +3,16 @@ cmake_minimum_required(VERSION 3.20)
|
|||
project(remorse_rebuild LANGUAGES CXX)
|
||||
|
||||
add_library(remorse_core
|
||||
src/animation_archive.cpp
|
||||
src/combat_tactics.cpp
|
||||
src/collision.cpp
|
||||
src/entity_dispatch_entry.cpp
|
||||
src/file_system.cpp
|
||||
src/flex_archive.cpp
|
||||
src/fixed_map.cpp
|
||||
src/glob_archive.cpp
|
||||
src/map_renderer.cpp
|
||||
src/map_sorter.cpp
|
||||
src/palette.cpp
|
||||
src/runtime.cpp
|
||||
src/shape_archive.cpp
|
||||
|
|
@ -31,6 +34,13 @@ add_executable(remorse_map_preview
|
|||
|
||||
target_link_libraries(remorse_map_preview PRIVATE remorse_core)
|
||||
|
||||
if(WIN32)
|
||||
add_executable(remorse_game WIN32
|
||||
src/windowed_game_main.cpp
|
||||
)
|
||||
target_link_libraries(remorse_game PRIVATE remorse_core user32 gdi32)
|
||||
endif()
|
||||
|
||||
enable_testing()
|
||||
|
||||
add_executable(entity_dispatch_entry_tests
|
||||
|
|
@ -105,6 +115,38 @@ target_link_libraries(map_renderer_tests PRIVATE remorse_core)
|
|||
|
||||
add_test(NAME map_renderer_tests COMMAND map_renderer_tests)
|
||||
|
||||
add_executable(map_sorter_tests
|
||||
tests/map_sorter_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(map_sorter_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME map_sorter_tests COMMAND map_sorter_tests)
|
||||
|
||||
add_executable(isometric_controls_tests
|
||||
tests/isometric_controls_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(isometric_controls_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME isometric_controls_tests COMMAND isometric_controls_tests)
|
||||
|
||||
add_executable(animation_archive_tests
|
||||
tests/animation_archive_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(animation_archive_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME animation_archive_tests COMMAND animation_archive_tests)
|
||||
|
||||
add_executable(collision_tests
|
||||
tests/collision_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(collision_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME collision_tests COMMAND collision_tests)
|
||||
|
||||
add_executable(combat_tactics_tests
|
||||
tests/combat_tactics_tests.cpp
|
||||
)
|
||||
|
|
@ -117,7 +159,14 @@ if(MSVC)
|
|||
target_compile_options(remorse_core PRIVATE /W4 /permissive-)
|
||||
target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(map_renderer_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(map_sorter_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(isometric_controls_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(animation_archive_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(collision_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-)
|
||||
if(WIN32)
|
||||
target_compile_options(remorse_game PRIVATE /W4 /permissive-)
|
||||
endif()
|
||||
target_compile_options(remorse_rebuild PRIVATE /W4 /permissive-)
|
||||
target_compile_options(entity_dispatch_entry_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(file_system_tests PRIVATE /W4 /permissive-)
|
||||
|
|
@ -131,7 +180,14 @@ else()
|
|||
target_compile_options(remorse_core PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(combat_tactics_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(map_renderer_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(map_sorter_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(isometric_controls_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(animation_archive_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(collision_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic)
|
||||
if(WIN32)
|
||||
target_compile_options(remorse_game PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
target_compile_options(remorse_rebuild PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(entity_dispatch_entry_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(file_system_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
|
|
|||
|
|
@ -30,11 +30,12 @@ call "%VCVARS%" || exit /b 2
|
|||
|
||||
cd /d "%REPO_ROOT%" || exit /b 2
|
||||
|
||||
cmake -S rebuild/remorse -B rebuild/remorse/out/build || exit /b 1
|
||||
cmake --build rebuild/remorse/out/build --config "%CONFIG%" || exit /b 1
|
||||
ctest --test-dir rebuild/remorse/out/build -C "%CONFIG%" --output-on-failure || exit /b 1
|
||||
set "BUILD_DIR=rebuild/remorse/out/build-nmake"
|
||||
cmake -S rebuild/remorse -B "%BUILD_DIR%" -G "NMake Makefiles" -DCMAKE_BUILD_TYPE="%CONFIG%" || exit /b 1
|
||||
cmake --build "%BUILD_DIR%" || exit /b 1
|
||||
ctest --test-dir "%BUILD_DIR%" --output-on-failure || exit /b 1
|
||||
|
||||
set "EXE=rebuild\remorse\out\build\%CONFIG%\remorse_rebuild.exe"
|
||||
set "EXE=%BUILD_DIR%\remorse_rebuild.exe"
|
||||
if not exist "%EXE%" (
|
||||
echo Built executable was not found at "%EXE%".
|
||||
exit /b 1
|
||||
|
|
|
|||
47
rebuild/remorse/include/remorse/animation_archive.h
Normal file
47
rebuild/remorse/include/remorse/animation_archive.h
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
#include "remorse\compat.h"
|
||||
|
||||
namespace remorse {
|
||||
|
||||
struct AnimationFrameMetadata {
|
||||
std::array<u8, 8> bytes{};
|
||||
};
|
||||
|
||||
struct AnimationClip {
|
||||
std::array<u8, 4> header{};
|
||||
u8 frameCount = 0;
|
||||
u8 directionCount = 8;
|
||||
std::vector<AnimationFrameMetadata> frames;
|
||||
};
|
||||
|
||||
struct AnimationArchive {
|
||||
std::vector<u8> bytes;
|
||||
};
|
||||
|
||||
struct AnimationDisplacement {
|
||||
s32 x = 0;
|
||||
s32 y = 0;
|
||||
s32 z = 0;
|
||||
bool onGround = false;
|
||||
};
|
||||
|
||||
std::optional<AnimationArchive> loadAnimationArchive(const std::filesystem::path& path);
|
||||
std::optional<AnimationClip> loadAnimationClip(const AnimationArchive& archive, u32 shapeIndex, u8 animationIndex);
|
||||
std::optional<AnimationFrameMetadata> getAnimationFrame(
|
||||
const AnimationClip& clip,
|
||||
u8 direction,
|
||||
u8 frameIndex);
|
||||
u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept;
|
||||
bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept;
|
||||
std::optional<AnimationDisplacement> decodeAnimationDisplacement(
|
||||
const AnimationFrameMetadata& metadata,
|
||||
u8 direction,
|
||||
bool rotateDirection);
|
||||
|
||||
} // namespace remorse
|
||||
30
rebuild/remorse/include/remorse/collision.h
Normal file
30
rebuild/remorse/include/remorse/collision.h
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "remorse\fixed_map.h"
|
||||
#include "remorse\glob_archive.h"
|
||||
#include "remorse\map_renderer.h"
|
||||
#include "remorse\type_flags.h"
|
||||
|
||||
namespace remorse {
|
||||
|
||||
struct CollisionBody {
|
||||
WorldPoint location{};
|
||||
s32 extentX = 0;
|
||||
s32 extentY = 0;
|
||||
s32 extentZ = 0;
|
||||
};
|
||||
|
||||
CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false);
|
||||
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right);
|
||||
bool canMoveCollisionBody(
|
||||
const CollisionBody& body,
|
||||
WorldPoint destination,
|
||||
const std::vector<CollisionBody>& obstacles);
|
||||
std::vector<CollisionBody> collectMapCollisionBodies(
|
||||
const FixedMap& map,
|
||||
const std::vector<ShapeTypeInfo>& shapeTypes,
|
||||
const std::vector<GlobObject>& globObjects);
|
||||
|
||||
} // namespace remorse
|
||||
46
rebuild/remorse/include/remorse/detail/map_sorter.h
Normal file
46
rebuild/remorse/include/remorse/detail/map_sorter.h
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
#include "remorse/compat.h"
|
||||
|
||||
namespace remorse {
|
||||
namespace detail {
|
||||
|
||||
struct RenderSortItem {
|
||||
s32 left = 0;
|
||||
s32 top = 0;
|
||||
s32 right = 0;
|
||||
s32 bottom = 0;
|
||||
s32 x = 0;
|
||||
s32 xLeft = 0;
|
||||
s32 y = 0;
|
||||
s32 yFar = 0;
|
||||
s32 z = 0;
|
||||
s32 zTop = 0;
|
||||
s32 sxLeft = 0;
|
||||
s32 sxRight = 0;
|
||||
s32 sxTop = 0;
|
||||
s32 syTop = 0;
|
||||
s32 sxBottom = 0;
|
||||
s32 syBottom = 0;
|
||||
u16 shape = 0;
|
||||
u8 frame = 0;
|
||||
bool bigFlatSquare = false;
|
||||
bool flat = false;
|
||||
bool occludes = false;
|
||||
bool solid = false;
|
||||
bool draw = false;
|
||||
bool roof = false;
|
||||
bool translucent = false;
|
||||
bool animated = false;
|
||||
bool land = false;
|
||||
bool sprite = false;
|
||||
bool inventoryItem = false;
|
||||
};
|
||||
|
||||
std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& items);
|
||||
|
||||
} // namespace detail
|
||||
} // namespace remorse
|
||||
|
|
@ -2,6 +2,10 @@
|
|||
|
||||
#include "remorse/compat.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace remorse {
|
||||
|
||||
CR_PACK_PUSH_1
|
||||
|
|
@ -9,23 +13,139 @@ struct EntityDispatchEntryBase {
|
|||
u8 bytes[0x32];
|
||||
} CR_PACKED;
|
||||
|
||||
struct StandProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x10];
|
||||
} CR_PACKED;
|
||||
|
||||
struct SystemTimerProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x18];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyboardProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x04];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyDaemonProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x0e];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyEvent {
|
||||
u8 character;
|
||||
u8 scanCode;
|
||||
u16 modifiers;
|
||||
u16 field4;
|
||||
u16 field6;
|
||||
u8 field8;
|
||||
u8 field9;
|
||||
u16 fieldA;
|
||||
} CR_PACKED;
|
||||
|
||||
struct EntityDispatchEntryRuntimeState {
|
||||
u8 bytes[0x18];
|
||||
} CR_PACKED;
|
||||
CR_PACK_POP
|
||||
|
||||
static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence");
|
||||
static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy");
|
||||
|
||||
struct NpcBehaviorServices {
|
||||
bool (*isEntirelyOnScreen)(u16 npcNumber, void* context);
|
||||
u16 (*getActivity)(u16 npcNumber, void* context);
|
||||
bool (*isCurrentActivitySpecifiedBy)(u16 npcNumber, u16 activity, void* context);
|
||||
bool (*canSeeControlledNPC)(u16 npcNumber, void* context);
|
||||
void (*startNextBehavior)(u16 npcNumber, u16 activity, void* context);
|
||||
void* context;
|
||||
};
|
||||
|
||||
class ProcessKernel {
|
||||
public:
|
||||
EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]);
|
||||
SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
void deliverSystemTimerEvent();
|
||||
u32 systemTimerTick() const;
|
||||
void setSyncContext(bool enabled, u16 currentProcessId);
|
||||
void setMarkNewProcesses(bool enabled);
|
||||
void setLastAllocationSize(u16 size);
|
||||
u16 addProcess(EntityDispatchEntryBase& entry);
|
||||
void clearProcessSlot(u16 id);
|
||||
void terminateProcess(u16 id, u16 (&groupCounts)[32]);
|
||||
void clearTerminatedProcesses();
|
||||
void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0);
|
||||
EntityDispatchEntryBase* processAt(u16 id) const;
|
||||
u16 allocationSizeAt(u16 id) const;
|
||||
const char* processNameAt(u16 id) const;
|
||||
bool itemHasProcess(u16 itemNumber) const;
|
||||
u16 processCount() const;
|
||||
u16 terminatedProcessCount() const;
|
||||
u16 newlyCreatedCount() const;
|
||||
std::size_t capacity() const;
|
||||
|
||||
private:
|
||||
void releaseOwnedProcess(u16 id);
|
||||
std::vector<EntityDispatchEntryBase*> processes_;
|
||||
std::vector<u16> allocationSizes_;
|
||||
std::vector<const char*> processNames_;
|
||||
std::vector<std::unique_ptr<EntityDispatchEntryBase>> ownedProcesses_;
|
||||
std::vector<std::unique_ptr<StandProcessEntry>> ownedStandProcesses_;
|
||||
std::unique_ptr<SystemTimerProcessEntry> systemTimerProcess_;
|
||||
std::unique_ptr<KeyboardProcessEntry> keyboardProcess_;
|
||||
std::unique_ptr<KeyDaemonProcessEntry> keyDaemonProcess_;
|
||||
u16 systemTimerProcessId_ = 0xffff;
|
||||
std::vector<u8> itemProcessPresence_;
|
||||
u16 lastAllocationSize_ = 0;
|
||||
u16 processCount_ = 0;
|
||||
u16 terminatedProcessCount_ = 0;
|
||||
u16 newlyCreatedCount_ = 0;
|
||||
u16 currentProcessId_ = 0;
|
||||
bool syncEnabled_ = false;
|
||||
bool markNewProcesses_ = false;
|
||||
};
|
||||
|
||||
class EntityDispatchEntry {
|
||||
public:
|
||||
static constexpr u16 initBaseSegment = 0x11e0;
|
||||
static constexpr u16 initBaseOffset = 0x0000;
|
||||
|
||||
static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry);
|
||||
static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId);
|
||||
static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]);
|
||||
static void incrementGroupId(EntityDispatchEntryBase& entry);
|
||||
static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType);
|
||||
static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType);
|
||||
static void sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration);
|
||||
static void unlinkSleep(EntityDispatchEntryBase& entry);
|
||||
};
|
||||
|
||||
class StandProcess {
|
||||
public:
|
||||
static constexpr u16 runOffset = 0x0359;
|
||||
static constexpr u16 vtableOffset = 0x1f0f;
|
||||
|
||||
static void run(EntityDispatchEntryBase& entry, bool (*startBehavior)(const EntityDispatchEntryBase&, void*),
|
||||
void* context, u32 timerTick);
|
||||
static void run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick);
|
||||
};
|
||||
|
||||
class SystemTimerProcess {
|
||||
public:
|
||||
static u32 tick(const SystemTimerProcessEntry& entry);
|
||||
static void increment(SystemTimerProcessEntry& entry);
|
||||
};
|
||||
|
||||
class KeyboardProcess {
|
||||
public:
|
||||
static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
|
||||
KeyEvent& event, const KeyEvent& lastEvent);
|
||||
};
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
42
rebuild/remorse/include/remorse/isometric_controls.h
Normal file
42
rebuild/remorse/include/remorse/isometric_controls.h
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
#pragma once
|
||||
|
||||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/compat.h"
|
||||
|
||||
namespace remorse {
|
||||
|
||||
struct WorldPositionD {
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
};
|
||||
|
||||
inline bool controllerWalkRequested(u16 modifiers)
|
||||
{
|
||||
const bool shiftDown = (modifiers & 0x03) != 0;
|
||||
const bool capsLockOn = (modifiers & 0x40) != 0;
|
||||
return shiftDown == capsLockOn;
|
||||
}
|
||||
|
||||
inline std::optional<AnimationDisplacement> hostMovementStep(
|
||||
const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection)
|
||||
{
|
||||
auto step = decodeAnimationDisplacement(metadata, direction, rotateDirection);
|
||||
if (step && (metadata.bytes[5] & 1) != 0) {
|
||||
step->x = 0;
|
||||
step->y = 0;
|
||||
}
|
||||
return step;
|
||||
}
|
||||
|
||||
inline WorldPositionD worldPositionAtScreenOffset(
|
||||
s32 originX,
|
||||
s32 originY,
|
||||
double screenOffsetX,
|
||||
double screenOffsetY)
|
||||
{
|
||||
return WorldPositionD{
|
||||
originX + 2.0 * screenOffsetX + 4.0 * screenOffsetY,
|
||||
originY - 2.0 * screenOffsetX + 4.0 * screenOffsetY};
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
@ -17,6 +17,17 @@ struct WorldRect {
|
|||
s32 maxY = 0;
|
||||
};
|
||||
|
||||
struct WorldPoint {
|
||||
s32 x = 0;
|
||||
s32 y = 0;
|
||||
s32 z = 0;
|
||||
};
|
||||
|
||||
struct ScreenPoint {
|
||||
s32 x = 0;
|
||||
s32 y = 0;
|
||||
};
|
||||
|
||||
struct MapRenderOptions {
|
||||
u32 mapIndex = 1;
|
||||
u32 maxWidth = 1600;
|
||||
|
|
@ -24,6 +35,7 @@ struct MapRenderOptions {
|
|||
bool expandGlobs = true;
|
||||
bool includeRoofs = false;
|
||||
bool includeHiddenMarkers = false;
|
||||
std::optional<WorldPoint> viewCenter;
|
||||
std::optional<WorldRect> worldRect;
|
||||
};
|
||||
|
||||
|
|
@ -42,6 +54,7 @@ struct RenderedMapImage {
|
|||
};
|
||||
|
||||
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options);
|
||||
ScreenPoint projectToScreen(const WorldPoint& point);
|
||||
bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image);
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
|
|
@ -20,5 +20,6 @@ struct ExportManifestSummary {
|
|||
std::optional<ExportManifestSummary> loadExportManifestSummary(const std::filesystem::path& manifestPath);
|
||||
std::filesystem::path defaultManifestPath(const std::filesystem::path& currentPath);
|
||||
void printStartupReport(const ExportManifestSummary& manifest);
|
||||
void installCrashDiagnostics();
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
135
rebuild/remorse/src/animation_archive.cpp
Normal file
135
rebuild/remorse/src/animation_archive.cpp
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
#include "remorse/animation_archive.h"
|
||||
|
||||
#include "remorse/file_system.h"
|
||||
|
||||
#include <limits>
|
||||
|
||||
namespace remorse {
|
||||
namespace {
|
||||
|
||||
std::optional<u32> readU32Le(const std::vector<u8>& bytes, std::size_t offset)
|
||||
{
|
||||
if (offset > bytes.size() || bytes.size() - offset < 4) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<u32>(bytes[offset]) |
|
||||
(static_cast<u32>(bytes[offset + 1]) << 8) |
|
||||
(static_cast<u32>(bytes[offset + 2]) << 16) |
|
||||
(static_cast<u32>(bytes[offset + 3]) << 24);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<AnimationArchive> loadAnimationArchive(const std::filesystem::path& path)
|
||||
{
|
||||
const auto bytes = readBinaryFile(path);
|
||||
if (!bytes) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return AnimationArchive{*bytes};
|
||||
}
|
||||
|
||||
std::optional<AnimationClip> loadAnimationClip(
|
||||
const AnimationArchive& archive,
|
||||
u32 shapeIndex,
|
||||
u8 animationIndex)
|
||||
{
|
||||
if (shapeIndex > std::numeric_limits<std::size_t>::max() / 4) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto shapeTableOffset = readU32Le(archive.bytes, static_cast<std::size_t>(shapeIndex) * 4);
|
||||
if (!shapeTableOffset || *shapeTableOffset == 0 ||
|
||||
*shapeTableOffset > archive.bytes.size() || archive.bytes.size() - *shapeTableOffset < 0x400) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const std::size_t animationOffsetPosition = static_cast<std::size_t>(*shapeTableOffset) +
|
||||
static_cast<std::size_t>(animationIndex) * 4;
|
||||
const auto animationOffset = readU32Le(archive.bytes, animationOffsetPosition);
|
||||
if (!animationOffset || *animationOffset == 0 ||
|
||||
*animationOffset > archive.bytes.size() || archive.bytes.size() - *animationOffset < 4) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
AnimationClip clip;
|
||||
for (std::size_t index = 0; index < clip.header.size(); ++index) {
|
||||
clip.header[index] = archive.bytes[*animationOffset + index];
|
||||
}
|
||||
clip.frameCount = clip.header[0];
|
||||
if (clip.frameCount == 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
clip.directionCount = (clip.header[3] & 0x40) != 0 ? 16 : 8;
|
||||
const std::size_t metadataSize = static_cast<std::size_t>(clip.frameCount) * clip.directionCount * 8;
|
||||
const std::size_t metadataOffset = static_cast<std::size_t>(*animationOffset) + clip.header.size();
|
||||
if (metadataOffset > archive.bytes.size() || metadataSize > archive.bytes.size() - metadataOffset) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
clip.frames.resize(static_cast<std::size_t>(clip.frameCount) * clip.directionCount);
|
||||
for (std::size_t index = 0; index < clip.frames.size(); ++index) {
|
||||
const std::size_t sourceOffset = metadataOffset + index * 8;
|
||||
for (std::size_t byte = 0; byte < clip.frames[index].bytes.size(); ++byte) {
|
||||
clip.frames[index].bytes[byte] = archive.bytes[sourceOffset + byte];
|
||||
}
|
||||
}
|
||||
return clip;
|
||||
}
|
||||
|
||||
std::optional<AnimationFrameMetadata> getAnimationFrame(
|
||||
const AnimationClip& clip,
|
||||
u8 direction,
|
||||
u8 frameIndex)
|
||||
{
|
||||
if (direction > 15 || frameIndex >= clip.frameCount ||
|
||||
(clip.directionCount != 8 && clip.directionCount != 16)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::size_t effectiveDirection = clip.directionCount == 8 ? direction / 2 : direction;
|
||||
const std::size_t index = effectiveDirection * clip.frameCount + frameIndex;
|
||||
if (index >= clip.frames.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return clip.frames[index];
|
||||
}
|
||||
|
||||
u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept
|
||||
{
|
||||
return static_cast<u16>(metadata.bytes[0]) |
|
||||
(static_cast<u16>(metadata.bytes[1] & 0x0f) << 8);
|
||||
}
|
||||
|
||||
bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept
|
||||
{
|
||||
return (metadata.bytes[1] & 0x80) != 0;
|
||||
}
|
||||
|
||||
std::optional<AnimationDisplacement> decodeAnimationDisplacement(
|
||||
const AnimationFrameMetadata& metadata,
|
||||
u8 direction,
|
||||
bool rotateDirection)
|
||||
{
|
||||
if (direction > 15) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
static constexpr s8 directionX[16] = {
|
||||
0, 1, 1, 2, 1, 2, 1, 1, 0, -1, -1, -2, -1, -2, -1, -1};
|
||||
static constexpr s8 directionY[16] = {
|
||||
-1, -2, -1, -1, 0, 1, 1, 2, 1, 2, 1, 1, 0, -1, -1, -2};
|
||||
|
||||
const u8 effectiveDirection = static_cast<u8>((direction + (rotateDirection ? 4 : 0)) & 0x0f);
|
||||
const u16 packedStride = static_cast<u16>(metadata.bytes[4]) |
|
||||
(static_cast<u16>(metadata.bytes[5] & 1) << 8);
|
||||
const s32 signedStride = (packedStride & 0x100) != 0
|
||||
? static_cast<s32>(packedStride) - 0x200
|
||||
: static_cast<s32>(packedStride);
|
||||
|
||||
return AnimationDisplacement{
|
||||
static_cast<s32>(directionX[effectiveDirection]) * signedStride * 2,
|
||||
static_cast<s32>(directionY[effectiveDirection]) * signedStride * 2,
|
||||
static_cast<s8>(metadata.bytes[2]),
|
||||
(metadata.bytes[5] & 0x02) != 0};
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
156
rebuild/remorse/src/collision.cpp
Normal file
156
rebuild/remorse/src/collision.cpp
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
#include "remorse/collision.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
namespace remorse {
|
||||
namespace {
|
||||
|
||||
constexpr u32 solidFlag = 0x0002;
|
||||
constexpr u16 flippedFlag = 0x0020;
|
||||
constexpr s32 shapeDimensionScale = 32;
|
||||
constexpr s32 shapeHeightScale = 8;
|
||||
constexpr s32 sweepStep = 16;
|
||||
constexpr s32 globCoordMask = ~0x3ff;
|
||||
constexpr s32 globCoordShift = 2;
|
||||
constexpr s32 globCoordOffset = 2;
|
||||
|
||||
bool intervalsOverlap(std::int64_t leftMin, std::int64_t leftMax,
|
||||
std::int64_t rightMin, std::int64_t rightMax)
|
||||
{
|
||||
return leftMin < rightMax && rightMin < leftMax;
|
||||
}
|
||||
|
||||
std::int64_t overlapVolumeAt(const CollisionBody& body, WorldPoint location, const CollisionBody& obstacle)
|
||||
{
|
||||
if (body.extentX <= 0 || body.extentY <= 0 || body.extentZ <= 0 ||
|
||||
obstacle.extentX <= 0 || obstacle.extentY <= 0 || obstacle.extentZ <= 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const std::int64_t overlapX = std::min<std::int64_t>(location.x,
|
||||
obstacle.location.x) - std::max<std::int64_t>(
|
||||
static_cast<std::int64_t>(location.x) - body.extentX,
|
||||
static_cast<std::int64_t>(obstacle.location.x) - obstacle.extentX);
|
||||
const std::int64_t overlapY = std::min<std::int64_t>(location.y,
|
||||
obstacle.location.y) - std::max<std::int64_t>(
|
||||
static_cast<std::int64_t>(location.y) - body.extentY,
|
||||
static_cast<std::int64_t>(obstacle.location.y) - obstacle.extentY);
|
||||
const std::int64_t overlapZ = std::min<std::int64_t>(
|
||||
static_cast<std::int64_t>(location.z) + body.extentZ,
|
||||
static_cast<std::int64_t>(obstacle.location.z) + obstacle.extentZ) -
|
||||
std::max<std::int64_t>(location.z, obstacle.location.z);
|
||||
if (overlapX <= 0 || overlapY <= 0 || overlapZ <= 0) {
|
||||
return -1;
|
||||
}
|
||||
return overlapX * overlapY * overlapZ;
|
||||
}
|
||||
|
||||
bool overlapsAt(const CollisionBody& body, WorldPoint location, const CollisionBody& obstacle)
|
||||
{
|
||||
return overlapVolumeAt(body, location, obstacle) >= 0;
|
||||
}
|
||||
|
||||
const GlobObject* findGlob(const std::vector<GlobObject>& globObjects, u32 index)
|
||||
{
|
||||
const auto found = std::find_if(globObjects.begin(), globObjects.end(), [index](const GlobObject& object) {
|
||||
return object.index == index;
|
||||
});
|
||||
return found == globObjects.end() ? nullptr : &*found;
|
||||
}
|
||||
|
||||
void appendSolidBody(std::vector<CollisionBody>& bodies, const std::vector<ShapeTypeInfo>& shapeTypes,
|
||||
u32 shape, WorldPoint location, bool flipped)
|
||||
{
|
||||
if (shape >= shapeTypes.size()) {
|
||||
return;
|
||||
}
|
||||
const ShapeTypeInfo& info = shapeTypes[shape];
|
||||
if ((info.flags & solidFlag) == 0) {
|
||||
return;
|
||||
}
|
||||
CollisionBody body = makeCollisionBody(location, info, flipped);
|
||||
if (body.extentX > 0 && body.extentY > 0 && body.extentZ > 0) {
|
||||
bodies.push_back(body);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped)
|
||||
{
|
||||
const s32 extentX = static_cast<s32>(flipped ? shapeInfo.y : shapeInfo.x) * shapeDimensionScale;
|
||||
const s32 extentY = static_cast<s32>(flipped ? shapeInfo.x : shapeInfo.y) * shapeDimensionScale;
|
||||
return CollisionBody{
|
||||
location,
|
||||
extentX,
|
||||
extentY,
|
||||
static_cast<s32>(shapeInfo.z) * shapeHeightScale};
|
||||
}
|
||||
|
||||
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right)
|
||||
{
|
||||
return overlapsAt(left, left.location, right);
|
||||
}
|
||||
|
||||
bool canMoveCollisionBody(
|
||||
const CollisionBody& body,
|
||||
WorldPoint destination,
|
||||
const std::vector<CollisionBody>& obstacles)
|
||||
{
|
||||
const std::int64_t dx = static_cast<std::int64_t>(destination.x) - body.location.x;
|
||||
const std::int64_t dy = static_cast<std::int64_t>(destination.y) - body.location.y;
|
||||
const std::int64_t dz = static_cast<std::int64_t>(destination.z) - body.location.z;
|
||||
const std::int64_t largestDelta = std::max({std::abs(dx), std::abs(dy), std::abs(dz)});
|
||||
const std::int64_t steps = std::max<std::int64_t>(1, (largestDelta + sweepStep - 1) / sweepStep);
|
||||
|
||||
for (const CollisionBody& obstacle : obstacles) {
|
||||
const std::int64_t startingOverlap = overlapVolumeAt(body, body.location, obstacle);
|
||||
for (std::int64_t step = 1; step <= steps; ++step) {
|
||||
const WorldPoint sample{
|
||||
static_cast<s32>(body.location.x + dx * step / steps),
|
||||
static_cast<s32>(body.location.y + dy * step / steps),
|
||||
static_cast<s32>(body.location.z + dz * step / steps)};
|
||||
const std::int64_t sampleOverlap = overlapVolumeAt(body, sample, obstacle);
|
||||
if (sampleOverlap >= 0 && (startingOverlap < 0 || sampleOverlap > startingOverlap)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<CollisionBody> collectMapCollisionBodies(
|
||||
const FixedMap& map,
|
||||
const std::vector<ShapeTypeInfo>& shapeTypes,
|
||||
const std::vector<GlobObject>& globObjects)
|
||||
{
|
||||
std::vector<CollisionBody> bodies;
|
||||
for (const FixedMapEntry& item : map.entries) {
|
||||
if (item.shape >= shapeTypes.size()) {
|
||||
continue;
|
||||
}
|
||||
const ShapeTypeInfo& info = shapeTypes[item.shape];
|
||||
if (info.family == 3) {
|
||||
const GlobObject* glob = findGlob(globObjects, item.quality);
|
||||
if (!glob) {
|
||||
continue;
|
||||
}
|
||||
for (const GlobObjectEntry& child : glob->entries) {
|
||||
const WorldPoint location{
|
||||
(static_cast<s32>(item.x) & globCoordMask) +
|
||||
(static_cast<s32>(child.x) << globCoordShift) + globCoordOffset,
|
||||
(static_cast<s32>(item.y) & globCoordMask) +
|
||||
(static_cast<s32>(child.y) << globCoordShift) + globCoordOffset,
|
||||
static_cast<s32>(item.z) + child.z};
|
||||
appendSolidBody(bodies, shapeTypes, child.shape, location, false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
appendSolidBody(bodies, shapeTypes, item.shape,
|
||||
WorldPoint{item.x, item.y, item.z}, (item.flags & flippedFlag) != 0);
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
@ -1,5 +1,9 @@
|
|||
#include "remorse/entity_dispatch_entry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace remorse {
|
||||
|
||||
namespace {
|
||||
|
|
@ -12,23 +16,437 @@ void writeLe16(EntityDispatchEntryBase& entry, u16 offset, u16 value)
|
|||
entry.bytes[offset] = static_cast<u8>(value & 0xff);
|
||||
entry.bytes[offset + 1] = static_cast<u8>(value >> 8);
|
||||
}
|
||||
|
||||
u16 readLe16(const EntityDispatchEntryBase& entry, u16 offset)
|
||||
{
|
||||
return static_cast<u16>(entry.bytes[offset] | (static_cast<u16>(entry.bytes[offset + 1]) << 8));
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry)
|
||||
void clearBytes(EntityDispatchEntryBase& entry, u16 begin, u16 end)
|
||||
{
|
||||
for (u16 offset = begin; offset < end; ++offset) {
|
||||
entry.bytes[offset] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* ProcessKernel::createProcess(u8 activeGroup, 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);
|
||||
}
|
||||
ownedProcesses_.reserve(ownedProcesses_.size() + 1);
|
||||
auto entry = std::make_unique<EntityDispatchEntryBase>();
|
||||
EntityDispatchEntry::initBase(entry.get(), activeGroup, groupCounts);
|
||||
setLastAllocationSize(sizeof(EntityDispatchEntryBase));
|
||||
const u16 id = addProcess(*entry);
|
||||
if (syncEnabled_) {
|
||||
EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_);
|
||||
if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) {
|
||||
current->bytes[0x18] |= 0x04;
|
||||
}
|
||||
if (id > currentProcessId_) {
|
||||
entry->bytes[0x16] |= 0x40;
|
||||
}
|
||||
}
|
||||
EntityDispatchEntryBase* result = entry.get();
|
||||
ownedProcesses_.push_back(std::move(entry));
|
||||
return result;
|
||||
}
|
||||
|
||||
StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumber, 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);
|
||||
}
|
||||
ownedStandProcesses_.reserve(ownedStandProcesses_.size() + 1);
|
||||
auto process = std::make_unique<StandProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
writeLe16(process->base, 0x04, npcNumber);
|
||||
writeLe16(process->base, 0x06, 0x258);
|
||||
writeLe16(process->base, 0x00, StandProcess::vtableOffset);
|
||||
process->extra[0x00] |= 0x01;
|
||||
process->extra[0x01] |= 0x01;
|
||||
process->extra[0x0e] = static_cast<u8>(npcNumber);
|
||||
process->extra[0x0f] = static_cast<u8>(npcNumber >> 8);
|
||||
setLastAllocationSize(sizeof(StandProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "Stand";
|
||||
if (syncEnabled_) {
|
||||
EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_);
|
||||
if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) {
|
||||
current->bytes[0x18] |= 0x04;
|
||||
}
|
||||
if (id > currentProcessId_) {
|
||||
process->base.bytes[0x16] |= 0x40;
|
||||
}
|
||||
}
|
||||
StandProcessEntry* result = process.get();
|
||||
ownedStandProcesses_.push_back(std::move(process));
|
||||
const std::size_t itemByte = npcNumber >> 3;
|
||||
if (itemProcessPresence_.size() <= itemByte) {
|
||||
itemProcessPresence_.resize(itemByte + 1, 0);
|
||||
}
|
||||
itemProcessPresence_[itemByte] |= static_cast<u8>(1u << (npcNumber & 7));
|
||||
return result;
|
||||
}
|
||||
|
||||
SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (systemTimerProcess_ != nullptr) {
|
||||
throw std::logic_error("system timer process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<SystemTimerProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
process->extra[0] = 0x02;
|
||||
process->extra[4] = 0x3c;
|
||||
setLastAllocationSize(sizeof(SystemTimerProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "SystemTimer";
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x2403));
|
||||
systemTimerProcessId_ = id;
|
||||
systemTimerProcess_ = std::move(process);
|
||||
return systemTimerProcess_.get();
|
||||
}
|
||||
|
||||
KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (keyboardProcess_ != nullptr) {
|
||||
throw std::logic_error("keyboard process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<KeyboardProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x103));
|
||||
setLastAllocationSize(sizeof(KeyboardProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "KeyboardProcess";
|
||||
writeLe16(process->base, 0x18, static_cast<u16>(readLe16(process->base, 0x18) | 0x180));
|
||||
keyboardProcess_ = std::move(process);
|
||||
return keyboardProcess_.get();
|
||||
}
|
||||
|
||||
KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (keyDaemonProcess_ != nullptr) {
|
||||
throw std::logic_error("key daemon process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<KeyDaemonProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
process->extra[0] = 0x02;
|
||||
process->extra[4] = 0x2d;
|
||||
setLastAllocationSize(sizeof(KeyDaemonProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "KeyDaemon";
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x2403));
|
||||
keyDaemonProcess_ = std::move(process);
|
||||
return keyDaemonProcess_.get();
|
||||
}
|
||||
|
||||
void ProcessKernel::deliverSystemTimerEvent()
|
||||
{
|
||||
if (systemTimerProcess_ == nullptr) {
|
||||
throw std::logic_error("system timer process is not registered");
|
||||
}
|
||||
if (processAt(systemTimerProcessId_) != &systemTimerProcess_->base ||
|
||||
(readLe16(systemTimerProcess_->base, 0x16) & 0x400) == 0) {
|
||||
throw std::logic_error("system timer event registration is invalid");
|
||||
}
|
||||
SystemTimerProcess::increment(*systemTimerProcess_);
|
||||
}
|
||||
|
||||
u32 ProcessKernel::systemTimerTick() const
|
||||
{
|
||||
if (systemTimerProcess_ == nullptr) {
|
||||
throw std::logic_error("system timer process is not registered");
|
||||
}
|
||||
return SystemTimerProcess::tick(*systemTimerProcess_);
|
||||
}
|
||||
|
||||
void ProcessKernel::setSyncContext(bool enabled, u16 currentProcessId)
|
||||
{
|
||||
syncEnabled_ = enabled;
|
||||
currentProcessId_ = currentProcessId;
|
||||
}
|
||||
|
||||
void ProcessKernel::setMarkNewProcesses(bool enabled)
|
||||
{
|
||||
markNewProcesses_ = enabled;
|
||||
}
|
||||
|
||||
void ProcessKernel::setLastAllocationSize(u16 size)
|
||||
{
|
||||
lastAllocationSize_ = size;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::addProcess(EntityDispatchEntryBase& entry)
|
||||
{
|
||||
auto freeSlot = std::find(processes_.begin(), processes_.end(), nullptr);
|
||||
if (freeSlot == processes_.end()) {
|
||||
if (processes_.size() + 30 > 1023) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
const std::size_t oldCapacity = processes_.size();
|
||||
processes_.resize(oldCapacity + 30, nullptr);
|
||||
allocationSizes_.resize(oldCapacity + 30, 0);
|
||||
processNames_.resize(oldCapacity + 30, nullptr);
|
||||
freeSlot = processes_.begin() + oldCapacity;
|
||||
}
|
||||
const u16 id = static_cast<u16>(freeSlot - processes_.begin());
|
||||
*freeSlot = &entry;
|
||||
entry.bytes[0x02] = static_cast<u8>(id & 0xff);
|
||||
entry.bytes[0x03] = static_cast<u8>(id >> 8);
|
||||
allocationSizes_[id] = lastAllocationSize_;
|
||||
lastAllocationSize_ = 0;
|
||||
++processCount_;
|
||||
if (markNewProcesses_) {
|
||||
++newlyCreatedCount_;
|
||||
entry.bytes[0x19] |= 0x02;
|
||||
}
|
||||
processNames_[id] = "Default";
|
||||
return id;
|
||||
}
|
||||
|
||||
void ProcessKernel::clearProcessSlot(u16 id)
|
||||
{
|
||||
if (id >= processes_.size()) {
|
||||
throw std::out_of_range("process ID outside table");
|
||||
}
|
||||
processes_[id] = nullptr;
|
||||
allocationSizes_[id] = 0;
|
||||
processNames_[id] = nullptr;
|
||||
}
|
||||
|
||||
void ProcessKernel::releaseOwnedProcess(u16 id)
|
||||
{
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
clearProcessSlot(id);
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (stand != ownedStandProcesses_.end()) {
|
||||
ownedStandProcesses_.erase(stand);
|
||||
return;
|
||||
}
|
||||
const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(),
|
||||
[entry](const auto& process) { return process.get() == entry; });
|
||||
ownedProcesses_.erase(owned);
|
||||
}
|
||||
|
||||
void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
|
||||
{
|
||||
EntityDispatchEntryBase* entry = processAt(id);
|
||||
if (id == 0 || entry == nullptr) {
|
||||
throw std::out_of_range("process ID is not addressable");
|
||||
}
|
||||
const u16 itemNumber = readLe16(*entry, 0x04);
|
||||
if (systemTimerProcess_ != nullptr && entry == &systemTimerProcess_->base) {
|
||||
throw std::logic_error("system timer teardown is not ported");
|
||||
}
|
||||
if (keyboardProcess_ != nullptr && entry == &keyboardProcess_->base) {
|
||||
throw std::logic_error("keyboard process teardown is not ported");
|
||||
}
|
||||
if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) {
|
||||
throw std::logic_error("key daemon process teardown is not ported");
|
||||
}
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() || id < 3 ||
|
||||
readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 ||
|
||||
readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) {
|
||||
throw std::logic_error("item process child cleanup is not ported");
|
||||
}
|
||||
if (stand == ownedStandProcesses_.end() && 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");
|
||||
}
|
||||
const bool immediate = (entry->bytes[0x18] & 0x04) != 0;
|
||||
if (!immediate && (entry->bytes[0x16] & 0x08) != 0) {
|
||||
throw std::logic_error("process is already terminated");
|
||||
}
|
||||
--groupCounts[entry->bytes[0x08] & 0x1f];
|
||||
if (immediate) {
|
||||
releaseOwnedProcess(id);
|
||||
} else {
|
||||
entry->bytes[0x16] |= 0x08;
|
||||
++terminatedProcessCount_;
|
||||
}
|
||||
--processCount_;
|
||||
if (itemNumber != 0) {
|
||||
const bool stillPresent = std::any_of(processes_.begin() + 3, processes_.end(),
|
||||
[itemNumber](const EntityDispatchEntryBase* process) {
|
||||
return process != nullptr && readLe16(*process, 0x04) == itemNumber &&
|
||||
(readLe16(*process, 0x16) & 0x08) == 0;
|
||||
});
|
||||
if (!stillPresent) {
|
||||
itemProcessPresence_[itemNumber >> 3] &= static_cast<u8>(~(1u << (itemNumber & 7)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessKernel::clearTerminatedProcesses()
|
||||
{
|
||||
for (std::size_t id = 3; id < processes_.size() && terminatedProcessCount_ != 0; ++id) {
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
if (entry == nullptr || (entry->bytes[0x16] & 0x08) == 0) {
|
||||
continue;
|
||||
}
|
||||
if (entry->bytes[0x1a] != 0 || entry->bytes[0x1b] != 0) {
|
||||
throw std::logic_error("terminated process has linked state");
|
||||
}
|
||||
releaseOwnedProcess(static_cast<u16>(id));
|
||||
--terminatedProcessCount_;
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick)
|
||||
{
|
||||
if (run == nullptr) {
|
||||
throw std::invalid_argument("process run slot is required");
|
||||
}
|
||||
const bool priorSyncEnabled = syncEnabled_;
|
||||
const u16 priorProcessId = currentProcessId_;
|
||||
syncEnabled_ = true;
|
||||
try {
|
||||
for (std::size_t id = 0; id < processes_.size(); ++id) {
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) {
|
||||
if ((readLe16(*entry, 0x18) & 0x1000) != 0) {
|
||||
const u32 sleepStart = readLe16(*entry, 0x0a) | (static_cast<u32>(readLe16(*entry, 0x0c)) << 16);
|
||||
const u32 sleepLength = readLe16(*entry, 0x0e) | (static_cast<u32>(readLe16(*entry, 0x10)) << 16);
|
||||
if (sleepStart + sleepLength < timerTick) {
|
||||
if ((readLe16(*entry, 0x16) & 0x100) != 0) {
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (stand == ownedStandProcesses_.end() ||
|
||||
readLe16(*entry, 0x00) != StandProcess::vtableOffset) {
|
||||
throw std::logic_error("sleep completion dispatch is not ported");
|
||||
}
|
||||
}
|
||||
EntityDispatchEntry::unlinkSleep(*entry);
|
||||
}
|
||||
}
|
||||
if ((readLe16(*entry, 0x16) & 0x40) != 0) {
|
||||
writeLe16(*entry, 0x16, static_cast<u16>(readLe16(*entry, 0x16) & ~0x40));
|
||||
} else {
|
||||
const u8 groupId = entry->bytes[0x08] & 0x1f;
|
||||
const u16 flags = readLe16(*entry, 0x16);
|
||||
if ((readLe16(*entry, 0x18) & 0x1000) == 0 && readLe16(*entry, 0x24) == 0 &&
|
||||
readLe16(*entry, 0x26) == 0 && (flags & 1) == 0 &&
|
||||
((flags & 2) != 0 || groupId == activeGroup || groupId == 30 || groupId == 31)) {
|
||||
currentProcessId_ = static_cast<u16>(id);
|
||||
run(*entry, context);
|
||||
currentProcessId_ = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
clearTerminatedProcesses();
|
||||
}
|
||||
} catch (...) {
|
||||
syncEnabled_ = priorSyncEnabled;
|
||||
currentProcessId_ = priorProcessId;
|
||||
throw;
|
||||
}
|
||||
syncEnabled_ = priorSyncEnabled;
|
||||
currentProcessId_ = priorProcessId;
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const
|
||||
{
|
||||
return id < processes_.size() ? processes_[id] : nullptr;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::allocationSizeAt(u16 id) const
|
||||
{
|
||||
return id < allocationSizes_.size() ? allocationSizes_[id] : 0;
|
||||
}
|
||||
|
||||
const char* ProcessKernel::processNameAt(u16 id) const
|
||||
{
|
||||
return id < processNames_.size() ? processNames_[id] : nullptr;
|
||||
}
|
||||
|
||||
bool ProcessKernel::itemHasProcess(u16 itemNumber) const
|
||||
{
|
||||
const std::size_t itemByte = itemNumber >> 3;
|
||||
return itemByte < itemProcessPresence_.size() &&
|
||||
(itemProcessPresence_[itemByte] & (1u << (itemNumber & 7))) != 0;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::processCount() const
|
||||
{
|
||||
return processCount_;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::terminatedProcessCount() const
|
||||
{
|
||||
return terminatedProcessCount_;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::newlyCreatedCount() const
|
||||
{
|
||||
return newlyCreatedCount_;
|
||||
}
|
||||
|
||||
std::size_t ProcessKernel::capacity() const
|
||||
{
|
||||
return processes_.size();
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (entry == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
for (u8& byte : entry->bytes) {
|
||||
byte = 0;
|
||||
}
|
||||
writeLe16(*entry, 0x00, 0x3b06);
|
||||
writeLe16(*entry, 0x1e, 0x2d10);
|
||||
writeLe16(*entry, 0x28, 0x3afe);
|
||||
clearBytes(*entry, 0x02, 0x06);
|
||||
writeLe16(*entry, 0x06, 1);
|
||||
entry->bytes[0x08] = 0;
|
||||
clearBytes(*entry, 0x0a, 0x1e);
|
||||
writeLe16(*entry, 0x18, 1);
|
||||
clearBytes(*entry, 0x20, 0x28);
|
||||
clearBytes(*entry, 0x2a, 0x32);
|
||||
setGroupId(*entry, activeGroup, groupCounts);
|
||||
return entry;
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId)
|
||||
void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32])
|
||||
{
|
||||
entry.bytes[groupIdOffset] = static_cast<u8>((entry.bytes[groupIdOffset] & 0xe0) | (groupId & 0x1f));
|
||||
if (groupId == 0 || groupId > 31) {
|
||||
throw std::invalid_argument("process group ID must be in 1..31");
|
||||
}
|
||||
const u8 oldGroupId = entry.bytes[groupIdOffset] & 0x1f;
|
||||
if (oldGroupId == groupId) {
|
||||
return;
|
||||
}
|
||||
if (oldGroupId != 0) {
|
||||
--groupCounts[oldGroupId];
|
||||
}
|
||||
entry.bytes[groupIdOffset] = groupId;
|
||||
++groupCounts[groupId];
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry)
|
||||
|
|
@ -46,4 +464,77 @@ void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u1
|
|||
writeLe16(entry, eventTypeOffset, eventType);
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration)
|
||||
{
|
||||
writeLe16(entry, 0x18, static_cast<u16>(readLe16(entry, 0x18) | 0x1000));
|
||||
writeLe16(entry, 0x0a, static_cast<u16>(timerTick));
|
||||
writeLe16(entry, 0x0c, static_cast<u16>(timerTick >> 16));
|
||||
writeLe16(entry, 0x0e, static_cast<u16>(duration));
|
||||
writeLe16(entry, 0x10, static_cast<u16>(duration >> 16));
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::unlinkSleep(EntityDispatchEntryBase& entry)
|
||||
{
|
||||
writeLe16(entry, 0x18, static_cast<u16>(readLe16(entry, 0x18) & ~0x1000));
|
||||
clearBytes(entry, 0x0a, 0x12);
|
||||
}
|
||||
|
||||
void StandProcess::run(EntityDispatchEntryBase& entry,
|
||||
bool (*startBehavior)(const EntityDispatchEntryBase&, void*), void* context, u32 timerTick)
|
||||
{
|
||||
if (startBehavior == nullptr) {
|
||||
throw std::invalid_argument("NPC behavior boundary is required");
|
||||
}
|
||||
if (!startBehavior(entry, context)) {
|
||||
EntityDispatchEntry::sleep(entry, timerTick, 0x3c);
|
||||
}
|
||||
}
|
||||
|
||||
void StandProcess::run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick)
|
||||
{
|
||||
if (services.isEntirelyOnScreen == nullptr || services.getActivity == nullptr ||
|
||||
services.isCurrentActivitySpecifiedBy == nullptr || services.canSeeControlledNPC == nullptr ||
|
||||
services.startNextBehavior == nullptr) {
|
||||
throw std::invalid_argument("NPC behavior services are required");
|
||||
}
|
||||
const u16 npcNumber = static_cast<u16>(entry.extra[0x0e] | (static_cast<u16>(entry.extra[0x0f]) << 8));
|
||||
bool started = false;
|
||||
if (services.isEntirelyOnScreen(npcNumber, services.context) &&
|
||||
services.getActivity(npcNumber, services.context) != 0 &&
|
||||
!services.isCurrentActivitySpecifiedBy(npcNumber, 0x71, services.context) &&
|
||||
services.canSeeControlledNPC(npcNumber, services.context)) {
|
||||
services.startNextBehavior(npcNumber, 0x71, services.context);
|
||||
started = true;
|
||||
}
|
||||
run(entry.base, [](const EntityDispatchEntryBase&, void* context) {
|
||||
return *static_cast<bool*>(context);
|
||||
}, &started, timerTick);
|
||||
}
|
||||
|
||||
u32 SystemTimerProcess::tick(const SystemTimerProcessEntry& entry)
|
||||
{
|
||||
return static_cast<u32>(entry.extra[0x0e] | (static_cast<u16>(entry.extra[0x0f]) << 8)) |
|
||||
(static_cast<u32>(entry.extra[0x10] | (static_cast<u16>(entry.extra[0x11]) << 8)) << 16);
|
||||
}
|
||||
|
||||
void SystemTimerProcess::increment(SystemTimerProcessEntry& entry)
|
||||
{
|
||||
const u32 nextTick = tick(entry) + 1;
|
||||
entry.extra[0x0e] = static_cast<u8>(nextTick);
|
||||
entry.extra[0x0f] = static_cast<u8>(nextTick >> 8);
|
||||
entry.extra[0x10] = static_cast<u8>(nextTick >> 16);
|
||||
entry.extra[0x11] = static_cast<u8>(nextTick >> 24);
|
||||
}
|
||||
|
||||
bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
|
||||
KeyEvent& event, const KeyEvent& lastEvent)
|
||||
{
|
||||
if (selector != 0x10 || filter != 0 || event.character == 0 || event.field8 == 0) {
|
||||
return false;
|
||||
}
|
||||
std::memcpy(&event, &lastEvent, sizeof(event));
|
||||
process.extra[0] &= static_cast<u8>(~0x10);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
const std::filesystem::path manifestPath = argc > 1
|
||||
? std::filesystem::path(argv[1])
|
||||
: remorse::defaultManifestPath(std::filesystem::current_path());
|
||||
|
|
@ -24,9 +25,48 @@ int main(int argc, char** argv)
|
|||
}
|
||||
|
||||
remorse::printStartupReport(*manifest);
|
||||
remorse::EntityDispatchEntryBase entry{};
|
||||
remorse::EntityDispatchEntry::initBase(&entry);
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 1);
|
||||
remorse::ProcessKernel kernel;
|
||||
remorse::u16 groupCounts[32]{};
|
||||
const auto* entry = kernel.createProcess(1, groupCounts);
|
||||
std::cout << "Registered process ID: " << (entry ? entry->bytes[0x02] : 0) << '\n';
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
kernel.createProcess(1, groupCounts);
|
||||
}
|
||||
kernel.createSystemTimerProcess(1, groupCounts);
|
||||
kernel.createKeyboardProcess(1, groupCounts);
|
||||
kernel.createKeyDaemonProcess(1, groupCounts);
|
||||
kernel.terminateProcess(3, groupCounts);
|
||||
kernel.clearTerminatedProcesses();
|
||||
auto* reused = kernel.createStandProcess(1, 1, groupCounts);
|
||||
std::cout << "Reused Stand process ID: " << (reused ? reused->base.bytes[0x02] : 0) << '\n';
|
||||
remorse::NpcBehaviorServices npcServices{
|
||||
[](remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, void*) -> remorse::u16 { return 0; },
|
||||
[](remorse::u16, remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, remorse::u16, void*) {},
|
||||
nullptr
|
||||
};
|
||||
struct ScanContext {
|
||||
remorse::StandProcessEntry* standing;
|
||||
remorse::NpcBehaviorServices* npcServices;
|
||||
remorse::u32 timerTick;
|
||||
int hostCallbacks = 0;
|
||||
} scanContext{reused, &npcServices, 0};
|
||||
for (int tick = 0; tick < 100; ++tick) {
|
||||
kernel.deliverSystemTimerEvent();
|
||||
}
|
||||
scanContext.timerTick = kernel.systemTimerTick();
|
||||
kernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& scan = *static_cast<ScanContext*>(context);
|
||||
if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) {
|
||||
remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick);
|
||||
} else {
|
||||
++scan.hostCallbacks;
|
||||
}
|
||||
}, &scanContext, scanContext.timerTick);
|
||||
std::cout << "Scheduler scan host callbacks: " << scanContext.hostCallbacks << '\n';
|
||||
std::cout << "StandProcess Run sleep ticks: " << static_cast<int>(reused->base.bytes[0x0e]) << '\n';
|
||||
|
||||
const auto gameDataRoot = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
#include "remorse/runtime.h"
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
|
|
@ -7,6 +8,7 @@
|
|||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
if (!root) {
|
||||
std::cerr << "Could not locate Crusader game data root.\n";
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/glob_archive.h"
|
||||
#include "remorse/detail/map_sorter.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
#include "remorse/type_flags.h"
|
||||
|
||||
|
|
@ -14,7 +15,12 @@ namespace {
|
|||
|
||||
constexpr u16 flagInvisible = 0x0010;
|
||||
constexpr u16 flagFlipped = 0x0020;
|
||||
constexpr u32 siSolid = 0x0002;
|
||||
constexpr u32 siLand = 0x0008;
|
||||
constexpr u32 siOccl = 0x0010;
|
||||
constexpr u32 siDraw = 0x0100;
|
||||
constexpr u32 siRoof = 0x0400;
|
||||
constexpr u32 siTranslucent = 0x0800;
|
||||
constexpr s32 globCoordMask = ~0x3ff;
|
||||
constexpr s32 globCoordShift = 2;
|
||||
constexpr s32 globCoordOffset = 2;
|
||||
|
|
@ -139,12 +145,12 @@ std::vector<SceneItem> collectSceneItems(
|
|||
|
||||
s32 screenX(const SceneItem& item)
|
||||
{
|
||||
return (item.x - item.y) / 4;
|
||||
return projectToScreen(WorldPoint{item.x, item.y, item.z}).x;
|
||||
}
|
||||
|
||||
s32 screenY(const SceneItem& item)
|
||||
{
|
||||
return (item.x + item.y) / 8 - item.z;
|
||||
return projectToScreen(WorldPoint{item.x, item.y, item.z}).y;
|
||||
}
|
||||
|
||||
std::optional<DecodedShapeFrame> cachedDecode(
|
||||
|
|
@ -166,10 +172,16 @@ std::optional<DecodedShapeFrame> cachedDecode(
|
|||
return decoded;
|
||||
}
|
||||
|
||||
std::vector<RenderNode> prepareRenderNodes(const std::vector<SceneItem>& items, const ShapeArchive& shapeArchive)
|
||||
std::vector<RenderNode> prepareRenderNodes(
|
||||
const std::vector<SceneItem>& items,
|
||||
const ShapeArchive& shapeArchive,
|
||||
const std::vector<ShapeTypeInfo>& typeFlags)
|
||||
{
|
||||
std::map<std::pair<u32, u32>, DecodedShapeFrame> cache;
|
||||
std::vector<RenderNode> nodes;
|
||||
std::vector<detail::RenderSortItem> sortItems;
|
||||
nodes.reserve(items.size());
|
||||
sortItems.reserve(items.size());
|
||||
for (const SceneItem& item : items) {
|
||||
const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame);
|
||||
if (!decoded) {
|
||||
|
|
@ -188,24 +200,52 @@ std::vector<RenderNode> prepareRenderNodes(const std::vector<SceneItem>& items,
|
|||
node.top = bottomY - node.decoded.frame.yOffset;
|
||||
node.right = node.left + static_cast<s32>(node.decoded.frame.width);
|
||||
node.bottom = node.top + static_cast<s32>(node.decoded.frame.height);
|
||||
|
||||
const ShapeTypeInfo& info = typeFlags[item.shape];
|
||||
const s32 xDimension = static_cast<s32>(flipped ? info.y : info.x) * 32;
|
||||
const s32 yDimension = static_cast<s32>(flipped ? info.x : info.y) * 32;
|
||||
const s32 zDimension = static_cast<s32>(info.z) * 8;
|
||||
detail::RenderSortItem sortItem;
|
||||
sortItem.left = node.left;
|
||||
sortItem.top = node.top;
|
||||
sortItem.right = node.right;
|
||||
sortItem.bottom = node.bottom;
|
||||
sortItem.x = item.x;
|
||||
sortItem.xLeft = item.x - xDimension;
|
||||
sortItem.y = item.y;
|
||||
sortItem.yFar = item.y - yDimension;
|
||||
sortItem.z = item.z;
|
||||
sortItem.zTop = item.z + zDimension;
|
||||
sortItem.sxLeft = sortItem.xLeft / 4 - item.y / 4;
|
||||
sortItem.sxRight = item.x / 4 - sortItem.yFar / 4;
|
||||
sortItem.sxTop = sortItem.xLeft / 4 - sortItem.yFar / 4;
|
||||
sortItem.syTop = sortItem.xLeft / 8 + sortItem.yFar / 8 - sortItem.zTop;
|
||||
sortItem.sxBottom = bottomX;
|
||||
sortItem.syBottom = bottomY;
|
||||
sortItem.shape = item.shape;
|
||||
sortItem.frame = item.frame;
|
||||
sortItem.bigFlatSquare = xDimension == yDimension && xDimension >= 128;
|
||||
sortItem.flat = zDimension == 0;
|
||||
sortItem.translucent = (info.flags & siTranslucent) != 0;
|
||||
sortItem.animated = info.animationType != 0;
|
||||
sortItem.occludes = (info.flags & siOccl) != 0 && !sortItem.translucent &&
|
||||
(item.flags & flagInvisible) == 0;
|
||||
sortItem.solid = (info.flags & siSolid) != 0;
|
||||
sortItem.draw = (info.flags & siDraw) != 0;
|
||||
sortItem.roof = (info.flags & siRoof) != 0;
|
||||
sortItem.land = (info.flags & siLand) != 0;
|
||||
sortItem.inventoryItem = info.family == 13;
|
||||
nodes.push_back(node);
|
||||
sortItems.push_back(sortItem);
|
||||
}
|
||||
|
||||
std::sort(nodes.begin(), nodes.end(), [](const RenderNode& left, const RenderNode& right) {
|
||||
const s32 leftKey = left.item.x + left.item.y;
|
||||
const s32 rightKey = right.item.x + right.item.y;
|
||||
if (leftKey != rightKey) {
|
||||
return leftKey < rightKey;
|
||||
}
|
||||
if (left.item.z != right.item.z) {
|
||||
return left.item.z < right.item.z;
|
||||
}
|
||||
if (left.item.y != right.item.y) {
|
||||
return left.item.y < right.item.y;
|
||||
}
|
||||
return left.item.x < right.item.x;
|
||||
});
|
||||
return nodes;
|
||||
const std::vector<std::size_t> order = detail::resolveRenderOrder(sortItems);
|
||||
std::vector<RenderNode> orderedNodes;
|
||||
orderedNodes.reserve(order.size());
|
||||
for (const std::size_t index : order) {
|
||||
orderedNodes.push_back(std::move(nodes[index]));
|
||||
}
|
||||
return orderedNodes;
|
||||
}
|
||||
|
||||
void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette)
|
||||
|
|
@ -248,6 +288,11 @@ void writeLe32(std::ofstream& output, u32 value)
|
|||
|
||||
} // namespace
|
||||
|
||||
ScreenPoint projectToScreen(const WorldPoint& point)
|
||||
{
|
||||
return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z};
|
||||
}
|
||||
|
||||
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options)
|
||||
{
|
||||
const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
|
|
@ -270,7 +315,7 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
|
|||
}
|
||||
|
||||
const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options);
|
||||
auto nodes = prepareRenderNodes(items, *shapeArchive);
|
||||
auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags);
|
||||
if (nodes.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
|
@ -290,12 +335,22 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
|
|||
image.rawItemCount = static_cast<u32>(fixedMap->entries.size());
|
||||
image.renderItemCount = static_cast<u32>(items.size());
|
||||
image.decodedItemCount = static_cast<u32>(nodes.size());
|
||||
image.sourceLeft = nodes[0].left;
|
||||
image.sourceTop = nodes[0].top;
|
||||
image.fullWidth = maxRight - minLeft;
|
||||
image.fullHeight = maxBottom - minTop;
|
||||
image.width = std::min(options.maxWidth, static_cast<u32>(std::max<s32>(1, image.fullWidth)));
|
||||
image.height = std::min(options.maxHeight, static_cast<u32>(std::max<s32>(1, image.fullHeight)));
|
||||
image.width = options.viewCenter
|
||||
? options.maxWidth
|
||||
: std::min(options.maxWidth, static_cast<u32>(std::max<s32>(1, image.fullWidth)));
|
||||
image.height = options.viewCenter
|
||||
? options.maxHeight
|
||||
: std::min(options.maxHeight, static_cast<u32>(std::max<s32>(1, image.fullHeight)));
|
||||
if (options.viewCenter) {
|
||||
const ScreenPoint center = projectToScreen(*options.viewCenter);
|
||||
image.sourceLeft = center.x - static_cast<s32>(image.width / 2);
|
||||
image.sourceTop = center.y - static_cast<s32>(image.height / 2);
|
||||
} else {
|
||||
image.sourceLeft = nodes[0].left;
|
||||
image.sourceTop = nodes[0].top;
|
||||
}
|
||||
image.pixels.assign(
|
||||
static_cast<std::size_t>(image.width) * image.height,
|
||||
RgbColor{static_cast<u8>(10), static_cast<u8>(12), static_cast<u8>(18)});
|
||||
|
|
|
|||
316
rebuild/remorse/src/map_sorter.cpp
Normal file
316
rebuild/remorse/src/map_sorter.cpp
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
#include "remorse/detail/map_sorter.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace remorse {
|
||||
namespace detail {
|
||||
namespace {
|
||||
|
||||
struct SortNode {
|
||||
RenderSortItem item;
|
||||
std::vector<std::size_t> dependencies;
|
||||
bool occluded = false;
|
||||
s32 order = -1;
|
||||
};
|
||||
|
||||
bool listLessThan(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (left.sprite != right.sprite) {
|
||||
return left.sprite < right.sprite;
|
||||
}
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
return left.flat > right.flat;
|
||||
}
|
||||
|
||||
bool rectIntersects(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
return left.left < right.right && left.right > right.left &&
|
||||
left.top < right.bottom && left.bottom > right.top;
|
||||
}
|
||||
|
||||
bool rectContains(const RenderSortItem& outer, const RenderSortItem& inner)
|
||||
{
|
||||
return outer.left <= inner.left && outer.top <= inner.top &&
|
||||
outer.right >= inner.right && outer.bottom >= inner.bottom;
|
||||
}
|
||||
|
||||
bool overlaps(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (!rectIntersects(left, right)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 topDiffX = left.sxTop - right.sxBottom;
|
||||
const s32 topDiffY = left.syTop - right.syBottom;
|
||||
const s32 bottomDiffX = left.sxBottom - right.sxTop;
|
||||
const s32 bottomDiffY = left.syBottom - right.syTop;
|
||||
const bool rightClear = left.sxRight <= right.sxLeft;
|
||||
const bool leftClear = left.sxLeft >= right.sxRight;
|
||||
const bool topLeftClear = topDiffX + topDiffY * 2 >= 0;
|
||||
const bool topRightClear = -topDiffX + topDiffY * 2 >= 0;
|
||||
const bool bottomLeftClear = bottomDiffX - bottomDiffY * 2 >= 0;
|
||||
const bool bottomRightClear = -bottomDiffX - bottomDiffY * 2 >= 0;
|
||||
return !(rightClear || leftClear || topLeftClear || topRightClear || bottomLeftClear || bottomRightClear);
|
||||
}
|
||||
|
||||
bool occludes(const RenderSortItem& outer, const RenderSortItem& inner)
|
||||
{
|
||||
if (!rectContains(outer, inner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 topDiffX = outer.sxTop - inner.sxTop;
|
||||
const s32 topDiffY = outer.syTop - inner.syTop;
|
||||
const s32 bottomDiffX = outer.sxBottom - inner.sxBottom;
|
||||
const s32 bottomDiffY = outer.syBottom - inner.syBottom;
|
||||
const bool rightResult = outer.sxRight >= inner.sxRight;
|
||||
const bool leftResult = outer.sxLeft <= inner.sxLeft;
|
||||
const bool topLeftResult = topDiffX + topDiffY * 2 <= 0;
|
||||
const bool topRightResult = -topDiffX + topDiffY * 2 <= 0;
|
||||
const bool bottomLeftResult = bottomDiffX - bottomDiffY * 2 <= 0;
|
||||
const bool bottomRightResult = -bottomDiffX - bottomDiffY * 2 <= 0;
|
||||
return rightResult && leftResult && topLeftResult && topRightResult &&
|
||||
bottomLeftResult && bottomRightResult;
|
||||
}
|
||||
|
||||
bool below(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (left.sprite != right.sprite) {
|
||||
return left.sprite < right.sprite;
|
||||
}
|
||||
|
||||
if (left.flat && right.flat) {
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
} else if (left.inventoryItem == right.inventoryItem) {
|
||||
if (left.zTop <= right.z) {
|
||||
return true;
|
||||
}
|
||||
if (left.z >= right.zTop) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool yFlatLeft = left.yFar == left.y;
|
||||
const bool yFlatRight = right.yFar == right.y;
|
||||
if (yFlatLeft && yFlatRight) {
|
||||
if (left.y / 32 != right.y / 32) {
|
||||
return left.y < right.y;
|
||||
}
|
||||
} else {
|
||||
if (left.y <= right.yFar) {
|
||||
return true;
|
||||
}
|
||||
if (left.yFar >= right.y) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool xFlatLeft = left.xLeft == left.x;
|
||||
const bool xFlatRight = right.xLeft == right.x;
|
||||
if (xFlatLeft && xFlatRight) {
|
||||
if (left.x / 32 != right.x / 32) {
|
||||
return left.x < right.x;
|
||||
}
|
||||
} else {
|
||||
if (left.x <= right.xLeft) {
|
||||
return true;
|
||||
}
|
||||
if (left.xLeft >= right.x) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.zTop - 8 <= right.z && left.z < right.zTop - 8) {
|
||||
return true;
|
||||
}
|
||||
if (left.z >= right.zTop - 8 && left.zTop - 8 > right.z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (yFlatLeft != yFlatRight) {
|
||||
if (left.y / 32 <= right.yFar / 32) {
|
||||
return true;
|
||||
}
|
||||
if (left.yFar / 32 >= right.y / 32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 yCenterLeft = (left.yFar / 32 + left.y / 32) / 2;
|
||||
const s32 yCenterRight = (right.yFar / 32 + right.y / 32) / 2;
|
||||
if (yCenterLeft != yCenterRight) {
|
||||
return yCenterLeft < yCenterRight;
|
||||
}
|
||||
}
|
||||
|
||||
if (xFlatLeft != xFlatRight) {
|
||||
if (left.x / 32 <= right.xLeft / 32) {
|
||||
return true;
|
||||
}
|
||||
if (left.xLeft / 32 >= right.x / 32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 xCenterLeft = (left.xLeft / 32 + left.x / 32) / 2;
|
||||
const s32 xCenterRight = (right.xLeft / 32 + right.x / 32) / 2;
|
||||
if (xCenterLeft != xCenterRight) {
|
||||
return xCenterLeft < xCenterRight;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.flat || right.flat) {
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
if (left.inventoryItem != right.inventoryItem) {
|
||||
return left.inventoryItem < right.inventoryItem;
|
||||
}
|
||||
if (left.flat != right.flat) {
|
||||
return left.flat > right.flat;
|
||||
}
|
||||
if (left.translucent != right.translucent) {
|
||||
return left.translucent < right.translucent;
|
||||
}
|
||||
if (left.animated != right.animated) {
|
||||
return left.animated < right.animated;
|
||||
}
|
||||
if (left.draw != right.draw) {
|
||||
return left.draw > right.draw;
|
||||
}
|
||||
if (left.solid != right.solid) {
|
||||
return left.solid > right.solid;
|
||||
}
|
||||
if (left.occludes != right.occludes) {
|
||||
return left.occludes > right.occludes;
|
||||
}
|
||||
if (left.bigFlatSquare != right.bigFlatSquare) {
|
||||
return left.bigFlatSquare > right.bigFlatSquare;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.x == right.x && left.y == right.y && left.translucent != right.translucent) {
|
||||
return left.translucent < right.translucent;
|
||||
}
|
||||
if (left.land && right.land && left.roof != right.roof) {
|
||||
return left.roof < right.roof;
|
||||
}
|
||||
if (left.roof != right.roof) {
|
||||
return left.roof > right.roof;
|
||||
}
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
|
||||
if (xFlatLeft || xFlatRight || yFlatLeft || yFlatRight) {
|
||||
if (left.sxLeft != right.sxLeft) {
|
||||
return left.sxLeft > right.sxLeft;
|
||||
}
|
||||
if (left.syBottom != right.syBottom) {
|
||||
return left.syBottom < right.syBottom;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.x + left.y != right.x + right.y) {
|
||||
return left.x + left.y < right.x + right.y;
|
||||
}
|
||||
if (left.xLeft + left.yFar != right.xLeft + right.yFar) {
|
||||
return left.xLeft + left.yFar < right.xLeft + right.yFar;
|
||||
}
|
||||
if (left.y != right.y) {
|
||||
return left.y < right.y;
|
||||
}
|
||||
if (left.x != right.x) {
|
||||
return left.x < right.x;
|
||||
}
|
||||
if (left.shape != right.shape) {
|
||||
return left.shape < right.shape;
|
||||
}
|
||||
return left.frame < right.frame;
|
||||
}
|
||||
|
||||
void insertDependencySorted(std::vector<SortNode>& nodes, std::size_t owner, std::size_t dependency)
|
||||
{
|
||||
std::vector<std::size_t>& dependencies = nodes[owner].dependencies;
|
||||
for (auto current = dependencies.begin(); current != dependencies.end(); ++current) {
|
||||
if (*current == dependency) {
|
||||
return;
|
||||
}
|
||||
if (listLessThan(nodes[dependency].item, nodes[*current].item)) {
|
||||
dependencies.insert(current, dependency);
|
||||
return;
|
||||
}
|
||||
}
|
||||
dependencies.push_back(dependency);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& items)
|
||||
{
|
||||
std::vector<SortNode> nodes;
|
||||
nodes.reserve(items.size());
|
||||
for (const RenderSortItem& item : items) {
|
||||
nodes.push_back(SortNode{item, {}, false, -1});
|
||||
}
|
||||
|
||||
std::vector<std::size_t> ordered;
|
||||
ordered.reserve(nodes.size());
|
||||
for (std::size_t index = 0; index < nodes.size(); ++index) {
|
||||
std::size_t insertAt = ordered.size();
|
||||
for (std::size_t otherIndex = 0; otherIndex < ordered.size(); ++otherIndex) {
|
||||
const std::size_t other = ordered[otherIndex];
|
||||
if (insertAt == ordered.size() && listLessThan(nodes[index].item, nodes[other].item)) {
|
||||
insertAt = otherIndex;
|
||||
}
|
||||
if (nodes[other].occluded || !overlaps(nodes[index].item, nodes[other].item)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (below(nodes[index].item, nodes[other].item)) {
|
||||
if (nodes[other].item.occludes && occludes(nodes[other].item, nodes[index].item)) {
|
||||
nodes[index].occluded = true;
|
||||
break;
|
||||
}
|
||||
insertDependencySorted(nodes, other, index);
|
||||
} else if (nodes[index].item.occludes && occludes(nodes[index].item, nodes[other].item)) {
|
||||
nodes[other].occluded = true;
|
||||
} else {
|
||||
insertDependencySorted(nodes, index, other);
|
||||
}
|
||||
}
|
||||
ordered.insert(ordered.begin() + static_cast<std::ptrdiff_t>(insertAt), index);
|
||||
}
|
||||
|
||||
std::vector<std::size_t> painted;
|
||||
painted.reserve(nodes.size());
|
||||
const auto visit = [&nodes, &painted](const auto& self, std::size_t index) -> void {
|
||||
SortNode& node = nodes[index];
|
||||
if (node.occluded || node.order >= 0) {
|
||||
return;
|
||||
}
|
||||
node.order = -2;
|
||||
for (const std::size_t dependency : node.dependencies) {
|
||||
if (nodes[dependency].order == -2) {
|
||||
break;
|
||||
}
|
||||
if (nodes[dependency].order == -1) {
|
||||
self(self, dependency);
|
||||
}
|
||||
}
|
||||
node.order = static_cast<s32>(painted.size());
|
||||
painted.push_back(index);
|
||||
};
|
||||
|
||||
for (const std::size_t index : ordered) {
|
||||
if (nodes[index].order == -1) {
|
||||
visit(visit, index);
|
||||
}
|
||||
}
|
||||
return painted;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
} // namespace remorse
|
||||
|
|
@ -5,9 +5,59 @@
|
|||
#include <regex>
|
||||
#include <sstream>
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <crtdbg.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#endif
|
||||
|
||||
namespace remorse {
|
||||
namespace {
|
||||
|
||||
#ifdef _WIN32
|
||||
void writeCrashMessage(const char* message)
|
||||
{
|
||||
OutputDebugStringA(message);
|
||||
const HANDLE errorOutput = GetStdHandle(STD_ERROR_HANDLE);
|
||||
if (errorOutput != nullptr && errorOutput != INVALID_HANDLE_VALUE) {
|
||||
DWORD written = 0;
|
||||
WriteFile(errorOutput, message, static_cast<DWORD>(std::strlen(message)), &written, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
LONG WINAPI reportUnhandledException(EXCEPTION_POINTERS* exception)
|
||||
{
|
||||
char message[160];
|
||||
std::snprintf(message, sizeof(message), "Unhandled exception 0x%08lX at %p\n",
|
||||
exception->ExceptionRecord->ExceptionCode, exception->ExceptionRecord->ExceptionAddress);
|
||||
writeCrashMessage(message);
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
}
|
||||
|
||||
void reportTermination() noexcept
|
||||
{
|
||||
try {
|
||||
if (const auto error = std::current_exception()) {
|
||||
std::rethrow_exception(error);
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
char message[512];
|
||||
std::snprintf(message, sizeof(message), "Unhandled C++ exception: %s\n", error.what());
|
||||
writeCrashMessage(message);
|
||||
std::_Exit(EXIT_FAILURE);
|
||||
} catch (...) {
|
||||
writeCrashMessage("Unhandled C++ exception of unknown type\n");
|
||||
std::_Exit(EXIT_FAILURE);
|
||||
}
|
||||
writeCrashMessage("Program terminated without an active exception\n");
|
||||
std::_Exit(EXIT_FAILURE);
|
||||
}
|
||||
#endif
|
||||
|
||||
std::string readTextFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
|
|
@ -42,6 +92,23 @@ u32 readJsonU32(const std::string& json, const char* key)
|
|||
|
||||
} // namespace
|
||||
|
||||
void installCrashDiagnostics()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
|
||||
_set_error_mode(_OUT_TO_STDERR);
|
||||
#ifdef _DEBUG
|
||||
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
|
||||
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
|
||||
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
|
||||
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
|
||||
#endif
|
||||
SetUnhandledExceptionFilter(reportUnhandledException);
|
||||
std::set_terminate(reportTermination);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<ExportManifestSummary> loadExportManifestSummary(const std::filesystem::path& manifestPath)
|
||||
{
|
||||
const std::string json = readTextFile(manifestPath);
|
||||
|
|
@ -73,7 +140,7 @@ void printStartupReport(const ExportManifestSummary& manifest)
|
|||
std::cout << "Fallback function files: " << manifest.fallbackFunctionFiles << '\n';
|
||||
std::cout << "Global buckets: " << manifest.globalBuckets << '\n';
|
||||
std::cout << "Global definitions: " << manifest.globalDefinitions << '\n';
|
||||
std::cout << "Status: host runtime scaffold is alive; exported game code is not linked yet.\n";
|
||||
std::cout << "Status: StandProcess Run, registered timer, and keyboard diagnostic callback active; original key queue, NPC services, and game loop not linked.\n";
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
770
rebuild/remorse/src/windowed_game_main.cpp
Normal file
770
rebuild/remorse/src/windowed_game_main.cpp
Normal file
|
|
@ -0,0 +1,770 @@
|
|||
#define NOMINMAX
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/collision.h"
|
||||
#include "remorse/entity_dispatch_entry.h"
|
||||
#include "remorse/file_system.h"
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/glob_archive.h"
|
||||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
#include "remorse/palette.h"
|
||||
#include "remorse/runtime.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
#include "remorse/type_flags.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr wchar_t windowClassName[] = L"CrusaderRemorseGameWindow";
|
||||
constexpr UINT timerId = 1;
|
||||
constexpr UINT sceneReadyMessage = WM_APP + 1;
|
||||
constexpr remorse::u32 backingWidth = 2560;
|
||||
constexpr remorse::u32 backingHeight = 1440;
|
||||
constexpr int initialClientWidth = 1280;
|
||||
constexpr int initialClientHeight = 760;
|
||||
constexpr double simulationTickSeconds = 0.025;
|
||||
|
||||
struct AppState {
|
||||
remorse::GameDataRoot root;
|
||||
remorse::u32 mapIndex = 1;
|
||||
remorse::ProcessKernel diagnosticKernel;
|
||||
remorse::u16 diagnosticGroupCounts[32]{};
|
||||
remorse::StandProcessEntry* diagnosticStand = nullptr;
|
||||
remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr;
|
||||
remorse::u32 standWakeCount = 0;
|
||||
remorse::u32 diagnosticKeyEvents = 0;
|
||||
std::mutex sceneMutex;
|
||||
std::optional<remorse::RenderedMapImage> scene;
|
||||
std::optional<remorse::AnimationClip> standAnimation;
|
||||
std::optional<remorse::AnimationClip> walkAnimation;
|
||||
std::optional<remorse::AnimationClip> runAnimation;
|
||||
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames;
|
||||
remorse::CollisionBody playerCollisionBody{};
|
||||
std::vector<remorse::CollisionBody> collisionBodies;
|
||||
remorse::Palette256 playerPalette{};
|
||||
std::vector<std::uint8_t> dibPixels;
|
||||
std::vector<std::uint8_t> viewPixels;
|
||||
remorse::WorldPoint spawn{};
|
||||
remorse::WorldPoint playerWorld{};
|
||||
remorse::s32 minWorldX = 0;
|
||||
remorse::s32 minWorldY = 0;
|
||||
remorse::s32 maxWorldX = 0;
|
||||
remorse::s32 maxWorldY = 0;
|
||||
double playerOffsetX = 0.0;
|
||||
double playerOffsetY = 0.0;
|
||||
double simulationAccumulator = 0.0;
|
||||
remorse::u8 playerAnimation = 0;
|
||||
remorse::u8 playerDirection = 14;
|
||||
remorse::u8 playerFrame = 0;
|
||||
std::wstring loadError;
|
||||
bool sceneLoaded = false;
|
||||
std::thread sceneThread;
|
||||
HDC backBufferDc = nullptr;
|
||||
HBITMAP backBufferBitmap = nullptr;
|
||||
HBITMAP previousBackBufferBitmap = nullptr;
|
||||
int backBufferWidth = 0;
|
||||
int backBufferHeight = 0;
|
||||
LARGE_INTEGER lastTick{};
|
||||
LARGE_INTEGER ticksPerSecond{};
|
||||
};
|
||||
|
||||
remorse::u32 standSleepStart(const remorse::StandProcessEntry& stand)
|
||||
{
|
||||
const auto& bytes = stand.base.bytes;
|
||||
return bytes[0x0a] | (static_cast<remorse::u32>(bytes[0x0b]) << 8) |
|
||||
(static_cast<remorse::u32>(bytes[0x0c]) << 16) |
|
||||
(static_cast<remorse::u32>(bytes[0x0d]) << 24);
|
||||
}
|
||||
|
||||
std::wstring widen(const std::string& value)
|
||||
{
|
||||
if (value.empty()) {
|
||||
return {};
|
||||
}
|
||||
const int length = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0);
|
||||
if (length <= 0) {
|
||||
return L"Map loading failed.";
|
||||
}
|
||||
std::wstring result(static_cast<std::size_t>(length), L'\0');
|
||||
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), length);
|
||||
return result;
|
||||
}
|
||||
|
||||
void setLoadFailure(AppState& state, const std::wstring& message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
state.loadError = message;
|
||||
state.sceneLoaded = true;
|
||||
}
|
||||
|
||||
void loadSceneAsync(HWND window, AppState& state)
|
||||
{
|
||||
state.sceneThread = std::thread([window, &state]() {
|
||||
try {
|
||||
const auto fixedPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
const auto typeFlagsPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
|
||||
const auto globPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "GLOB.FLX");
|
||||
if (!fixedPath) {
|
||||
setLoadFailure(state, L"STATIC\\FIXED.DAT was not found under the game data root.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
if (!typeFlagsPath || !globPath) {
|
||||
setLoadFailure(state, L"STATIC\\TYPEFLAG.DAT or STATIC\\GLOB.FLX was not found.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto archive = remorse::loadFixedMapArchive(*fixedPath);
|
||||
const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt;
|
||||
if (!map || map->entries.empty()) {
|
||||
setLoadFailure(state, L"The selected map could not be loaded or contains no records.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath);
|
||||
const auto globObjects = remorse::loadGlobObjects(*globPath);
|
||||
if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) {
|
||||
setLoadFailure(state, L"Collision shape metadata could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects);
|
||||
|
||||
const auto animationPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "ANIM.DAT");
|
||||
const auto shapesPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "SHAPES.FLX");
|
||||
const auto palettePath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "GAMEPAL.PAL");
|
||||
if (!animationPath || !shapesPath || !palettePath) {
|
||||
setLoadFailure(state, L"The player animation, shape, or palette resource is missing.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto animationArchive = remorse::loadAnimationArchive(*animationPath);
|
||||
const auto shapeArchive = remorse::loadShapeArchive(*shapesPath);
|
||||
const auto palette = remorse::loadPalette256(*palettePath);
|
||||
const auto standAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt;
|
||||
const auto walkAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt;
|
||||
const auto runAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt;
|
||||
const auto shapeFrames = shapeArchive
|
||||
? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt;
|
||||
if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) {
|
||||
setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames(shapeFrames->size());
|
||||
const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) {
|
||||
for (remorse::u8 direction = 0; direction < 16; ++direction) {
|
||||
for (remorse::u32 frameIndex = 0; frameIndex < clip.frameCount; ++frameIndex) {
|
||||
const auto metadata = remorse::getAnimationFrame(
|
||||
clip, direction, static_cast<remorse::u8>(frameIndex));
|
||||
if (!metadata) {
|
||||
return false;
|
||||
}
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
if (shapeFrame >= playerFrames.size()) {
|
||||
return false;
|
||||
}
|
||||
if (!playerFrames[shapeFrame]) {
|
||||
auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame);
|
||||
if (!decoded) {
|
||||
return false;
|
||||
}
|
||||
playerFrames[shapeFrame] = std::move(*decoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) ||
|
||||
!cacheAnimationFrames(*runAnimation)) {
|
||||
setLoadFailure(state, L"A player animation references a missing shape frame.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
remorse::s32 minX = map->entries.front().x;
|
||||
remorse::s32 minY = map->entries.front().y;
|
||||
remorse::s32 maxX = minX;
|
||||
remorse::s32 maxY = minY;
|
||||
for (const remorse::FixedMapEntry& entry : map->entries) {
|
||||
minX = std::min(minX, static_cast<remorse::s32>(entry.x));
|
||||
minY = std::min(minY, static_cast<remorse::s32>(entry.y));
|
||||
maxX = std::max(maxX, static_cast<remorse::s32>(entry.x));
|
||||
maxY = std::max(maxY, static_cast<remorse::s32>(entry.y));
|
||||
}
|
||||
|
||||
const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0};
|
||||
remorse::MapRenderOptions options;
|
||||
options.mapIndex = state.mapIndex;
|
||||
options.maxWidth = backingWidth;
|
||||
options.maxHeight = backingHeight;
|
||||
options.viewCenter = spawn;
|
||||
auto scene = remorse::renderMapPreview(state.root, options);
|
||||
if (!scene) {
|
||||
setLoadFailure(state, L"Map graphics or palette data could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> dibPixels(scene->pixels.size() * 3);
|
||||
for (std::size_t index = 0; index < scene->pixels.size(); ++index) {
|
||||
dibPixels[index * 3] = scene->pixels[index].blue;
|
||||
dibPixels[index * 3 + 1] = scene->pixels[index].green;
|
||||
dibPixels[index * 3 + 2] = scene->pixels[index].red;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
state.spawn = spawn;
|
||||
state.playerWorld = spawn;
|
||||
state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
|
||||
state.collisionBodies = std::move(collisionBodies);
|
||||
state.minWorldX = minX;
|
||||
state.minWorldY = minY;
|
||||
state.maxWorldX = maxX;
|
||||
state.maxWorldY = maxY;
|
||||
state.scene = std::move(scene);
|
||||
state.dibPixels = std::move(dibPixels);
|
||||
state.standAnimation = *standAnimation;
|
||||
state.walkAnimation = *walkAnimation;
|
||||
state.runAnimation = *runAnimation;
|
||||
state.playerFrames = std::move(playerFrames);
|
||||
state.playerPalette = *palette;
|
||||
state.sceneLoaded = true;
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
setLoadFailure(state, widen(error.what()));
|
||||
} catch (...) {
|
||||
setLoadFailure(state, L"An unexpected error occurred while building the map scene.");
|
||||
}
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
});
|
||||
}
|
||||
|
||||
void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font)
|
||||
{
|
||||
const int saved = SaveDC(device);
|
||||
SetBkMode(device, TRANSPARENT);
|
||||
SetTextColor(device, color);
|
||||
SelectObject(device, font);
|
||||
DrawTextW(device, text, -1, const_cast<RECT*>(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
||||
RestoreDC(device, saved);
|
||||
}
|
||||
|
||||
bool isKeyDown(int key)
|
||||
{
|
||||
return (GetAsyncKeyState(key) & 0x8000) != 0;
|
||||
}
|
||||
|
||||
std::optional<remorse::u8> readMovementDirection()
|
||||
{
|
||||
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return static_cast<remorse::u8>(12);
|
||||
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return static_cast<remorse::u8>(0);
|
||||
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return static_cast<remorse::u8>(8);
|
||||
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return static_cast<remorse::u8>(4);
|
||||
|
||||
const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8);
|
||||
const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6);
|
||||
const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2);
|
||||
const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4);
|
||||
if (up && left) return static_cast<remorse::u8>(12);
|
||||
if (up && right) return static_cast<remorse::u8>(0);
|
||||
if (down && left) return static_cast<remorse::u8>(8);
|
||||
if (down && right) return static_cast<remorse::u8>(4);
|
||||
if (up) return static_cast<remorse::u8>(14);
|
||||
if (right) return static_cast<remorse::u8>(2);
|
||||
if (down) return static_cast<remorse::u8>(6);
|
||||
if (left) return static_cast<remorse::u8>(10);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool isWalkRequested()
|
||||
{
|
||||
remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0;
|
||||
if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01;
|
||||
if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02;
|
||||
return remorse::controllerWalkRequested(modifiers);
|
||||
}
|
||||
|
||||
void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
|
||||
int sourceLeft, int sourceTop, std::size_t viewStride)
|
||||
{
|
||||
const remorse::AnimationClip* clip = nullptr;
|
||||
if (state.playerAnimation == 1 && state.walkAnimation) {
|
||||
clip = &*state.walkAnimation;
|
||||
} else if (state.playerAnimation == 3 && state.runAnimation) {
|
||||
clip = &*state.runAnimation;
|
||||
} else if (state.standAnimation) {
|
||||
clip = &*state.standAnimation;
|
||||
}
|
||||
if (!clip || state.playerFrames.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame;
|
||||
const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex);
|
||||
if (!metadata) {
|
||||
return;
|
||||
}
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame];
|
||||
const int actorX = static_cast<int>(state.scene->width / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetX)) - sourceLeft;
|
||||
const int actorY = static_cast<int>(state.scene->height / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetY)) - sourceTop;
|
||||
const int spriteLeft = actorX + sprite.frame.xOffset;
|
||||
const int spriteTop = actorY + sprite.frame.yOffset;
|
||||
const bool flipped = remorse::isAnimationFrameFlipped(*metadata);
|
||||
|
||||
for (remorse::u32 y = 0; y < sprite.frame.height; ++y) {
|
||||
const int destinationY = spriteTop + static_cast<int>(y);
|
||||
if (destinationY < 0 || destinationY >= viewHeight) {
|
||||
continue;
|
||||
}
|
||||
for (remorse::u32 x = 0; x < sprite.frame.width; ++x) {
|
||||
const int destinationX = spriteLeft + static_cast<int>(x);
|
||||
if (destinationX < 0 || destinationX >= viewWidth) {
|
||||
continue;
|
||||
}
|
||||
const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x;
|
||||
const remorse::s16 paletteIndex = sprite.pixels[
|
||||
static_cast<std::size_t>(y) * sprite.frame.width + sourceX];
|
||||
if (paletteIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
const remorse::RgbColor& color = state.playerPalette.colors[
|
||||
static_cast<remorse::u8>(paletteIndex)];
|
||||
const std::size_t pixelOffset = static_cast<std::size_t>(destinationY) * viewStride +
|
||||
static_cast<std::size_t>(destinationX) * 3;
|
||||
state.viewPixels[pixelOffset] = static_cast<std::uint8_t>(color.blue * 255 / 63);
|
||||
state.viewPixels[pixelOffset + 1] = static_cast<std::uint8_t>(color.green * 255 / 63);
|
||||
state.viewPixels[pixelOffset + 2] = static_cast<std::uint8_t>(color.red * 255 / 63);
|
||||
}
|
||||
}
|
||||
|
||||
BITMAPINFO bitmap{};
|
||||
bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
|
||||
bitmap.bmiHeader.biWidth = viewWidth;
|
||||
bitmap.bmiHeader.biHeight = -viewHeight;
|
||||
bitmap.bmiHeader.biPlanes = 1;
|
||||
bitmap.bmiHeader.biBitCount = 24;
|
||||
bitmap.bmiHeader.biCompression = BI_RGB;
|
||||
StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight,
|
||||
state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY);
|
||||
}
|
||||
|
||||
void drawLoadingScreen(HDC device, const RECT& client, const AppState& state)
|
||||
{
|
||||
HBRUSH background = CreateSolidBrush(RGB(13, 23, 28));
|
||||
FillRect(device, &client, background);
|
||||
DeleteObject(background);
|
||||
|
||||
RECT title = client;
|
||||
title.bottom = title.top + 70;
|
||||
HFONT titleFont = CreateFontW(-30, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Bahnschrift");
|
||||
drawCenteredText(device, title, L"CRUSADER / NO REMORSE", RGB(228, 220, 191), titleFont);
|
||||
DeleteObject(titleFont);
|
||||
|
||||
RECT status = client;
|
||||
status.top = title.bottom;
|
||||
HFONT bodyFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
|
||||
const std::wstring message = state.loadError.empty()
|
||||
? L"Building the retail map scene..."
|
||||
: state.loadError;
|
||||
drawCenteredText(device, status, message.c_str(), state.loadError.empty()
|
||||
? RGB(74, 207, 184) : RGB(245, 157, 119), bodyFont);
|
||||
DeleteObject(bodyFont);
|
||||
}
|
||||
|
||||
void paintWindow(HWND window, AppState& state)
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
HDC paintDc = BeginPaint(window, &paint);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
|
||||
const int clientWidth = static_cast<int>(std::max(1L, client.right - client.left));
|
||||
const int clientHeight = static_cast<int>(std::max(1L, client.bottom - client.top));
|
||||
if (state.backBufferWidth != clientWidth || state.backBufferHeight != clientHeight) {
|
||||
if (state.backBufferDc) {
|
||||
SelectObject(state.backBufferDc, state.previousBackBufferBitmap);
|
||||
DeleteObject(state.backBufferBitmap);
|
||||
DeleteDC(state.backBufferDc);
|
||||
state.backBufferDc = nullptr;
|
||||
state.backBufferBitmap = nullptr;
|
||||
state.previousBackBufferBitmap = nullptr;
|
||||
}
|
||||
state.backBufferDc = CreateCompatibleDC(paintDc);
|
||||
if (state.backBufferDc) {
|
||||
state.backBufferBitmap = CreateCompatibleBitmap(paintDc, clientWidth, clientHeight);
|
||||
if (state.backBufferBitmap) {
|
||||
state.previousBackBufferBitmap = static_cast<HBITMAP>(
|
||||
SelectObject(state.backBufferDc, state.backBufferBitmap));
|
||||
state.backBufferWidth = clientWidth;
|
||||
state.backBufferHeight = clientHeight;
|
||||
} else {
|
||||
DeleteDC(state.backBufferDc);
|
||||
state.backBufferDc = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
HDC device = state.backBufferDc ? state.backBufferDc : paintDc;
|
||||
const auto finishPaint = [&]() {
|
||||
if (device != paintDc) {
|
||||
BitBlt(paintDc, 0, 0, clientWidth, clientHeight, device, 0, 0, SRCCOPY);
|
||||
}
|
||||
EndPaint(window, &paint);
|
||||
};
|
||||
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
if (!state.sceneLoaded || !state.scene) {
|
||||
drawLoadingScreen(device, client, state);
|
||||
finishPaint();
|
||||
return;
|
||||
}
|
||||
if (!state.loadError.empty()) {
|
||||
drawLoadingScreen(device, client, state);
|
||||
finishPaint();
|
||||
return;
|
||||
}
|
||||
|
||||
HBRUSH clearBrush = CreateSolidBrush(RGB(10, 17, 22));
|
||||
FillRect(device, &client, clearBrush);
|
||||
DeleteObject(clearBrush);
|
||||
|
||||
const int viewWidth = std::min(clientWidth, static_cast<int>(state.scene->width));
|
||||
const int viewHeight = std::min(clientHeight, static_cast<int>(state.scene->height));
|
||||
const int centeredLeft = static_cast<int>(state.scene->width / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetX)) - viewWidth / 2;
|
||||
const int centeredTop = static_cast<int>(state.scene->height / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetY)) - viewHeight / 2;
|
||||
const int sourceLeft = std::clamp(centeredLeft, 0, static_cast<int>(state.scene->width) - viewWidth);
|
||||
const int sourceTop = std::clamp(centeredTop, 0, static_cast<int>(state.scene->height) - viewHeight);
|
||||
|
||||
const std::size_t viewStride = (static_cast<std::size_t>(viewWidth) * 3 + 3) & ~std::size_t(3);
|
||||
state.viewPixels.resize(viewStride * static_cast<std::size_t>(viewHeight));
|
||||
const std::size_t sceneStride = static_cast<std::size_t>(state.scene->width) * 3;
|
||||
for (int row = 0; row < viewHeight; ++row) {
|
||||
const std::size_t sceneOffset = static_cast<std::size_t>(sourceTop + row) * sceneStride +
|
||||
static_cast<std::size_t>(sourceLeft) * 3;
|
||||
const std::size_t viewOffset = static_cast<std::size_t>(row) * viewStride;
|
||||
std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset,
|
||||
static_cast<std::size_t>(viewWidth) * 3);
|
||||
}
|
||||
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
|
||||
|
||||
RECT hud{0, 0, viewWidth, 62};
|
||||
HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29));
|
||||
FillRect(device, &hud, hudBrush);
|
||||
DeleteObject(hudBrush);
|
||||
HPEN hudLine = CreatePen(PS_SOLID, 1, RGB(43, 204, 178));
|
||||
HGDIOBJ oldPen = SelectObject(device, hudLine);
|
||||
MoveToEx(device, 0, hud.bottom - 1, nullptr);
|
||||
LineTo(device, viewWidth, hud.bottom - 1);
|
||||
SelectObject(device, oldPen);
|
||||
DeleteObject(hudLine);
|
||||
|
||||
std::wostringstream label;
|
||||
label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex
|
||||
<< L" X " << state.playerWorld.x
|
||||
<< L" Y " << state.playerWorld.y
|
||||
<< L" Z " << static_cast<int>(state.playerWorld.z)
|
||||
<< L" DIR " << std::setw(2) << static_cast<int>(state.playerDirection)
|
||||
<< L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE")
|
||||
<< L" WASD / KEYPAD SHIFT RUN";
|
||||
HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
|
||||
RECT labelBounds{20, 0, viewWidth - 12, 36};
|
||||
const int saved = SaveDC(device);
|
||||
SetBkMode(device, TRANSPARENT);
|
||||
SetTextColor(device, RGB(224, 229, 214));
|
||||
SelectObject(device, hudFont);
|
||||
DrawTextW(device, label.str().c_str(), -1, &labelBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
|
||||
const remorse::EntityDispatchEntryBase& stand = state.diagnosticStand->base;
|
||||
const remorse::u32 sleepStart = standSleepStart(*state.diagnosticStand);
|
||||
const remorse::u32 sleepLength = stand.bytes[0x0e] | (static_cast<remorse::u32>(stand.bytes[0x0f]) << 8);
|
||||
std::wostringstream diagnostics;
|
||||
diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick()
|
||||
<< L" | STAND #" << static_cast<int>(stand.bytes[0x02])
|
||||
<< L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ")
|
||||
<< ((stand.bytes[0x19] & 0x10) != 0
|
||||
? static_cast<remorse::u32>(sleepStart + sleepLength - state.diagnosticKernel.systemTimerTick() + 1)
|
||||
: 0)
|
||||
<< L" | WAKEUPS " << state.standWakeCount
|
||||
<< L" | KEY EVENTS " << state.diagnosticKeyEvents;
|
||||
RECT diagnosticsBounds{20, 36, viewWidth - 12, hud.bottom - 1};
|
||||
SetTextColor(device, RGB(74, 207, 184));
|
||||
DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
|
||||
RestoreDC(device, saved);
|
||||
DeleteObject(hudFont);
|
||||
|
||||
finishPaint();
|
||||
}
|
||||
|
||||
void updatePlayer(HWND window, AppState& state)
|
||||
{
|
||||
LARGE_INTEGER now{};
|
||||
QueryPerformanceCounter(&now);
|
||||
const double elapsed = std::clamp(
|
||||
static_cast<double>(now.QuadPart - state.lastTick.QuadPart) /
|
||||
static_cast<double>(state.ticksPerSecond.QuadPart),
|
||||
0.0, 0.25);
|
||||
state.lastTick = now;
|
||||
|
||||
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
|
||||
DestroyWindow(window);
|
||||
return;
|
||||
}
|
||||
if (GetForegroundWindow() != window) {
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.simulationAccumulator += elapsed;
|
||||
const auto direction = readMovementDirection();
|
||||
bool changed = false;
|
||||
while (state.simulationAccumulator >= simulationTickSeconds) {
|
||||
state.simulationAccumulator -= simulationTickSeconds;
|
||||
state.diagnosticKernel.deliverSystemTimerEvent();
|
||||
const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0;
|
||||
const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand);
|
||||
state.diagnosticKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& entry, void* context) {
|
||||
auto& app = *static_cast<AppState*>(context);
|
||||
if (&entry == &app.diagnosticStand->base) {
|
||||
remorse::StandProcess::run(entry,
|
||||
[](const remorse::EntityDispatchEntryBase&, void*) { return false; },
|
||||
nullptr, app.diagnosticKernel.systemTimerTick());
|
||||
}
|
||||
}, &state, state.diagnosticKernel.systemTimerTick());
|
||||
if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) {
|
||||
++state.standWakeCount;
|
||||
}
|
||||
changed = true;
|
||||
if (!direction) {
|
||||
changed = changed || state.playerAnimation != 0 || state.playerFrame != 0;
|
||||
state.playerAnimation = 0;
|
||||
state.playerFrame = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3;
|
||||
const remorse::AnimationClip& clip = requestedAnimation == 1
|
||||
? *state.walkAnimation : *state.runAnimation;
|
||||
if (state.playerAnimation != requestedAnimation) {
|
||||
state.playerAnimation = requestedAnimation;
|
||||
state.playerFrame = 0;
|
||||
} else {
|
||||
state.playerFrame = static_cast<remorse::u8>(
|
||||
(state.playerFrame + 1) % clip.frameCount);
|
||||
}
|
||||
state.playerDirection = *direction;
|
||||
|
||||
const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame);
|
||||
if (metadata) {
|
||||
const auto step = remorse::hostMovementStep(
|
||||
*metadata, state.playerDirection, (clip.header[2] & 0x10) != 0);
|
||||
if (step) {
|
||||
const remorse::WorldPoint destination{
|
||||
state.playerWorld.x + step->x,
|
||||
state.playerWorld.y + step->y,
|
||||
state.playerWorld.z + step->z};
|
||||
const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination);
|
||||
const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn);
|
||||
const double nextOffsetX = destinationScreen.x - spawnScreen.x;
|
||||
const double nextOffsetY = destinationScreen.y - spawnScreen.y;
|
||||
const bool withinMapBounds = destination.x >= state.minWorldX &&
|
||||
destination.x <= state.maxWorldX && destination.y >= state.minWorldY &&
|
||||
destination.y <= state.maxWorldY;
|
||||
const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 &&
|
||||
std::abs(nextOffsetY) <= backingHeight / 2 - 16;
|
||||
if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody(
|
||||
state.playerCollisionBody, destination, state.collisionBodies)) {
|
||||
state.playerWorld = destination;
|
||||
state.playerCollisionBody.location = destination;
|
||||
state.playerOffsetX = nextOffsetX;
|
||||
state.playerOffsetY = nextOffsetY;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
AppState* state = reinterpret_cast<AppState*>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (message == WM_NCCREATE) {
|
||||
const auto* create = reinterpret_cast<const CREATESTRUCTW*>(lParam);
|
||||
state = static_cast<AppState*>(create->lpCreateParams);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(state));
|
||||
}
|
||||
if (!state) {
|
||||
return DefWindowProcW(window, message, wParam, lParam);
|
||||
}
|
||||
|
||||
switch (message) {
|
||||
case WM_CREATE:
|
||||
QueryPerformanceFrequency(&state->ticksPerSecond);
|
||||
QueryPerformanceCounter(&state->lastTick);
|
||||
SetTimer(window, timerId, 16, nullptr);
|
||||
loadSceneAsync(window, *state);
|
||||
return 0;
|
||||
case WM_TIMER:
|
||||
if (wParam == timerId) {
|
||||
updatePlayer(window, *state);
|
||||
}
|
||||
return 0;
|
||||
case WM_CHAR:
|
||||
if (wParam > 0 && wParam <= 0xff) {
|
||||
remorse::KeyEvent lastEvent{};
|
||||
lastEvent.character = static_cast<remorse::u8>(wParam);
|
||||
lastEvent.scanCode = static_cast<remorse::u8>((lParam >> 16) & 0xff);
|
||||
lastEvent.field8 = 1;
|
||||
remorse::KeyEvent event = lastEvent;
|
||||
if (remorse::KeyboardProcess::handleKeyEvent(*state->diagnosticKeyboard, 0x10, 0, event, lastEvent)) {
|
||||
++state->diagnosticKeyEvents;
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
case WM_SIZE:
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
case WM_ERASEBKGND:
|
||||
return 1;
|
||||
case WM_PAINT:
|
||||
paintWindow(window, *state);
|
||||
return 0;
|
||||
case sceneReadyMessage:
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, timerId);
|
||||
if (state->sceneThread.joinable()) {
|
||||
state->sceneThread.join();
|
||||
}
|
||||
if (state->backBufferDc) {
|
||||
SelectObject(state->backBufferDc, state->previousBackBufferBitmap);
|
||||
DeleteObject(state->backBufferBitmap);
|
||||
DeleteDC(state->backBufferDc);
|
||||
}
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
default:
|
||||
return DefWindowProcW(window, message, wParam, lParam);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCommand)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
remorse::u32 mapIndex = 1;
|
||||
if (commandLine && *commandLine) {
|
||||
wchar_t* end = nullptr;
|
||||
const unsigned long parsed = std::wcstoul(commandLine, &end, 0);
|
||||
if (end != commandLine && parsed <= 255) {
|
||||
mapIndex = static_cast<remorse::u32>(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
wchar_t executablePath[MAX_PATH]{};
|
||||
GetModuleFileNameW(nullptr, executablePath, MAX_PATH);
|
||||
auto root = remorse::findGameDataRoot(std::filesystem::path(executablePath).parent_path());
|
||||
if (!root) {
|
||||
root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
}
|
||||
if (!root) {
|
||||
MessageBoxW(nullptr,
|
||||
L"Could not locate CRUSADER.EXE, STATIC, and USECODE. Place this application below the game data folder or launch it from that folder.",
|
||||
L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 2;
|
||||
}
|
||||
|
||||
AppState state;
|
||||
state.root = *root;
|
||||
state.mapIndex = mapIndex;
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts);
|
||||
}
|
||||
state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts);
|
||||
|
||||
WNDCLASSEXW windowClass{};
|
||||
windowClass.cbSize = sizeof(windowClass);
|
||||
windowClass.style = CS_HREDRAW | CS_VREDRAW;
|
||||
windowClass.lpfnWndProc = windowProcedure;
|
||||
windowClass.hInstance = instance;
|
||||
windowClass.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512));
|
||||
windowClass.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512));
|
||||
windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
|
||||
windowClass.lpszClassName = windowClassName;
|
||||
if (!RegisterClassExW(&windowClass)) {
|
||||
MessageBoxW(nullptr, L"Could not register the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 3;
|
||||
}
|
||||
|
||||
RECT bounds{0, 0, initialClientWidth, initialClientHeight};
|
||||
AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE);
|
||||
HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top,
|
||||
nullptr, nullptr, instance, &state);
|
||||
if (!window) {
|
||||
MessageBoxW(nullptr, L"Could not create the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 4;
|
||||
}
|
||||
|
||||
ShowWindow(window, showCommand);
|
||||
UpdateWindow(window);
|
||||
MSG message{};
|
||||
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return static_cast<int>(message.wParam);
|
||||
}
|
||||
149
rebuild/remorse/tests/animation_archive_tests.cpp
Normal file
149
rebuild/remorse/tests/animation_archive_tests.cpp
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/file_system.h"
|
||||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <filesystem>
|
||||
|
||||
namespace {
|
||||
|
||||
void writeU32Le(std::vector<remorse::u8>& bytes, std::size_t offset, remorse::u32 value)
|
||||
{
|
||||
for (std::size_t index = 0; index < 4; ++index) {
|
||||
bytes[offset + index] = static_cast<remorse::u8>(value >> (index * 8));
|
||||
}
|
||||
}
|
||||
|
||||
remorse::AnimationArchive makeSyntheticArchive()
|
||||
{
|
||||
constexpr remorse::u32 shapeTable = 0x20;
|
||||
constexpr remorse::u32 clipOffset = 0x440;
|
||||
std::vector<remorse::u8> bytes(clipOffset + 4 + 2 * 16 * 8);
|
||||
writeU32Le(bytes, 4, shapeTable);
|
||||
writeU32Le(bytes, shapeTable + 4, clipOffset);
|
||||
bytes[clipOffset] = 2;
|
||||
bytes[clipOffset + 1] = 5;
|
||||
bytes[clipOffset + 2] = 0x02;
|
||||
bytes[clipOffset + 3] = 0x40;
|
||||
const std::size_t frameOffset = clipOffset + 4 + (5 * 2 + 1) * 8;
|
||||
bytes[frameOffset] = 0x34;
|
||||
bytes[frameOffset + 1] = 0x81;
|
||||
bytes[frameOffset + 2] = 0xfe;
|
||||
bytes[frameOffset + 4] = 0xff;
|
||||
bytes[frameOffset + 5] = 0x01;
|
||||
return remorse::AnimationArchive{std::move(bytes)};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto synthetic = makeSyntheticArchive();
|
||||
const auto sixteenDirectionClip = remorse::loadAnimationClip(synthetic, 1, 1);
|
||||
assert(sixteenDirectionClip.has_value());
|
||||
assert(sixteenDirectionClip->frameCount == 2);
|
||||
assert(sixteenDirectionClip->directionCount == 16);
|
||||
const auto selectedFrame = remorse::getAnimationFrame(*sixteenDirectionClip, 5, 1);
|
||||
assert(selectedFrame.has_value());
|
||||
assert(remorse::getAnimationShapeFrame(*selectedFrame) == 0x134);
|
||||
assert(remorse::isAnimationFrameFlipped(*selectedFrame));
|
||||
const auto rotatedStep = remorse::decodeAnimationDisplacement(*selectedFrame, 5, true);
|
||||
assert(rotatedStep.has_value());
|
||||
assert(rotatedStep->x == 2);
|
||||
assert(rotatedStep->y == -4);
|
||||
assert(rotatedStep->z == -2);
|
||||
assert(!rotatedStep->onGround);
|
||||
assert(!remorse::getAnimationFrame(*sixteenDirectionClip, 16, 0));
|
||||
assert(!remorse::getAnimationFrame(*sixteenDirectionClip, 0, 2));
|
||||
|
||||
remorse::AnimationFrameMetadata negativeStride;
|
||||
negativeStride.bytes[4] = 0xff;
|
||||
negativeStride.bytes[5] = 0x01;
|
||||
const auto northStep = remorse::decodeAnimationDisplacement(negativeStride, 0, false);
|
||||
assert(northStep.has_value());
|
||||
assert(northStep->x == 0);
|
||||
assert(northStep->y == 2);
|
||||
negativeStride.bytes[5] = 0x03;
|
||||
const auto groundedStep = remorse::decodeAnimationDisplacement(negativeStride, 0, false);
|
||||
assert(groundedStep.has_value() && groundedStep->onGround);
|
||||
|
||||
remorse::AnimationFrameMetadata positiveStride;
|
||||
positiveStride.bytes[4] = 1;
|
||||
const remorse::s32 expectedX[16] = {
|
||||
0, 2, 2, 4, 2, 4, 2, 2, 0, -2, -2, -4, -2, -4, -2, -2};
|
||||
const remorse::s32 expectedY[16] = {
|
||||
-2, -4, -2, -2, 0, 2, 2, 4, 2, 4, 2, 2, 0, -2, -2, -4};
|
||||
for (remorse::u8 direction = 0; direction < 16; ++direction) {
|
||||
const auto step = remorse::decodeAnimationDisplacement(positiveStride, direction, false);
|
||||
assert(step.has_value());
|
||||
assert(step->x == expectedX[direction]);
|
||||
assert(step->y == expectedY[direction]);
|
||||
}
|
||||
|
||||
remorse::AnimationArchive malformed;
|
||||
malformed.bytes.resize(8);
|
||||
writeU32Le(malformed.bytes, 4, 0xfffffff0);
|
||||
assert(!remorse::loadAnimationClip(malformed, 1, 0));
|
||||
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
assert(root.has_value());
|
||||
const auto animationPath = remorse::resolveGameDataPath(
|
||||
*root, std::filesystem::path("STATIC") / "ANIM.DAT");
|
||||
assert(animationPath.has_value());
|
||||
const auto animationArchive = remorse::loadAnimationArchive(*animationPath);
|
||||
assert(animationArchive.has_value());
|
||||
|
||||
const auto stand = remorse::loadAnimationClip(*animationArchive, 1, 0);
|
||||
const auto walk = remorse::loadAnimationClip(*animationArchive, 1, 1);
|
||||
const auto run = remorse::loadAnimationClip(*animationArchive, 1, 3);
|
||||
assert(stand.has_value() && stand->frameCount > 0);
|
||||
assert(walk.has_value() && walk->frameCount == 17);
|
||||
assert(run.has_value() && run->frameCount == 12);
|
||||
assert(remorse::getAnimationFrame(*walk, 0, 0).has_value());
|
||||
assert(remorse::getAnimationFrame(*run, 15, 11).has_value());
|
||||
for (remorse::u8 direction : {remorse::u8{6}, remorse::u8{7}, remorse::u8{10}, remorse::u8{11}}) {
|
||||
for (remorse::u8 frame : {remorse::u8{4}, remorse::u8{12}}) {
|
||||
const auto metadata = remorse::getAnimationFrame(*walk, direction, frame);
|
||||
assert(metadata.has_value() && (metadata->bytes[5] & 1) != 0);
|
||||
const auto authored = remorse::decodeAnimationDisplacement(*metadata, direction, false);
|
||||
const auto host = remorse::hostMovementStep(*metadata, direction, false);
|
||||
assert(authored && (authored->x < 0 || authored->y < 0));
|
||||
assert(host && host->x == 0 && host->y == 0);
|
||||
}
|
||||
}
|
||||
const auto runFrame = remorse::getAnimationFrame(*run, 14, 6);
|
||||
assert(runFrame.has_value());
|
||||
const auto hostRun = remorse::hostMovementStep(*runFrame, 14, false);
|
||||
assert(hostRun && hostRun->x < 0 && hostRun->y < 0);
|
||||
|
||||
const auto shapesPath = remorse::resolveGameDataPath(
|
||||
*root, std::filesystem::path("STATIC") / "SHAPES.FLX");
|
||||
assert(shapesPath.has_value());
|
||||
const auto shapeArchive = remorse::loadShapeArchive(*shapesPath);
|
||||
assert(shapeArchive.has_value());
|
||||
const auto playerFrames = remorse::loadShapeFrames(*shapeArchive, 1);
|
||||
assert(playerFrames.has_value() && playerFrames->size() >= walk->frameCount);
|
||||
std::vector<bool> referencedFrames(playerFrames->size(), false);
|
||||
for (const remorse::AnimationClip* clip : {&*stand, &*walk, &*run}) {
|
||||
for (remorse::u8 direction = 0; direction < 16; ++direction) {
|
||||
for (remorse::u8 frame = 0; frame < clip->frameCount; ++frame) {
|
||||
const auto metadata = remorse::getAnimationFrame(*clip, direction, frame);
|
||||
assert(metadata.has_value());
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
assert(shapeFrame < referencedFrames.size());
|
||||
referencedFrames[shapeFrame] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool decodedReferencedFrame = false;
|
||||
for (std::size_t frame = 0; frame < referencedFrames.size(); ++frame) {
|
||||
if (referencedFrames[frame]) {
|
||||
assert(remorse::decodeShapeFrame(*shapeArchive, 1, static_cast<remorse::u32>(frame)).has_value());
|
||||
decodedReferencedFrame = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert(decodedReferencedFrame);
|
||||
return 0;
|
||||
}
|
||||
72
rebuild/remorse/tests/collision_tests.cpp
Normal file
72
rebuild/remorse/tests/collision_tests.cpp
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
#include "remorse/collision.h"
|
||||
|
||||
#include <cassert>
|
||||
|
||||
int main()
|
||||
{
|
||||
const remorse::CollisionBody actor{{100, 100, 0}, 96, 96, 80};
|
||||
const remorse::CollisionBody wall{{300, 100, 0}, 64, 96, 128};
|
||||
assert(!remorse::collisionBodiesOverlap(actor, wall));
|
||||
assert(remorse::canMoveCollisionBody(actor, {200, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(actor, {260, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(actor, {400, 100, 0}, {wall}));
|
||||
|
||||
const remorse::CollisionBody floorBelow{{300, 100, -20}, 64, 96, 20};
|
||||
const remorse::CollisionBody overhead{{300, 100, 80}, 64, 96, 32};
|
||||
assert(!remorse::collisionBodiesOverlap(actor, floorBelow));
|
||||
assert(!remorse::collisionBodiesOverlap(actor, overhead));
|
||||
|
||||
const remorse::CollisionBody initiallyOverlapping{{250, 100, 0}, 96, 96, 80};
|
||||
assert(remorse::canMoveCollisionBody(initiallyOverlapping, {200, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(initiallyOverlapping, {400, 100, 0}, {wall}));
|
||||
|
||||
remorse::ShapeTypeInfo actorInfo;
|
||||
actorInfo.x = 3;
|
||||
actorInfo.y = 3;
|
||||
actorInfo.z = 10;
|
||||
actorInfo.flags = 0x2;
|
||||
const remorse::CollisionBody authoredActor = remorse::makeCollisionBody({100, 100, 0}, actorInfo);
|
||||
assert(authoredActor.extentX == 96);
|
||||
assert(authoredActor.extentY == 96);
|
||||
assert(authoredActor.extentZ == 80);
|
||||
|
||||
remorse::ShapeTypeInfo obstacleInfo;
|
||||
obstacleInfo.x = 2;
|
||||
obstacleInfo.y = 4;
|
||||
obstacleInfo.z = 8;
|
||||
const remorse::CollisionBody flipped = remorse::makeCollisionBody({300, 300, 0}, obstacleInfo, true);
|
||||
assert(flipped.extentX == 128);
|
||||
assert(flipped.extentY == 64);
|
||||
|
||||
remorse::FixedMap map;
|
||||
remorse::FixedMapEntry solid;
|
||||
solid.x = 500;
|
||||
solid.y = 600;
|
||||
solid.shape = 1;
|
||||
map.entries.push_back(solid);
|
||||
remorse::FixedMapEntry globParent;
|
||||
globParent.x = 0x480;
|
||||
globParent.y = 0x640;
|
||||
globParent.shape = 2;
|
||||
globParent.quality = 7;
|
||||
map.entries.push_back(globParent);
|
||||
|
||||
std::vector<remorse::ShapeTypeInfo> shapeTypes(4);
|
||||
shapeTypes[1] = obstacleInfo;
|
||||
shapeTypes[1].flags = 0x2;
|
||||
shapeTypes[2].family = 3;
|
||||
shapeTypes[2].flags = 0x2;
|
||||
shapeTypes[3] = obstacleInfo;
|
||||
shapeTypes[3].flags = 0x2;
|
||||
|
||||
remorse::GlobObject glob;
|
||||
glob.index = 7;
|
||||
glob.entries.push_back(remorse::GlobObjectEntry{2, 3, 4, 3, 0});
|
||||
const auto bodies = remorse::collectMapCollisionBodies(map, shapeTypes, {glob});
|
||||
assert(bodies.size() == 2);
|
||||
assert(bodies[0].location.x == 500 && bodies[0].location.y == 600);
|
||||
assert(bodies[1].location.x == (0x480 & ~0x3ff) + 2 * 4 + 2);
|
||||
assert(bodies[1].location.y == (0x640 & ~0x3ff) + 3 * 4 + 2);
|
||||
assert(bodies[1].location.z == 4);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -1,11 +1,30 @@
|
|||
#include "remorse/entity_dispatch_entry.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
int main()
|
||||
{
|
||||
remorse::EntityDispatchEntryBase entry{};
|
||||
remorse::EntityDispatchEntry::initBase(&entry);
|
||||
remorse::u16 groupCounts[32]{};
|
||||
for (remorse::u8& byte : entry.bytes) {
|
||||
byte = 0xa5;
|
||||
}
|
||||
assert(remorse::EntityDispatchEntry::initBase(&entry, 1, groupCounts) == &entry);
|
||||
assert(entry.bytes[0x00] == 0x06 && entry.bytes[0x01] == 0x3b);
|
||||
assert(entry.bytes[0x09] == 0xa5);
|
||||
assert(entry.bytes[0x1e] == 0x10 && entry.bytes[0x1f] == 0x2d);
|
||||
assert(entry.bytes[0x28] == 0xfe && entry.bytes[0x29] == 0x3a);
|
||||
for (remorse::u16 offset : {remorse::u16{0x02}, remorse::u16{0x04}, remorse::u16{0x0a}, remorse::u16{0x12}, remorse::u16{0x16}, remorse::u16{0x1a}, remorse::u16{0x20}, remorse::u16{0x26}, remorse::u16{0x2a}, remorse::u16{0x30}}) {
|
||||
assert(entry.bytes[offset] == 0 && entry.bytes[offset + 1] == 0);
|
||||
}
|
||||
assert(entry.bytes[0x06] == 1 && entry.bytes[0x07] == 0);
|
||||
assert(entry.bytes[0x08] == 1 && groupCounts[1] == 1);
|
||||
assert(entry.bytes[0x18] == 1 && entry.bytes[0x19] == 0);
|
||||
assert(remorse::EntityDispatchEntry::initBase(nullptr, 1, groupCounts) == nullptr);
|
||||
assert(groupCounts[1] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setSourceType(entry, 0x1234);
|
||||
assert(entry.bytes[0x04] == 0x34);
|
||||
|
|
@ -15,12 +34,446 @@ int main()
|
|||
assert(entry.bytes[0x06] == 0xf2);
|
||||
assert(entry.bytes[0x07] == 0x00);
|
||||
|
||||
entry.bytes[0x08] = 0xe0;
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 0x23);
|
||||
assert(entry.bytes[0x08] == 0xe3);
|
||||
remorse::EntityDispatchEntry::sleep(entry, 0x12345678, 0x0001003c);
|
||||
assert(entry.bytes[0x18] == 0x01 && entry.bytes[0x19] == 0x10);
|
||||
assert(entry.bytes[0x0a] == 0x78 && entry.bytes[0x0b] == 0x56);
|
||||
assert(entry.bytes[0x0c] == 0x34 && entry.bytes[0x0d] == 0x12);
|
||||
assert(entry.bytes[0x0e] == 0x3c && entry.bytes[0x0f] == 0x00);
|
||||
assert(entry.bytes[0x10] == 0x01 && entry.bytes[0x11] == 0x00);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(groupCounts[1] == 0 && groupCounts[3] == 1);
|
||||
entry.bytes[0x08] = 0xe3;
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(entry.bytes[0x08] == 0xe3 && groupCounts[3] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(groupCounts[3] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 4, groupCounts);
|
||||
assert(entry.bytes[0x08] == 4 && groupCounts[3] == 0 && groupCounts[4] == 1);
|
||||
|
||||
for (remorse::u8 invalidId : {remorse::u8{0}, remorse::u8{32}}) {
|
||||
bool rejected = false;
|
||||
try {
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, invalidId, groupCounts);
|
||||
} catch (const std::invalid_argument&) {
|
||||
rejected = true;
|
||||
}
|
||||
assert(rejected && entry.bytes[0x08] == 4 && groupCounts[4] == 1);
|
||||
}
|
||||
|
||||
remorse::EntityDispatchEntry::incrementGroupId(entry);
|
||||
assert(entry.bytes[0x08] == 0xe4);
|
||||
assert(entry.bytes[0x08] == 5);
|
||||
|
||||
remorse::ProcessKernel kernel;
|
||||
kernel.setLastAllocationSize(sizeof(entry));
|
||||
assert(kernel.addProcess(entry) == 0);
|
||||
assert(entry.bytes[0x02] == 0 && entry.bytes[0x03] == 0);
|
||||
assert(kernel.processAt(0) == &entry);
|
||||
assert(kernel.allocationSizeAt(0) == 0x32);
|
||||
assert(kernel.processCount() == 1 && kernel.capacity() == 30);
|
||||
assert(std::strcmp(kernel.processNameAt(0), "Default") == 0);
|
||||
remorse::EntityDispatchEntryBase second{};
|
||||
kernel.setMarkNewProcesses(true);
|
||||
assert(kernel.addProcess(second) == 1);
|
||||
assert(second.bytes[0x02] == 1 && second.bytes[0x03] == 0);
|
||||
assert(kernel.allocationSizeAt(1) == 0);
|
||||
assert(second.bytes[0x19] == 0x02 && kernel.newlyCreatedCount() == 1);
|
||||
kernel.setMarkNewProcesses(false);
|
||||
kernel.clearProcessSlot(1);
|
||||
assert(kernel.processAt(1) == nullptr && kernel.allocationSizeAt(1) == 0);
|
||||
assert(kernel.processNameAt(1) == nullptr && kernel.processCount() == 2);
|
||||
remorse::EntityDispatchEntryBase reused{};
|
||||
assert(kernel.addProcess(reused) == 1 && kernel.processAt(1) == &reused);
|
||||
std::vector<remorse::EntityDispatchEntryBase> additional(29);
|
||||
for (auto& process : additional) {
|
||||
kernel.addProcess(process);
|
||||
}
|
||||
assert(kernel.processAt(30) == &additional.back());
|
||||
assert(kernel.capacity() == 60 && kernel.processCount() == 32);
|
||||
|
||||
remorse::ProcessKernel createdKernel;
|
||||
remorse::u16 createdGroups[32]{};
|
||||
auto* created = createdKernel.createProcess(2, createdGroups);
|
||||
assert(created != nullptr && createdKernel.processAt(0) == created);
|
||||
assert(createdKernel.processCount() == 1 && createdKernel.allocationSizeAt(0) == 0x32);
|
||||
assert(created->bytes[0x02] == 0 && created->bytes[0x03] == 0);
|
||||
assert(created->bytes[0x08] == 2 && createdGroups[2] == 1);
|
||||
createdKernel.setSyncContext(true, 1);
|
||||
auto* next = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(1) == next && createdGroups[2] == 2);
|
||||
assert(next->bytes[0x02] == 1 && next->bytes[0x03] == 0);
|
||||
assert(next->bytes[0x16] == 0);
|
||||
createdKernel.setSyncContext(true, 0);
|
||||
auto* syncing = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(2) == syncing && createdGroups[2] == 3);
|
||||
assert(syncing->bytes[0x16] == 0x40 && syncing->bytes[0x17] == 0);
|
||||
|
||||
createdKernel.setSyncContext(true, 1);
|
||||
next->bytes[0x18] |= 0x02;
|
||||
auto* retiring = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(3) == retiring && createdKernel.processCount() == 4);
|
||||
assert(next->bytes[0x18] == 0x07 && retiring->bytes[0x16] == 0x40);
|
||||
createdKernel.terminateProcess(3, createdGroups);
|
||||
assert(createdKernel.processAt(3) == retiring && (retiring->bytes[0x16] & 0x08) != 0);
|
||||
assert(createdKernel.processCount() == 3 && createdKernel.terminatedProcessCount() == 1);
|
||||
assert(createdGroups[2] == 3);
|
||||
bool alreadyTerminated = false;
|
||||
try {
|
||||
createdKernel.terminateProcess(3, createdGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
alreadyTerminated = true;
|
||||
}
|
||||
assert(alreadyTerminated && createdGroups[2] == 3 && createdKernel.terminatedProcessCount() == 1);
|
||||
createdKernel.setSyncContext(true, 3);
|
||||
auto* afterTerminated = createdKernel.createProcess(2, createdGroups);
|
||||
assert((retiring->bytes[0x18] & 0x04) == 0 && (afterTerminated->bytes[0x16] & 0x40) != 0);
|
||||
createdKernel.terminateProcess(4, createdGroups);
|
||||
createdKernel.clearTerminatedProcesses();
|
||||
assert(createdKernel.processAt(3) == nullptr && createdKernel.allocationSizeAt(3) == 0);
|
||||
assert(createdKernel.processNameAt(3) == nullptr && createdKernel.terminatedProcessCount() == 0);
|
||||
auto* recycled = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(3) == recycled && recycled->bytes[0x02] == 3);
|
||||
assert(createdKernel.processCount() == 4 && createdGroups[2] == 4);
|
||||
|
||||
auto* immediate = createdKernel.createProcess(2, createdGroups);
|
||||
immediate->bytes[0x18] |= 0x04;
|
||||
createdKernel.terminateProcess(4, createdGroups);
|
||||
assert(createdKernel.processAt(4) == nullptr && createdKernel.processCount() == 4);
|
||||
assert(createdKernel.terminatedProcessCount() == 0 && createdGroups[2] == 4);
|
||||
|
||||
remorse::ProcessKernel fullKernel;
|
||||
std::vector<remorse::EntityDispatchEntryBase> fullTable(1020);
|
||||
for (auto& process : fullTable) {
|
||||
fullKernel.addProcess(process);
|
||||
}
|
||||
remorse::u16 fullGroups[32]{};
|
||||
bool exhausted = false;
|
||||
try {
|
||||
fullKernel.createProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
exhausted = false;
|
||||
try {
|
||||
fullKernel.createKeyboardProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
exhausted = false;
|
||||
try {
|
||||
fullKernel.createSystemTimerProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
|
||||
remorse::ProcessKernel scheduler;
|
||||
remorse::u16 scheduledGroups[32]{};
|
||||
auto* otherGroup = scheduler.createProcess(1, scheduledGroups);
|
||||
auto* matching = scheduler.createProcess(2, scheduledGroups);
|
||||
auto* syncingProcess = scheduler.createProcess(2, scheduledGroups);
|
||||
auto* specialGroup = scheduler.createProcess(30, scheduledGroups);
|
||||
syncingProcess->bytes[0x16] = 0x40;
|
||||
std::vector<remorse::u16> ran;
|
||||
auto recordRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& ids = *static_cast<std::vector<remorse::u16>*>(context);
|
||||
ids.push_back(static_cast<remorse::u16>(process.bytes[0x02] | process.bytes[0x03] << 8));
|
||||
};
|
||||
scheduler.scanRunnableProcesses(2, recordRun, &ran);
|
||||
assert((ran == std::vector<remorse::u16>{1, 3}));
|
||||
assert(syncingProcess->bytes[0x16] == 0 && otherGroup->bytes[0x16] == 0);
|
||||
ran.clear();
|
||||
matching->bytes[0x16] = 1;
|
||||
scheduler.scanRunnableProcesses(2, recordRun, &ran);
|
||||
assert((ran == std::vector<remorse::u16>{2, 3}));
|
||||
assert(specialGroup->bytes[0x08] == 30);
|
||||
|
||||
remorse::ProcessKernel spawningKernel;
|
||||
remorse::u16 spawningGroups[32]{};
|
||||
spawningKernel.createProcess(1, spawningGroups);
|
||||
auto* spawningProcess = spawningKernel.createProcess(2, spawningGroups);
|
||||
spawningProcess->bytes[0x18] |= 0x02;
|
||||
struct SpawnContext {
|
||||
remorse::ProcessKernel* kernel;
|
||||
remorse::u16 (*groups)[32];
|
||||
remorse::EntityDispatchEntryBase* spawned = nullptr;
|
||||
int runs = 0;
|
||||
} spawnContext{&spawningKernel, &spawningGroups};
|
||||
auto spawnRun = [](remorse::EntityDispatchEntryBase&, void* context) {
|
||||
auto& state = *static_cast<SpawnContext*>(context);
|
||||
++state.runs;
|
||||
if (state.spawned == nullptr) {
|
||||
state.spawned = state.kernel->createProcess(2, *state.groups);
|
||||
}
|
||||
};
|
||||
spawningKernel.scanRunnableProcesses(2, spawnRun, &spawnContext);
|
||||
assert(spawnContext.runs == 1 && spawnContext.spawned == spawningKernel.processAt(2));
|
||||
assert(spawningProcess->bytes[0x18] == 0x07 && spawnContext.spawned->bytes[0x16] == 0);
|
||||
|
||||
remorse::ProcessKernel retiringKernel;
|
||||
remorse::u16 retiringGroups[32]{};
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
retiringKernel.createProcess(1, retiringGroups);
|
||||
}
|
||||
retiringKernel.createProcess(2, retiringGroups);
|
||||
struct RetireContext {
|
||||
remorse::ProcessKernel* kernel;
|
||||
remorse::u16 (*groups)[32];
|
||||
} retireContext{&retiringKernel, &retiringGroups};
|
||||
auto retireRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& state = *static_cast<RetireContext*>(context);
|
||||
state.kernel->terminateProcess(static_cast<remorse::u16>(process.bytes[0x02]), *state.groups);
|
||||
};
|
||||
retiringKernel.scanRunnableProcesses(2, retireRun, &retireContext);
|
||||
assert(retiringKernel.processAt(3) == nullptr && retiringKernel.terminatedProcessCount() == 0);
|
||||
assert(retiringKernel.processCount() == 3 && retiringGroups[2] == 0);
|
||||
|
||||
remorse::ProcessKernel sleepingKernel;
|
||||
remorse::u16 sleepingGroups[32]{};
|
||||
auto* sleeper = sleepingKernel.createProcess(2, sleepingGroups);
|
||||
remorse::EntityDispatchEntry::sleep(*sleeper, 100, 60);
|
||||
ran.clear();
|
||||
sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 160);
|
||||
assert(ran.empty() && sleeper->bytes[0x19] == 0x10);
|
||||
sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 161);
|
||||
assert((ran == std::vector<remorse::u16>{0}));
|
||||
assert(sleeper->bytes[0x19] == 0);
|
||||
for (remorse::u16 offset = 0x0a; offset < 0x12; ++offset) {
|
||||
assert(sleeper->bytes[offset] == 0);
|
||||
}
|
||||
|
||||
remorse::ProcessKernel standKernel;
|
||||
remorse::u16 standGroups[32]{};
|
||||
standKernel.createProcess(2, standGroups);
|
||||
assert(!standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
|
||||
auto* standEntry = standKernel.createStandProcess(2, 0x1234, standGroups);
|
||||
auto* standing = &standEntry->base;
|
||||
assert(standKernel.processAt(1) == standing && standKernel.allocationSizeAt(1) == 0x42);
|
||||
assert(std::strcmp(standKernel.processNameAt(1), "Stand") == 0 && standGroups[2] == 2);
|
||||
assert(standing->bytes[0] == 0x0f && standing->bytes[1] == 0x1f);
|
||||
assert(standing->bytes[0x04] == 0x34 && standing->bytes[0x05] == 0x12);
|
||||
assert(standing->bytes[0x06] == 0x58 && standing->bytes[0x07] == 0x02);
|
||||
assert(standing->bytes[0x17] == 0x03 && standEntry->extra[0] == 0x01 && standEntry->extra[1] == 0x01);
|
||||
assert(standEntry->extra[0x0e] == 0x34 && standEntry->extra[0x0f] == 0x12);
|
||||
assert(standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
|
||||
bool itemTeardownRejected = false;
|
||||
try {
|
||||
standKernel.terminateProcess(1, standGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
itemTeardownRejected = true;
|
||||
}
|
||||
assert(itemTeardownRejected && standGroups[2] == 2 && standKernel.processAt(1) == standing);
|
||||
struct StandContext {
|
||||
remorse::u32 tick;
|
||||
bool visible;
|
||||
remorse::u16 activity = 0;
|
||||
bool currentActivity = false;
|
||||
bool canSee = false;
|
||||
remorse::u16 startedNpc = 0;
|
||||
remorse::u16 startedActivity = 0;
|
||||
int starts = 0;
|
||||
int runs = 0;
|
||||
remorse::StandProcessEntry* entry = nullptr;
|
||||
remorse::NpcBehaviorServices* services = nullptr;
|
||||
} standContext{99, false};
|
||||
remorse::NpcBehaviorServices standServices{
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->visible;
|
||||
},
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->activity;
|
||||
},
|
||||
[](remorse::u16 npcNumber, remorse::u16 activity, void* context) {
|
||||
assert(npcNumber == 0x1234 && activity == 0x71);
|
||||
return static_cast<StandContext*>(context)->currentActivity;
|
||||
},
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->canSee;
|
||||
},
|
||||
[](remorse::u16 npcNumber, remorse::u16 activity, void* context) {
|
||||
auto& state = *static_cast<StandContext*>(context);
|
||||
state.startedNpc = npcNumber;
|
||||
state.startedActivity = activity;
|
||||
++state.starts;
|
||||
},
|
||||
&standContext
|
||||
};
|
||||
standContext.entry = standEntry;
|
||||
standContext.services = &standServices;
|
||||
auto standRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& state = *static_cast<StandContext*>(context);
|
||||
if (process.bytes[0] != 0x0f || process.bytes[1] != 0x1f) {
|
||||
return;
|
||||
}
|
||||
++state.runs;
|
||||
remorse::StandProcess::run(*state.entry, *state.services, state.tick);
|
||||
};
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10);
|
||||
assert(standing->bytes[0x0a] == 99 && standing->bytes[0x0e] == 60);
|
||||
assert(standContext.starts == 0);
|
||||
standContext.tick = 159;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10);
|
||||
standContext.tick = 160;
|
||||
standContext.visible = true;
|
||||
standContext.activity = 0x71;
|
||||
standContext.canSee = true;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 2 && standing->bytes[0x19] == 0 && standing->bytes[0x0e] == 0);
|
||||
assert(standContext.starts == 1 && standContext.startedNpc == 0x1234 && standContext.startedActivity == 0x71);
|
||||
standContext.tick = 161;
|
||||
standContext.currentActivity = true;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 3 && standContext.starts == 1 && standing->bytes[0x0e] == 60);
|
||||
|
||||
remorse::ProcessKernel itemKernel;
|
||||
remorse::u16 itemGroups[32]{};
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
itemKernel.createProcess(1, itemGroups);
|
||||
}
|
||||
auto* firstStand = itemKernel.createStandProcess(2, 0x1234, itemGroups);
|
||||
auto* secondStand = itemKernel.createStandProcess(2, 0x1234, itemGroups);
|
||||
auto* otherStand = itemKernel.createStandProcess(2, 0x1235, itemGroups);
|
||||
assert(itemKernel.itemHasProcess(0x1234) && itemKernel.itemHasProcess(0x1235));
|
||||
itemKernel.terminateProcess(3, itemGroups);
|
||||
assert(itemKernel.itemHasProcess(0x1234) && itemKernel.processAt(3) == &firstStand->base);
|
||||
itemKernel.clearTerminatedProcesses();
|
||||
assert(itemKernel.processAt(3) == nullptr && itemKernel.itemHasProcess(0x1234));
|
||||
secondStand->base.bytes[0x18] |= 0x04;
|
||||
itemKernel.terminateProcess(4, itemGroups);
|
||||
assert(itemKernel.processAt(4) == nullptr && !itemKernel.itemHasProcess(0x1234));
|
||||
assert(itemKernel.itemHasProcess(0x1235) && itemKernel.processAt(5) == &otherStand->base);
|
||||
assert(itemGroups[2] == 1 && itemKernel.processCount() == 4);
|
||||
|
||||
remorse::SystemTimerProcessEntry systemTimer{};
|
||||
systemTimer.extra[0x0e] = 0xff;
|
||||
systemTimer.extra[0x0f] = 0xff;
|
||||
assert(remorse::SystemTimerProcess::tick(systemTimer) == 0xffff);
|
||||
remorse::SystemTimerProcess::increment(systemTimer);
|
||||
assert(remorse::SystemTimerProcess::tick(systemTimer) == 0x10000);
|
||||
assert(systemTimer.extra[0x0e] == 0 && systemTimer.extra[0x0f] == 0);
|
||||
assert(systemTimer.extra[0x10] == 1 && systemTimer.extra[0x11] == 0);
|
||||
|
||||
remorse::ProcessKernel timerKernel;
|
||||
remorse::u16 timerGroups[32]{};
|
||||
bool missingTimerRejected = false;
|
||||
try {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
} catch (const std::logic_error&) {
|
||||
missingTimerRejected = true;
|
||||
}
|
||||
assert(missingTimerRejected);
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
timerKernel.createProcess(1, timerGroups);
|
||||
}
|
||||
auto* registeredTimer = timerKernel.createSystemTimerProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(3) == ®isteredTimer->base);
|
||||
assert(timerKernel.allocationSizeAt(3) == 0x4a && timerGroups[1] == 4);
|
||||
assert(std::strcmp(timerKernel.processNameAt(3), "SystemTimer") == 0);
|
||||
assert(registeredTimer->base.bytes[0x16] == 3 && registeredTimer->base.bytes[0x17] == 0x27);
|
||||
assert(registeredTimer->base.bytes[0x18] == 1 && registeredTimer->extra[0] == 2);
|
||||
assert(registeredTimer->extra[4] == 0x3c && timerKernel.systemTimerTick() == 0);
|
||||
registeredTimer->base.bytes[0x17] &= static_cast<remorse::u8>(~0x04);
|
||||
bool registrationRejected = false;
|
||||
try {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
} catch (const std::logic_error&) {
|
||||
registrationRejected = true;
|
||||
}
|
||||
assert(registrationRejected && timerKernel.systemTimerTick() == 0);
|
||||
registeredTimer->base.bytes[0x17] |= 0x04;
|
||||
bool duplicateTimerRejected = false;
|
||||
try {
|
||||
timerKernel.createSystemTimerProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateTimerRejected = true;
|
||||
}
|
||||
assert(duplicateTimerRejected && timerGroups[1] == 4);
|
||||
bool timerTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(3, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
timerTeardownRejected = true;
|
||||
}
|
||||
assert(timerTeardownRejected && timerGroups[1] == 4);
|
||||
auto* timedStand = timerKernel.createStandProcess(1, 7, timerGroups);
|
||||
remorse::EntityDispatchEntry::sleep(timedStand->base, timerKernel.systemTimerTick(), 60);
|
||||
for (int tick = 0; tick < 60; ++tick) {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
}
|
||||
ran.clear();
|
||||
timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick());
|
||||
assert(ran.size() == 3 && timedStand->base.bytes[0x19] == 0x10);
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
ran.clear();
|
||||
timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick());
|
||||
assert((ran == std::vector<remorse::u16>{0, 1, 2, 4}));
|
||||
assert(timedStand->base.bytes[0x19] == 0 && timerKernel.systemTimerTick() == 61);
|
||||
|
||||
auto* keyboard = timerKernel.createKeyboardProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(5) == &keyboard->base && timerKernel.allocationSizeAt(5) == 0x36);
|
||||
assert(std::strcmp(timerKernel.processNameAt(5), "KeyboardProcess") == 0);
|
||||
assert(keyboard->base.bytes[0x16] == 3 && keyboard->base.bytes[0x17] == 1);
|
||||
assert(keyboard->base.bytes[0x18] == 0x81 && keyboard->base.bytes[0x19] == 1);
|
||||
assert(keyboard->extra[0] == 0 && keyboard->extra[3] == 0 && timerGroups[1] == 6);
|
||||
bool duplicateKeyboardRejected = false;
|
||||
try {
|
||||
timerKernel.createKeyboardProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateKeyboardRejected = true;
|
||||
}
|
||||
assert(duplicateKeyboardRejected && timerGroups[1] == 6);
|
||||
bool keyboardTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(5, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
keyboardTeardownRejected = true;
|
||||
}
|
||||
assert(keyboardTeardownRejected && timerGroups[1] == 6);
|
||||
|
||||
auto* keyDaemon = timerKernel.createKeyDaemonProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(6) == &keyDaemon->base && timerKernel.allocationSizeAt(6) == 0x40);
|
||||
assert(std::strcmp(timerKernel.processNameAt(6), "KeyDaemon") == 0);
|
||||
assert(keyDaemon->base.bytes[0x16] == 3 && keyDaemon->base.bytes[0x17] == 0x27);
|
||||
assert(keyDaemon->extra[0] == 2 && keyDaemon->extra[4] == 0x2d && timerGroups[1] == 7);
|
||||
bool duplicateDaemonRejected = false;
|
||||
try {
|
||||
timerKernel.createKeyDaemonProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateDaemonRejected = true;
|
||||
}
|
||||
assert(duplicateDaemonRejected && timerGroups[1] == 7);
|
||||
bool daemonTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(6, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
daemonTeardownRejected = true;
|
||||
}
|
||||
assert(daemonTeardownRejected && timerGroups[1] == 7);
|
||||
|
||||
remorse::KeyEvent keyboardEvent{0x41, 0x1e, 1, 2, 3, 1, 4, 5};
|
||||
const remorse::KeyEvent lastEvent{0x42, 0x30, 6, 7, 8, 9, 10, 11};
|
||||
keyboard->extra[0] = 0x31;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x11, 0, keyboardEvent, lastEvent));
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 1, keyboardEvent, lastEvent));
|
||||
assert(keyboardEvent.character == 0x41 && keyboard->extra[0] == 0x31);
|
||||
keyboardEvent.field8 = 0;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
keyboardEvent.field8 = 1;
|
||||
keyboardEvent.character = 0;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
keyboardEvent.character = 0x41;
|
||||
assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0);
|
||||
assert(keyboard->extra[0] == 0x21);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,98 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/runtime.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#ifdef _DEBUG
|
||||
#include <crtdbg.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (argc == 2 && std::strcmp(argv[1], "--crash-probe") == 0) {
|
||||
remorse::installCrashDiagnostics();
|
||||
try {
|
||||
throw std::runtime_error("diagnostic probe");
|
||||
} catch (...) {
|
||||
std::terminate();
|
||||
}
|
||||
}
|
||||
#ifdef _DEBUG
|
||||
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
|
||||
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
|
||||
#endif
|
||||
remorse::installCrashDiagnostics();
|
||||
assert((GetErrorMode() & SEM_NOGPFAULTERRORBOX) != 0);
|
||||
#ifdef _DEBUG
|
||||
assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0);
|
||||
assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_DEBUG) != 0);
|
||||
assert((_CrtSetReportMode(_CRT_ERROR, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0);
|
||||
#endif
|
||||
|
||||
wchar_t executable[MAX_PATH]{};
|
||||
if (GetModuleFileNameW(nullptr, executable, MAX_PATH) == 0) {
|
||||
return 1;
|
||||
}
|
||||
std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" --crash-probe";
|
||||
SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
||||
HANDLE readPipe = nullptr;
|
||||
HANDLE writePipe = nullptr;
|
||||
if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) {
|
||||
return 1;
|
||||
}
|
||||
if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) {
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(writePipe);
|
||||
return 1;
|
||||
}
|
||||
STARTUPINFOW startup{};
|
||||
startup.cb = sizeof(startup);
|
||||
startup.dwFlags = STARTF_USESTDHANDLES;
|
||||
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
|
||||
startup.hStdOutput = writePipe;
|
||||
startup.hStdError = writePipe;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW,
|
||||
nullptr, nullptr, &startup, &child)) {
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(writePipe);
|
||||
return 1;
|
||||
}
|
||||
CloseHandle(writePipe);
|
||||
const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000);
|
||||
if (waitResult == WAIT_TIMEOUT) {
|
||||
TerminateProcess(child.hProcess, 2);
|
||||
WaitForSingleObject(child.hProcess, INFINITE);
|
||||
}
|
||||
char buffer[512];
|
||||
DWORD count = 0;
|
||||
std::string crashOutput;
|
||||
while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) {
|
||||
crashOutput.append(buffer, count);
|
||||
}
|
||||
DWORD exitCode = 0;
|
||||
const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode);
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(child.hThread);
|
||||
CloseHandle(child.hProcess);
|
||||
if (!gotExitCode || waitResult != WAIT_OBJECT_0 || exitCode != 1 ||
|
||||
crashOutput.find("Unhandled C++ exception: diagnostic probe") == std::string::npos) {
|
||||
std::fprintf(stderr, "Crash probe wait=%lu exit=0x%08lX output=%s\n",
|
||||
waitResult, exitCode, crashOutput.c_str());
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
assert(root.has_value());
|
||||
assert(root->hasExecutable);
|
||||
|
|
|
|||
54
rebuild/remorse/tests/isometric_controls_tests.cpp
Normal file
54
rebuild/remorse/tests/isometric_controls_tests.cpp
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
|
||||
#include <cassert>
|
||||
|
||||
int main()
|
||||
{
|
||||
assert(remorse::controllerWalkRequested(0));
|
||||
assert(!remorse::controllerWalkRequested(0x01));
|
||||
assert(!remorse::controllerWalkRequested(0x02));
|
||||
assert(!remorse::controllerWalkRequested(0x40));
|
||||
assert(remorse::controllerWalkRequested(0x41));
|
||||
assert(remorse::controllerWalkRequested(0x42));
|
||||
constexpr remorse::s32 originX = 1024;
|
||||
constexpr remorse::s32 originY = 2048;
|
||||
const remorse::ScreenPoint origin = remorse::projectToScreen({originX, originY, 0});
|
||||
|
||||
const auto east = remorse::worldPositionAtScreenOffset(originX, originY, 1.0, 0.0);
|
||||
const remorse::ScreenPoint eastProjection = remorse::projectToScreen({
|
||||
static_cast<remorse::s32>(east.x), static_cast<remorse::s32>(east.y), 0});
|
||||
assert(eastProjection.x - origin.x == 1);
|
||||
assert(eastProjection.y - origin.y == 0);
|
||||
|
||||
const auto north = remorse::worldPositionAtScreenOffset(originX, originY, 0.0, -1.0);
|
||||
const remorse::ScreenPoint northProjection = remorse::projectToScreen({
|
||||
static_cast<remorse::s32>(north.x), static_cast<remorse::s32>(north.y), 0});
|
||||
assert(northProjection.x - origin.x == 0);
|
||||
assert(northProjection.y - origin.y == -1);
|
||||
|
||||
const auto west = remorse::worldPositionAtScreenOffset(originX, originY, -1.0, 0.0);
|
||||
const remorse::ScreenPoint westProjection = remorse::projectToScreen({
|
||||
static_cast<remorse::s32>(west.x), static_cast<remorse::s32>(west.y), 0});
|
||||
assert(westProjection.x - origin.x == -1);
|
||||
assert(westProjection.y - origin.y == 0);
|
||||
|
||||
const auto south = remorse::worldPositionAtScreenOffset(originX, originY, 0.0, 1.0);
|
||||
const remorse::ScreenPoint southProjection = remorse::projectToScreen({
|
||||
static_cast<remorse::s32>(south.x), static_cast<remorse::s32>(south.y), 0});
|
||||
assert(southProjection.x - origin.x == 0);
|
||||
assert(southProjection.y - origin.y == 1);
|
||||
remorse::AnimationFrameMetadata forwardFrame{};
|
||||
forwardFrame.bytes[4] = 6;
|
||||
const auto forward = remorse::hostMovementStep(forwardFrame, 6, false);
|
||||
assert(forward && forward->x > 0 && forward->y > 0);
|
||||
remorse::AnimationFrameMetadata reverseFrame{};
|
||||
reverseFrame.bytes[4] = 0xfe;
|
||||
reverseFrame.bytes[5] = 3;
|
||||
const auto authoredReverse = remorse::decodeAnimationDisplacement(reverseFrame, 6, false);
|
||||
const auto hostReverse = remorse::hostMovementStep(reverseFrame, 6, false);
|
||||
assert(authoredReverse && authoredReverse->x < 0 && authoredReverse->y < 0);
|
||||
assert(hostReverse && hostReverse->x == 0 && hostReverse->y == 0);
|
||||
assert(hostReverse->z == authoredReverse->z && hostReverse->onGround == authoredReverse->onGround);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <filesystem>
|
||||
|
||||
|
|
@ -21,5 +23,33 @@ int main()
|
|||
assert(!image->pixels.empty());
|
||||
assert(image->decodedItemCount > 0);
|
||||
assert(image->paintedItemCount > 0);
|
||||
|
||||
const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
assert(fixedPath.has_value());
|
||||
const auto archive = remorse::loadFixedMapArchive(*fixedPath);
|
||||
assert(archive.has_value());
|
||||
const auto fixedMap = remorse::loadFixedMap(*archive, options.mapIndex);
|
||||
assert(fixedMap.has_value());
|
||||
remorse::s32 minX = fixedMap->entries.front().x;
|
||||
remorse::s32 minY = fixedMap->entries.front().y;
|
||||
remorse::s32 maxX = minX;
|
||||
remorse::s32 maxY = minY;
|
||||
for (const remorse::FixedMapEntry& entry : fixedMap->entries) {
|
||||
minX = std::min(minX, static_cast<remorse::s32>(entry.x));
|
||||
minY = std::min(minY, static_cast<remorse::s32>(entry.y));
|
||||
maxX = std::max(maxX, static_cast<remorse::s32>(entry.x));
|
||||
maxY = std::max(maxY, static_cast<remorse::s32>(entry.y));
|
||||
}
|
||||
options.maxWidth = 1280;
|
||||
options.maxHeight = 760;
|
||||
options.viewCenter = remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0};
|
||||
const auto centeredImage = remorse::renderMapPreview(*root, options);
|
||||
assert(centeredImage.has_value());
|
||||
assert(centeredImage->paintedItemCount > 0);
|
||||
assert(centeredImage->width == options.maxWidth);
|
||||
assert(centeredImage->height == options.maxHeight);
|
||||
const remorse::ScreenPoint center = remorse::projectToScreen(*options.viewCenter);
|
||||
assert(centeredImage->sourceLeft == center.x - static_cast<remorse::s32>(options.maxWidth / 2));
|
||||
assert(centeredImage->sourceTop == center.y - static_cast<remorse::s32>(options.maxHeight / 2));
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
70
rebuild/remorse/tests/map_sorter_tests.cpp
Normal file
70
rebuild/remorse/tests/map_sorter_tests.cpp
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
#include "remorse/detail/map_sorter.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
int main()
|
||||
{
|
||||
remorse::detail::RenderSortItem elevated;
|
||||
elevated.left = 0;
|
||||
elevated.top = 0;
|
||||
elevated.right = 64;
|
||||
elevated.bottom = 64;
|
||||
elevated.x = 0;
|
||||
elevated.xLeft = -32;
|
||||
elevated.y = 0;
|
||||
elevated.yFar = -32;
|
||||
elevated.z = 32;
|
||||
elevated.zTop = 48;
|
||||
elevated.sxLeft = -100;
|
||||
elevated.sxRight = 100;
|
||||
elevated.sxTop = -100;
|
||||
elevated.syTop = -100;
|
||||
elevated.sxBottom = 100;
|
||||
elevated.syBottom = 100;
|
||||
elevated.shape = 2;
|
||||
|
||||
remorse::detail::RenderSortItem ground;
|
||||
ground.left = 0;
|
||||
ground.top = 0;
|
||||
ground.right = 64;
|
||||
ground.bottom = 64;
|
||||
ground.x = 100;
|
||||
ground.xLeft = 68;
|
||||
ground.y = 100;
|
||||
ground.yFar = 68;
|
||||
ground.z = 0;
|
||||
ground.zTop = 16;
|
||||
ground.sxLeft = -100;
|
||||
ground.sxRight = 100;
|
||||
ground.sxTop = -100;
|
||||
ground.syTop = -100;
|
||||
ground.sxBottom = 100;
|
||||
ground.syBottom = 100;
|
||||
ground.shape = 1;
|
||||
|
||||
const std::vector<remorse::detail::RenderSortItem> items{elevated, ground};
|
||||
const std::vector<std::size_t> order = remorse::detail::resolveRenderOrder(items);
|
||||
assert(order.size() == 2);
|
||||
assert(order[0] == 1);
|
||||
assert(order[1] == 0);
|
||||
|
||||
remorse::detail::RenderSortItem animatedFlat = elevated;
|
||||
animatedFlat.x = 64;
|
||||
animatedFlat.xLeft = 64;
|
||||
animatedFlat.y = 64;
|
||||
animatedFlat.yFar = 64;
|
||||
animatedFlat.z = 0;
|
||||
animatedFlat.zTop = 0;
|
||||
animatedFlat.flat = true;
|
||||
animatedFlat.animated = true;
|
||||
|
||||
remorse::detail::RenderSortItem staticFlat = animatedFlat;
|
||||
staticFlat.animated = false;
|
||||
const std::vector<remorse::detail::RenderSortItem> flatItems{animatedFlat, staticFlat};
|
||||
const std::vector<std::size_t> flatOrder = remorse::detail::resolveRenderOrder(flatItems);
|
||||
assert(flatOrder.size() == 2);
|
||||
assert(flatOrder[0] == 1);
|
||||
assert(flatOrder[1] == 0);
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue