diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e74e26..0ddd74c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,39 @@ -cmake_minimum_required(VERSION 3.20) +cmake_minimum_required(VERSION 4.0) -project(stonehearth_like_sim VERSION 0.1.0 LANGUAGES CXX) +project(stonehearth_like_sim VERSION 0.1.0 LANGUAGES C CXX) + +if(NOT WIN32) + message(FATAL_ERROR "Stonehearth-like Simulation Engine requires a Windows target.") +endif() + +include(CTest) +if(BUILD_TESTING AND (NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)) + message(FATAL_ERROR "The reflection test suites need GCC 16 or later. Set BUILD_TESTING=OFF to build the game alone.") +endif() + +include(FetchContent) +FetchContent_Declare(void_library + GIT_REPOSITORY https://git.faumaray.com/Void/Library + GIT_TAG 7b0fea6095f603f9e1904f66dfdc7752f4be4792 + SYSTEM + EXCLUDE_FROM_ALL +) + +function(add_void_library) + set(BUILD_SHARED_LIBS OFF) + set(VOID_ENABLE_TESTING OFF) + set(VOID_ENABLE_BENCHMARKS OFF) + set(VOID_ENABLED_MODULES Binary Core) + if(BUILD_TESTING) + list(APPEND VOID_ENABLED_MODULES Testing) + endif() + FetchContent_MakeAvailable(void_library) +endfunction() +add_void_library() + +if(BUILD_TESTING AND NOT VOID_HAS_CXX26_REFLECTION) + message(FATAL_ERROR "The reflection test suites need working C++26 reflection support.") +endif() find_package(Threads REQUIRED) @@ -17,7 +50,10 @@ target_include_directories(settlement_core ) target_compile_features(settlement_core PUBLIC cxx_std_20) -target_link_libraries(settlement_core PUBLIC Threads::Threads) +target_link_libraries(settlement_core + PUBLIC Threads::Threads + PRIVATE Void::Binary Void::Core +) if(MSVC) target_compile_options(settlement_core PRIVATE /W4 /permissive-) @@ -34,23 +70,31 @@ target_link_libraries(settlement_sim PRIVATE settlement_core) add_executable(settlement_colony_benchmark benchmarks/colony.cpp) target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core) -if(WIN32) - enable_language(RC) - add_executable(settlement_viewer WIN32 - app/d3d_scene_win32.cpp - app/viewer_win32.cpp - app/lan_session_win32.cpp - app/house_icons.rc - ) - target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi - d3d11 d3dcompiler) - if(NOT MSVC) - target_link_options(settlement_viewer PRIVATE -municode) - target_compile_options(settlement_viewer PRIVATE - $<$:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>) - else() - target_compile_options(settlement_viewer PRIVATE $<$:/W4;/permissive->) - endif() +add_library(settlement_lan STATIC + app/lan_session_win32.cpp + app/lan_wire.cpp +) +target_include_directories(settlement_lan PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app) +target_link_libraries(settlement_lan + PUBLIC settlement_core + PRIVATE Void::Binary ws2_32 bcrypt iphlpapi +) + +enable_language(RC) +add_executable(settlement_viewer WIN32 + app/d3d_scene_win32.cpp + app/viewer_win32.cpp + app/house_icons.rc +) +target_link_libraries(settlement_viewer PRIVATE settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler) +if(MSVC) + target_compile_options(settlement_lan PRIVATE /W4 /permissive-) + target_compile_options(settlement_viewer PRIVATE $<$:/W4;/permissive->) +else() + target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) + target_link_options(settlement_viewer PRIVATE -municode) + target_compile_options(settlement_viewer PRIVATE + $<$:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>) endif() if(MSVC) @@ -59,22 +103,12 @@ else() target_compile_options(settlement_sim PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) endif() -include(CTest) if(BUILD_TESTING) - if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) - message(FATAL_ERROR "The reflection test suites need GCC 16 or later. Set BUILD_TESTING=OFF to build the game alone.") - endif() - add_executable(settlement_core_tests - tests/core_tests.cpp - ) - target_compile_options(settlement_core_tests PRIVATE -std=c++26 -freflection) - target_link_libraries(settlement_core_tests PRIVATE settlement_core) + add_executable(settlement_core_tests tests/core_tests.cpp tests/test_main.cpp) + target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing) add_test(NAME settlement_core_tests COMMAND settlement_core_tests) - if(WIN32) - add_executable(settlement_lan_tests tests/lan_tests.cpp app/lan_session_win32.cpp) - target_compile_options(settlement_lan_tests PRIVATE -std=c++26 -freflection) - target_include_directories(settlement_lan_tests PRIVATE app) - target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi) - add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests) - endif() + + add_executable(settlement_lan_tests tests/lan_tests.cpp tests/test_main.cpp) + target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing) + add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests) endif() diff --git a/README.md b/README.md index 344f8e8..c5eebc6 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,9 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tools\render-svg-to-pn ## Сборка Windows на MSYS2 UCRT64 -Требуется 64-битная Windows. Скрипт установки разворачивает MSYS2 в `.tools/toolchain/msys64`, проверяет SHA-256 архива и устанавливает GCC 16, CMake и Ninja через UCRT64. Если MSYS2 уже установлен, передайте его каталог обоим скриптам через `-Msys2Root` или задайте `SETTLEMENT_MSYS2_ROOT`. +Требуется 64-битная Windows. Скрипт установки разворачивает MSYS2 в `.tools/toolchain/msys64`, проверяет SHA-256 архива и устанавливает GCC 16 или новее, CMake 4.0 или новее, Ninja, Git и `windres`. Если MSYS2 уже установлен, передайте его каталог обоим скриптам через `-Msys2Root` или задайте `SETTLEMENT_MSYS2_ROOT`. + +Для установки MSYS2 рекомендуется короткий путь из символов ASCII без пробелов. [Рекомендации MSYS2](https://www.msys2.org/docs/installer/#what-are-the-installation-folder-recommendations) ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1 @@ -53,7 +55,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Сборка запускает CTest и помещает проверенные исполняемые файлы и библиотеки GCC в `build/`. Просмотрщик запускается из `build/settlement_viewer.exe`. -Тесты используют C++26 и `-freflection`. `Void::Testing::Suite` находит методы с возвращаемым типом `Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры на другом компиляторе через CMake есть `-DBUILD_TESTING=OFF`. +При настройке CMake скачивает Void Library через Git и использует коммит `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. Для сборки без доступа к репозиторию передайте путь к заранее подготовленной копии этого коммита. [Репозиторий Void Library](https://git.faumaray.com/Void/Library) + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 -VoidLibrarySource 'C:\sources\Void Library' +``` + +При прямом вызове CMake задайте `-DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH=<путь>`. Для возврата к загрузке через Git очистите эту переменную CMake. Скрипт `build.ps1` делает это автоматически при запуске без `-VoidLibrarySource`. + +Void Library требует поддержки C++26. Тесты ядра и LAN используют рефлексию C++26. `Void::Testing::Suite` регистрирует методы без аргументов с возвращаемым типом `Void::Testing::Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры без тестов задайте `-DBUILD_TESTING=OFF` при прямом вызове CMake. ## Структура diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 103aba7..5b8f7b3 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -5,14 +5,14 @@ #include #include "lan_session.hpp" +#include "lan_wire.hpp" #include #include -#include #include #include #include -#include +#include #include #include #include @@ -24,11 +24,10 @@ namespace { using Clock = std::chrono::steady_clock; using namespace std::chrono_literals; -constexpr std::uint32_t protocol_version = 11; -constexpr std::size_t frame_limit = 4 * 1024 * 1024; +using lan_wire::guest_player; +using lan_wire::Message; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; -enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping }; struct Socket { SOCKET handle = INVALID_SOCKET; @@ -64,31 +63,6 @@ void tune_stream(SOCKET socket) { setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&enabled), sizeof(enabled)); } -void append_number(std::string& bytes, std::uint64_t value, unsigned length) { - for (unsigned i = 0; i < length; ++i) { - bytes.push_back(std::bit_cast(static_cast(value))); - value >>= 8U; - } -} - -std::uint64_t number(std::string_view bytes) noexcept { - std::uint64_t value = 0; - for (std::size_t i = 0; i < bytes.size(); ++i) { - value |= static_cast(static_cast(bytes[i])) << (8U * i); - } - return value; -} - -std::string frame(Message message, std::string_view payload = {}) { - if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play."); - std::string bytes; - bytes.reserve(5 + payload.size()); - append_number(bytes, 1 + payload.size(), 4); - bytes.push_back(static_cast(message)); - bytes.append(payload); - return bytes; -} - struct Channel { Socket socket; std::string input; @@ -107,10 +81,10 @@ struct Channel { output.erase(0, sent); sent = 0; } - if (output.size() + payload.size() + 5 > frame_limit + 1024) { + if (output.size() + payload.size() + lan_wire::frame_header_size > lan_wire::frame_limit + 1024) { throw std::runtime_error("The peer is not receiving data fast enough."); } - output += frame(message, payload); + lan_wire::append_frame(output, message, payload); } void flush() { @@ -141,18 +115,12 @@ struct Channel { if (count == 0) throw std::runtime_error("Connection closed."); last_received = Clock::now(); input.append(bytes.data(), static_cast(count)); - std::size_t cursor = 0; - while (input.size() - cursor >= 4) { - const std::string_view remaining(input.data() + cursor, input.size() - cursor); - const auto length = number(remaining.substr(0, 4)); - if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size."); - const auto end = 4 + static_cast(length); - if (remaining.size() < end) break; - on_message(static_cast(static_cast(remaining[4])), - remaining.substr(5, static_cast(length - 1))); - cursor += end; + std::size_t consumed = 0; + while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) { + on_message(frame->message, frame->payload); + consumed += frame->size; } - if (cursor != 0) input.erase(0, cursor); + if (consumed != 0) input.erase(0, consumed); } } }; @@ -258,8 +226,8 @@ struct LanSession::Impl { void handle_host(World& world, Message message, std::string_view payload) { if (!authenticated) { if (reject_pending) return; - if (message != Message::Hello || payload.size() != 12 || - number(payload.substr(0, 4)) != protocol_version || number(payload.substr(4)) != key) { + const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt; + if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) { peer.queue(Message::Reject); reject_pending = true; return; @@ -269,60 +237,52 @@ struct LanSession::Impl { return; } if (message == Message::Ping && payload.empty()) return; - if (message != Message::Command || payload.size() != 34) throw std::runtime_error("Invalid guest command."); - const PlayerCommand command{2, number(payload.substr(0, 8)), - static_cast(static_cast(payload[8])), - {std::bit_cast(static_cast(number(payload.substr(9, 4)))), - std::bit_cast(static_cast(number(payload.substr(13, 4))))}, - static_cast(payload[17]), - {std::bit_cast(static_cast(number(payload.substr(18, 4)))), - std::bit_cast(static_cast(number(payload.substr(22, 4))))}, - number(payload.substr(26, 8))}; - const auto result = world.apply_command(command); - std::string reply; - append_number(reply, static_cast(result.status), 1); - append_number(reply, world.next_command_sequence(2), 8); - peer.queue(Message::Receipt, reply); + const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt; + if (!command) throw std::runtime_error("Invalid guest command."); + const auto result = world.apply_command(*command); + const auto reply = lan_wire::encode_receipt({result.status, world.next_command_sequence(guest_player)}); + peer.queue(Message::Receipt, std::string_view(reply)); } void handle_guest(std::unique_ptr& latest, Message message, std::string_view payload) { if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version."); if (message == Message::Snapshot) { - std::istringstream data(std::string(payload), std::ios::binary); + std::ispanstream data(payload); latest = World::read_save(data); if (!latest->scenario_active() || latest->width() != first_colony_map_size || latest->height() != first_colony_map_size) { throw std::runtime_error("The host sent an unsupported colony."); } - if (!authenticated) guest_sequence = latest->next_command_sequence(2); + if (!authenticated) guest_sequence = latest->next_command_sequence(guest_player); authenticated = true; notice.clear(); return; } - if (message != Message::Receipt || payload.size() != 9 || !awaiting_receipt) { + const auto receipt = message == Message::Receipt ? lan_wire::decode_receipt(payload) : std::nullopt; + if (!receipt || !awaiting_receipt) { throw std::runtime_error("Invalid message from the host."); } - const auto status = static_cast(static_cast(payload[0])); + const auto status = receipt->status; if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); if (status != CommandStatus::Accepted) { rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, awaiting_receipt->value, awaiting_receipt->destination}; } - guest_sequence = number(payload.substr(1)); + guest_sequence = receipt->next_sequence; awaiting_receipt.reset(); } void send_snapshot(const World& world, Clock::time_point now) { if (peer.pending()) return; const auto host_seq = world.next_command_sequence(1); - const auto guest_seq = world.next_command_sequence(2); + const auto guest_seq = world.next_command_sequence(guest_player); const bool changed = world.tick() != sent_tick || host_seq != sent_host_sequence || guest_seq != sent_guest_sequence; const auto elapsed = now - last_snapshot; if (last_snapshot != Clock::time_point{} && elapsed < 2s && (!changed || (elapsed < 120ms && host_seq == sent_host_sequence && guest_seq == sent_guest_sequence))) return; std::ostringstream data(std::ios::binary); world.write_save(data); - peer.queue(Message::Snapshot, data.str()); + peer.queue(Message::Snapshot, data.view()); last_snapshot = now; sent_tick = world.tick(); sent_host_sequence = host_seq; @@ -332,16 +292,9 @@ struct LanSession::Impl { void send_action() { if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return; const Action action = actions.front(); - std::string payload; - append_number(payload, guest_sequence, 8); - append_number(payload, static_cast(action.kind), 1); - append_number(payload, std::bit_cast(action.cell.x), 4); - append_number(payload, std::bit_cast(action.cell.y), 4); - append_number(payload, action.value, 1); - append_number(payload, std::bit_cast(action.destination.x), 4); - append_number(payload, std::bit_cast(action.destination.y), 4); - append_number(payload, action.resident, 8); - peer.queue(Message::Command, payload); + const auto payload = lan_wire::encode_command( + {guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident}); + peer.queue(Message::Command, std::string_view(payload)); actions.pop_front(); awaiting_receipt = action; } @@ -394,11 +347,9 @@ void LanSession::join(std::string address, std::string code, std::uint16_t port) tune_stream(socket.handle); const bool pending = connect(socket.handle, reinterpret_cast(&remote), sizeof(remote)) != 0; if (pending && WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Could not connect to the host."); - std::string identity; - append_number(identity, protocol_version, 4); - append_number(identity, key, 8); + const auto identity = lan_wire::encode_hello({lan_wire::protocol_version, key}); Channel channel(std::move(socket)); - channel.queue(Message::Hello, identity); + channel.queue(Message::Hello, std::string_view(identity)); leave(); impl_->guest = true; impl_->connecting = pending; diff --git a/app/lan_wire.cpp b/app/lan_wire.cpp new file mode 100644 index 0000000..6f29774 --- /dev/null +++ b/app/lan_wire.cpp @@ -0,0 +1,82 @@ +#include "lan_wire.hpp" + +#include +#include + +#include +#include + +namespace settlement::viewer::lan_wire { +namespace { + +template +std::array encode(Fields... fields) { + static_assert((sizeof(Fields) + ...) == Size); + std::array payload{}; + Void::Binary::Writer writer(std::as_writable_bytes(std::span{payload})); + (writer.writeLittle(fields).value(), ...); + return payload; +} + +} // namespace + +void append_frame(std::string& output, Message message, std::string_view payload) { + if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play."); + const auto length = static_cast(payload.size() + 1); + const auto header = encode(length, static_cast(message)); + output.reserve(output.size() + header.size() + payload.size()); + output.append(header.data(), header.size()); + output.append(payload); +} + +std::optional next_frame(std::string_view input) { + if (input.size() < sizeof(std::uint32_t)) return std::nullopt; + Void::Binary::Reader reader(std::as_bytes(std::span{input})); + const auto length = reader.readLittle().value(); + if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size."); + if (reader.remaining() < length) return std::nullopt; + + const auto message = static_cast(reader.readLittle().value()); + const auto payload = input.substr(reader.position(), length - 1); + return Frame{message, payload, reader.position() + payload.size()}; +} + +std::array encode_hello(Hello hello) { + return encode<12>(hello.version, hello.key); +} + +std::optional decode_hello(std::string_view payload) { + if (payload.size() != 12) return std::nullopt; + Void::Binary::Reader reader(std::as_bytes(std::span{payload})); + return Hello{reader.readLittle().value(), reader.readLittle().value()}; +} + +std::array encode_command(const PlayerCommand& command) { + return encode<34>(command.sequence, static_cast(command.kind), command.cell.x, command.cell.y, + command.value, command.destination.x, command.destination.y, command.resident); +} + +std::optional decode_command(std::string_view payload) { + if (payload.size() != 34) return std::nullopt; + Void::Binary::Reader reader(std::as_bytes(std::span{payload})); + return PlayerCommand{guest_player, + reader.readLittle().value(), + static_cast(reader.readLittle().value()), + {reader.readLittle().value(), reader.readLittle().value()}, + reader.readLittle().value(), + {reader.readLittle().value(), reader.readLittle().value()}, + reader.readLittle().value()}; +} + +std::array encode_receipt(Receipt receipt) { + return encode<9>(static_cast(receipt.status), receipt.next_sequence); +} + +std::optional decode_receipt(std::string_view payload) { + if (payload.size() != 9) return std::nullopt; + Void::Binary::Reader reader(std::as_bytes(std::span{payload})); + return Receipt{static_cast(reader.readLittle().value()), + reader.readLittle().value()}; +} + +} // namespace settlement::viewer::lan_wire diff --git a/app/lan_wire.hpp b/app/lan_wire.hpp new file mode 100644 index 0000000..fc16d2c --- /dev/null +++ b/app/lan_wire.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include + +namespace settlement::viewer::lan_wire { + +inline constexpr std::uint32_t protocol_version = 11; +inline constexpr std::uint8_t guest_player = 2; +inline constexpr std::size_t frame_limit = 4 * 1024 * 1024; +inline constexpr std::size_t frame_header_size = sizeof(std::uint32_t) + sizeof(std::uint8_t); + +enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping }; + +struct Frame { + Message message; + std::string_view payload; + std::size_t size; +}; + +struct Hello { + std::uint32_t version; + std::uint64_t key; +}; + +struct Receipt { + CommandStatus status; + std::uint64_t next_sequence; +}; + +// The payload must be backed by storage separate from output. +void append_frame(std::string& output, Message message, std::string_view payload = {}); + +// A complete frame borrows its payload from input. Invalid lengths throw even before the body arrives. +[[nodiscard]] std::optional next_frame(std::string_view input); + +[[nodiscard]] std::array encode_hello(Hello hello); +[[nodiscard]] std::optional decode_hello(std::string_view payload); + +[[nodiscard]] std::array encode_command(const PlayerCommand& command); +[[nodiscard]] std::optional decode_command(std::string_view payload); + +[[nodiscard]] std::array encode_receipt(Receipt receipt); +[[nodiscard]] std::optional decode_receipt(std::string_view payload); + +} // namespace settlement::viewer::lan_wire diff --git a/build.ps1 b/build.ps1 index 7422c22..f9ee471 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,35 +1,70 @@ param( [ValidateSet('Debug', 'Release', 'RelWithDebInfo')] [string]$Configuration = 'Release', - [string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT + [string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT, + [string]$VoidLibrarySource ) $ErrorActionPreference = 'Stop' $projectRoot = $PSScriptRoot if (-not $Msys2Root) { $Msys2Root = Join-Path $projectRoot '.tools\toolchain\msys64' } $bin = Join-Path $Msys2Root 'ucrt64\bin' -foreach ($tool in @('g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) { +foreach ($tool in @('gcc.exe', 'g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) { if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) { throw "MSYS2 UCRT64 tool missing: $tool. Run .\setup-toolchain.ps1." } } $bin = (Get-Item -LiteralPath $bin).FullName.Replace('\', '/') +$toolPaths = @($bin) +$voidSource = '' +$gitOption = @() +if ($VoidLibrarySource) { + $voidSource = (Resolve-Path -LiteralPath $VoidLibrarySource).ProviderPath.Replace('\', '/') + if (-not (Test-Path -LiteralPath (Join-Path $voidSource 'CMakeLists.txt') -PathType Leaf)) { + throw "Void Library CMakeLists.txt was not found in $voidSource." + } +} else { + $git = Join-Path $Msys2Root 'usr\bin\git.exe' + if (Test-Path -LiteralPath $git -PathType Leaf) { + $bundledGit = Get-Item -LiteralPath $git + $git = $bundledGit.FullName + $toolPaths += $bundledGit.DirectoryName + } else { + $git = (Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue).Source + } + if (-not $git) { + throw 'Git is required to fetch Void Library. Run .\setup-toolchain.ps1 or pass -VoidLibrarySource.' + } + $gitOption = @("-DGIT_EXECUTABLE:FILEPATH=$($git.Replace('\', '/'))") +} $buildRoot = Join-Path $projectRoot 'build' $buildDirectory = Join-Path $buildRoot 'msys2-ucrt64' $previousPath = $env:Path try { - $env:Path = "$bin;$previousPath" + $env:Path = ($toolPaths + $previousPath) -join ';' $version = & (Join-Path $bin 'g++.exe') -dumpfullversion - if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { - throw "MSYS2 UCRT64 GCC 16 is required. Found: $version" + if ($LASTEXITCODE -ne 0 -or $version -notmatch '^\d+\.\d+(\.\d+)?$' -or + [version]$version -lt [version]'16.0') { + throw "MSYS2 UCRT64 GCC 16 or later is required. Found: $version" + } + $cVersion = & (Join-Path $bin 'gcc.exe') -dumpfullversion + if ($LASTEXITCODE -ne 0 -or $cVersion -ne $version) { + throw "gcc.exe and g++.exe must match. Found: $cVersion and $version" + } + $cmake = Join-Path $bin 'cmake.exe' + $cmakeVersion = & $cmake --version + if ($LASTEXITCODE -ne 0 -or $cmakeVersion[0] -notmatch '^cmake version (\d+\.\d+\.\d+)' -or + [version]$Matches[1] -lt [version]'4.0') { + throw 'CMake 4.0 or later is required. Run .\setup-toolchain.ps1.' } Write-Output "Building with MSYS2 UCRT64 GCC $version" - $cmake = Join-Path $bin 'cmake.exe' $options = @('-S', $projectRoot, '-B', $buildDirectory, '-G', 'Ninja', + "-DCMAKE_C_COMPILER=$bin/gcc.exe", "-DCMAKE_CXX_COMPILER=$bin/g++.exe", "-DCMAKE_RC_COMPILER=$bin/windres.exe", "-DCMAKE_MAKE_PROGRAM=$bin/ninja.exe", - "-DCMAKE_BUILD_TYPE=$Configuration", '-DBUILD_TESTING=ON') + "-DCMAKE_BUILD_TYPE=$Configuration", '-DBUILD_TESTING=ON', + "-DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH=$voidSource") + $gitOption & $cmake @options if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $cmake --build $buildDirectory --parallel diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 217d3b2..e5ce60f 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -1,10 +1,15 @@ #include "settlement/core/world.hpp" +#include +#include +#include + #include -#include +#include #include #include #include +#include #include #include #include @@ -32,15 +37,15 @@ public: if constexpr (std::is_enum_v) { field(static_cast>(value)); } else { - using Bits = std::make_unsigned_t; - std::uint64_t bits = std::bit_cast(value); - for (std::size_t i = 0; i < sizeof(T); ++i) { - const auto byte = static_cast(bits); + std::array bytes; + Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes})); + require_save(writer.writeLittle(value).has_value(), "Could not encode a save field."); + // Preserve the stream prefix if writing stops partway through a field. + for (char byte : bytes) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; - stream_.put(std::bit_cast(byte)); + stream_.put(byte); require_save(static_cast(stream_), "Could not write the save."); - bits >>= 8; } } } @@ -62,19 +67,22 @@ public: field(bits, payload); value = static_cast(bits); } else { - std::uint64_t bits = 0; - for (std::size_t i = 0; i < sizeof(T); ++i) { + std::array bytes; + for (char& byte : bytes) { const int next = stream_.get(); require_save(next != std::char_traits::eof(), "Save is incomplete or unreadable."); - const auto byte = static_cast(next); + byte = std::char_traits::to_char_type(next); if (payload) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; - if (legacy_footer_) legacy_digest_ = (legacy_digest_ ^ byte) * 1099511628211ULL; } - bits |= static_cast(byte) << (8 * i); } - value = std::bit_cast(static_cast>(bits)); + const auto wire = std::as_bytes(std::span{bytes}); + if (payload && legacy_footer_) legacy_digest_ = Void::Hash::fnv1a64_update(legacy_digest_, wire); + Void::Binary::Reader reader(wire); + const auto decoded = reader.readLittle(); + require_save(decoded.has_value(), "Could not decode a save field."); + value = *decoded; } } @@ -95,8 +103,9 @@ public: private: std::istream& stream_; std::size_t bytes_ = 0; + // Legacy footers cover the signature and version, which are read first. bool legacy_footer_ = true; - std::uint64_t legacy_digest_ = 14695981039346656037ULL; + std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis; }; template diff --git a/setup-toolchain.ps1 b/setup-toolchain.ps1 index 42d1039..59550b8 100644 --- a/setup-toolchain.ps1 +++ b/setup-toolchain.ps1 @@ -9,15 +9,38 @@ $portableRoot = Join-Path $toolRoot 'msys64' if (-not $Msys2Root) { $Msys2Root = $portableRoot } $bash = Join-Path $Msys2Root 'usr\bin\bash.exe' $bin = Join-Path $Msys2Root 'ucrt64\bin' -$compiler = Join-Path $bin 'g++.exe' -if ((Test-Path -LiteralPath $compiler -PathType Leaf) -and - (Test-Path -LiteralPath (Join-Path $bin 'cmake.exe') -PathType Leaf) -and - (Test-Path -LiteralPath (Join-Path $bin 'ninja.exe') -PathType Leaf)) { - $version = & $compiler -dumpfullversion - if ($LASTEXITCODE -eq 0 -and $version -match '^16(\.|$)') { - Write-Output "MSYS2 UCRT64 GCC $version is ready." +$git = Join-Path $Msys2Root 'usr\bin\git.exe' + +function Get-ReadyCompilerVersion { + foreach ($tool in @('gcc.exe', 'g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) { + if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) { + return + } + } + if (-not (Test-Path -LiteralPath $git -PathType Leaf)) { return } + $version = & (Join-Path $bin 'g++.exe') -dumpfullversion + if ($LASTEXITCODE -ne 0 -or $version -notmatch '^\d+\.\d+(\.\d+)?$' -or + [version]$version -lt [version]'16.0') { + return + } + $cVersion = & (Join-Path $bin 'gcc.exe') -dumpfullversion + if ($LASTEXITCODE -ne 0 -or $cVersion -ne $version) { + return + } + $cmakeVersion = & (Join-Path $bin 'cmake.exe') --version + if ($LASTEXITCODE -ne 0 -or $cmakeVersion[0] -notmatch '^cmake version (\d+\.\d+\.\d+)' -or + [version]$Matches[1] -lt [version]'4.0') { + return + } + return $version +} + +$version = Get-ReadyCompilerVersion +if ($version) { + Write-Output "MSYS2 UCRT64 GCC $version, CMake, Ninja, and Git are ready." + return } if (-not (Test-Path -LiteralPath $bash -PathType Leaf)) { if ([IO.Path]::GetFullPath($Msys2Root) -ne [IO.Path]::GetFullPath($portableRoot)) { @@ -45,13 +68,13 @@ try { # An MSYS2 runtime upgrade can close the first shell. Start a fresh shell for the remaining packages. & $bash --login -c 'pacman -Syu --noconfirm' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - & $bash --login -c 'pacman -Syu --needed --noconfirm mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja' + & $bash --login -c 'pacman -Syu --needed --noconfirm git mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } finally { $env:MSYSTEM = $previousMsysSystem } -$version = & $compiler -dumpfullversion -if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { - throw "Expected GCC 16 in MSYS2 UCRT64. Found: $version" +$version = Get-ReadyCompilerVersion +if (-not $version) { + throw 'Expected MSYS2 UCRT64 with matching GCC 16+ compilers, windres, CMake 4+, CTest, Ninja, and Git.' } -Write-Output "MSYS2 UCRT64 GCC $version is ready." +Write-Output "MSYS2 UCRT64 GCC $version, CMake, Ninja, and Git are ready." diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index e7de8ea..af34ccf 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -1,16 +1,39 @@ -#include "testing.hpp" - #include "settlement/core/deterministic_rng.hpp" #include "settlement/core/world.hpp" +#include +#include + #include +#include #include -#include +#include #include #include +#include +#include namespace { +using namespace std::string_view_literals; +using Void::Testing::require_eq; +using Void::Testing::Test; + +// Wire bytes for an empty 5-by-5 world with seed 0x0102030405060708. +constexpr auto empty_save_v13 = + "SETTLERS" + "\x0d\0\0\0" "\x08\x07\x06\x05\x04\x03\x02\x01" "\x05\0\0\0" "\x05\0\0\0" + "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" // Tick and path counters + "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" "\0" // Job and meal counters, hunger flag + "\x01\0\0\0\0\0\0\0" "\x01\0\0\0\0\0\0\0" // Next agent and job IDs + "\x01\0\0\0\0\0\0\0" "\x01\0\0\0\0\0\0\0" // Next resource and storage IDs + "\0\0\0\0\0" "\0\0\0\0\0" "\0\0\0\0\0" "\0\0\0\0\0" "\0\0\0\0\0" // Walkable cells + "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" // Empty record counts + "\0\0\0\0" "\0\0\0\0\0\0\0\0" // Scenario flags, priority and sawmill + "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" // Player sequences + "\0\0\0\0\0\0\0\0" "\0"sv; // Command revision and staged beds flag +static_assert(empty_save_v13.size() == 183); + void require(bool condition, const char* message) { if (!condition) { throw std::runtime_error(message); @@ -33,9 +56,18 @@ std::unique_ptr save_roundtrip(const settlement::World& world return restored; } -using Void::Testing::Test; +void require_save_error(std::string_view bytes, std::string_view expected) { + std::istringstream file(std::string(bytes), std::ios::binary); + try { + static_cast(settlement::World::read_save(file)); + } catch (const std::runtime_error& error) { + require_eq(std::string_view(error.what()), expected); + return; + } + throw std::runtime_error("invalid save was accepted"); +} -struct CoreTests : Void::Testing::Suite { +struct [[= Void::Testing::name("CoreTests")]] CoreTests : Void::Testing::Suite { Test test_parallel_pathfinding_completes_the_jobs(); Test test_single_worker_configuration_is_rejected(); Test test_rng_repeats_for_same_seed(); @@ -46,6 +78,9 @@ struct CoreTests : Void::Testing::Suite { [[= Void::Testing::tag("construction")]] Test test_cabin_placement_queues_a_complete_order(); Test test_hungry_resident_reserves_and_eats_a_berry(); Test test_invalid_save_is_rejected(); + Test test_save_version_13_matches_wire_fixture(); + Test test_legacy_save_footers(); + Test test_save_reports_output_failure(); Test test_two_players_share_the_first_colony(); Test test_bed_parts_are_delivered_separately(); Test test_resident_uses_assigned_bed_and_sleep_survives_save(); @@ -75,14 +110,13 @@ Test CoreTests::test_parallel_pathfinding_completes_the_jobs() { } for (int tick = 0; tick < 120; ++tick) world.step(); require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job"); - return {}; } Test CoreTests::test_single_worker_configuration_is_rejected() { try { settlement::World world(8, 8, 8, 1); } catch (const std::invalid_argument&) { - return {}; + return; } throw std::runtime_error("world accepted a single worker"); } @@ -91,9 +125,8 @@ Test CoreTests::test_rng_repeats_for_same_seed() { settlement::DeterministicRng left(12345); settlement::DeterministicRng right(12345); for (int index = 0; index < 1000; ++index) { - expect_eq(left.next_u64(), right.next_u64()); + require_eq(left.next_u64(), right.next_u64()); } - return {}; } Test CoreTests::test_work_jobs_complete() { @@ -116,7 +149,6 @@ Test CoreTests::test_work_jobs_complete() { "completed job retained an active state"); require(world.agents().front().state == settlement::AgentState::Idle, "worker did not return to idle after completing a job"); - return {}; } Test CoreTests::test_astar_route_uses_opening_in_wall() { @@ -139,7 +171,6 @@ Test CoreTests::test_astar_route_uses_opening_in_wall() { } require(world.path_searches() > 0, "path search counter was not updated"); require(world.path_nodes_visited() > 0, "A* did not report expanded nodes"); - return {}; } Test CoreTests::test_residents_gather_and_deliver_resources() { @@ -163,7 +194,6 @@ Test CoreTests::test_residents_gather_and_deliver_resources() { "storage retained reservations after deliveries completed"); require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0, "resource nodes retained units after deliveries completed"); - return {}; } Test CoreTests::test_production_reservations_and_construction() { @@ -244,8 +274,6 @@ Test CoreTests::test_production_reservations_and_construction() { "the builder skipped a delivery or construction stage"); require(world.storages()[0].items.empty() && world.storages()[1].items.empty(), "building did not consume the crafted materials from both stores"); - - return {}; } Test CoreTests::test_cabin_placement_queues_a_complete_order() { @@ -268,7 +296,6 @@ Test CoreTests::test_cabin_placement_queues_a_complete_order() { } catch (const std::invalid_argument&) { require(orders.size() == 6, "invalid placement partially queued new orders"); } - return {}; } Test CoreTests::test_hungry_resident_reserves_and_eats_a_berry() { @@ -318,7 +345,6 @@ Test CoreTests::test_hungry_resident_reserves_and_eats_a_berry() { static_cast(world.add_job(pantry, 1)); world.step(); require(world.jobs_completed() == 2, "the resident did not resume work after eating"); - return {}; } Test CoreTests::test_invalid_save_is_rejected() { @@ -337,7 +363,67 @@ Test CoreTests::test_invalid_save_is_rejected() { require(rejected(bytes + 'x'), "save with trailing data was accepted"); bytes[8] = 127; require(rejected(bytes), "unknown save version was accepted"); - return {}; +} + +Test CoreTests::test_save_version_13_matches_wire_fixture() { + constexpr std::uint64_t seed = 0x0102030405060708; + const settlement::World world(seed, 5, 5, 2); + require(save_contents(world) == empty_save_v13, "version 13 save bytes changed"); + + std::istringstream file(std::string(empty_save_v13), std::ios::binary); + const auto restored = settlement::World::read_save(file, 2); + require_eq(restored->seed(), seed); + require_eq(restored->width(), 5); + require_eq(restored->height(), 5); + require(save_contents(*restored) == empty_save_v13, "version 13 fixture changed after loading"); +} + +Test CoreTests::test_legacy_save_footers() { + constexpr auto incomplete = "Save is incomplete or unreadable."sv; + constexpr auto checksum_mismatch = "Legacy save integrity footer does not match."sv; + constexpr auto trailing_data = "Save contains unexpected trailing data."sv; + constexpr std::size_t version_offset = 8; + constexpr auto v8_footer = "\x33\x73\x67\x28\xa8\x53\x56\xfa"sv; + + // Version 1 ended at the record counts. These footers are fixed FNV-1a + // digests of the wire payloads, including SETTLERS and the version field. + std::string v1(empty_save_v13.substr(0, 146)); + v1[version_offset] = '\x01'; + v1 += "\x58\xc1\x77\x19\x3a\x69\xca\x2c"sv; + std::string v8(empty_save_v13); + v8[version_offset] = '\x08'; + v8 += v8_footer; + std::string v9(empty_save_v13); + v9[version_offset] = '\x09'; + + for (const auto* bytes : {&v1, &v8, &v9}) { + std::istringstream file(*bytes, std::ios::binary); + const auto restored = settlement::World::read_save(file); + require(save_contents(*restored) == empty_save_v13, "historical save did not preserve its state"); + } + + require_save_error(std::string_view(v8).substr(0, empty_save_v13.size()), incomplete); + require_save_error(std::string_view(v8).substr(0, v8.size() - 1), incomplete); + require_save_error(v8 + 'x', trailing_data); + require_save_error(v9 + std::string(v8_footer), trailing_data); + + v8.back() = '\0'; + require_save_error(v8, checksum_mismatch); +} + +Test CoreTests::test_save_reports_output_failure() { + const settlement::World world(0x0102030405060708, 5, 5, 2); + std::array buffer{}; + std::ospanstream file(buffer); + try { + world.write_save(file); + } catch (const std::runtime_error& error) { + require_eq(std::string_view(error.what()), "Could not write the save."sv); + require(file.bad(), "short write did not set the stream's badbit"); + require_eq(std::string_view(buffer.data(), buffer.size()), empty_save_v13.substr(0, buffer.size())); + return; + } + throw std::runtime_error("save succeeded despite a short write"); } Test CoreTests::test_two_players_share_the_first_colony() { @@ -383,7 +469,6 @@ Test CoreTests::test_two_players_share_the_first_colony() { "the shared colony could not feed its residents and complete the objective"); auto replay = save_roundtrip(*world); require(replay->scenario_progress().completed, "completion was lost after loading"); - return {}; } Test CoreTests::test_bed_parts_are_delivered_separately() { @@ -416,7 +501,6 @@ Test CoreTests::test_bed_parts_are_delivered_separately() { "the beds were not completed through three separate deliveries"); require(world->storages().back().item_count(ItemType::Cloth) == 8, "two beds must consume four pieces of cloth"); - return {}; } Test CoreTests::test_resident_uses_assigned_bed_and_sleep_survives_save() { @@ -467,7 +551,6 @@ Test CoreTests::test_resident_uses_assigned_bed_and_sleep_survives_save() { } require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed"); require(world.jobs_completed() == 2, "residents did not finish their existing work"); - return {}; } Test CoreTests::test_fatigue_slows_work_without_interrupting_it() { @@ -483,7 +566,6 @@ Test CoreTests::test_fatigue_slows_work_without_interrupting_it() { const auto before = resident.work_remaining; for (int i = 0; i < 6; ++i) world.step(); require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work"); - return {}; } Test CoreTests::test_ground_rest_never_uses_another_residents_bed() { @@ -525,7 +607,6 @@ Test CoreTests::test_ground_rest_never_uses_another_residents_bed() { require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner"); require(world.apply_command({1, 3, CommandKind::DemolishObject, new_cell}).status == CommandStatus::Accepted && world.assigned_bed(owner) == nullptr, "demolishing a bed left a stale assignment"); - return {}; } Test CoreTests::test_fields_mines_and_reindexing_active_hauls() { @@ -579,7 +660,6 @@ Test CoreTests::test_fields_mines_and_reindexing_active_hauls() { "growing, regrowing, or mining did not deliver resources"); require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted, "a new storage could not be placed"); - return {}; } Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignments() { @@ -636,7 +716,6 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment } require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood"); require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed"); - return {}; } Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { @@ -713,7 +792,6 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { require(world.storages().front().item_count(ItemType::Wood) == 0 && world.storages().front().item_count(ItemType::Loom) == 0, "the installed loom did not consume the materials and finished item exactly once"); - return {}; } Test CoreTests::test_field_growth_requires_a_worker() { @@ -743,7 +821,6 @@ Test CoreTests::test_field_growth_requires_a_worker() { require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading"); } require(world.resource_nodes().front().quantity > 0, "planting without a storage did not grow flax"); - return {}; } Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() { @@ -765,7 +842,6 @@ Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() { world.step(); require(world.agents().front().resource_node_index == 0 && world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache"); - return {}; } Test CoreTests::test_object_tools_work_in_an_older_demo_world() { @@ -787,7 +863,6 @@ Test CoreTests::test_object_tools_work_in_an_older_demo_world() { require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted, "a field in a demonstration could not be demolished"); static_cast(save_roundtrip(*world)); - return {}; } Test CoreTests::test_room_builds_and_saves_as_separate_parts() { @@ -830,7 +905,6 @@ Test CoreTests::test_room_builds_and_saves_as_separate_parts() { resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), "demolition removed the floor instead of the furniture"); static_cast(save_roundtrip(*resumed)); - return {}; } Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { @@ -907,7 +981,6 @@ Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { } static_cast(save_roundtrip(*resumed)); } - return {}; } Test CoreTests::test_carpenter_delivers_the_door_before_installation() { @@ -995,7 +1068,6 @@ Test CoreTests::test_carpenter_delivers_the_door_before_installation() { world->storages()[1].position}).status == CommandStatus::Accepted && crafted_orders() == 3, "losing the stock did not queue a replacement for the waiting room"); static_cast(save_roundtrip(*world)); - return {}; } Test CoreTests::test_carpenter_makes_furnishings_for_rooms() { @@ -1107,11 +1179,6 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() { count_orders(variant.craft) == 2, "a room ignored the matching furnishing already in stock"); static_cast(save_roundtrip(*world)); } - return {}; } } // namespace - -int main(int argc, char** argv) { - return CoreTests::run(argc, argv); -} diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 907d1df..af8575d 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -1,28 +1,156 @@ -#include "testing.hpp" - #include "lan_session.hpp" +#include "lan_wire.hpp" + +#include +#include #include -#include #include +#include +#include #include namespace { using namespace std::chrono_literals; +using namespace std::string_view_literals; using namespace settlement; using namespace settlement::viewer; -void require(bool condition, const char* message) { - if (!condition) throw std::runtime_error(message); -} - +using Void::Testing::expect_throw; +using Void::Testing::require; using Void::Testing::Test; +constexpr auto hello_bytes = "\x0d\x00\x00\x00\x01\x0b\x00\x00\x00\x10\x32\x54\x76\x98\xba\xdc\xfe"sv; +constexpr auto command_bytes = "\x23\x00\x00\x00\x03" + "\x11\x22\x33\x44\x55\x66\x77\x88\x07" + "\xfe\xff\xff\xff\x78\x56\x34\x12\xa5" + "\x04\x03\x02\x01\xfc\xfc\xfd\xfe\x87\x96\xa5\xb4\xc3\xd2\xe1\xf0"sv; +constexpr auto receipt_bytes = "\x0a\x00\x00\x00\x04\x04\x10\x32\x54\x76\x98\xba\xdc\xfe"sv; +constexpr auto ping_bytes = "\x01\x00\x00\x00\x06"sv; + struct LanTests : Void::Testing::Suite { + [[= Void::Testing::tag("wire")]] Test test_protocol_11_fixed_messages(); + [[= Void::Testing::tag("wire")]] Test test_fragmented_and_coalesced_frames(); + [[= Void::Testing::tag("wire")]] Test test_frame_size_limits(); [[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback(); }; +Test LanTests::test_protocol_11_fixed_messages() { + using namespace lan_wire; + constexpr Hello hello{protocol_version, 0xfedcba9876543210ULL}; + constexpr PlayerCommand command{ + 1, 0x8877665544332211ULL, CommandKind::MoveObject, {-2, 0x12345678}, 0xa5, + {0x01020304, -0x01020304}, 0xf0e1d2c3b4a59687ULL + }; + constexpr Receipt receipt{CommandStatus::InvalidTarget, 0xfedcba9876543210ULL}; + + std::string encoded; + const auto hello_payload = encode_hello(hello); + append_frame(encoded, Message::Hello, std::string_view(hello_payload)); + require(encoded == hello_bytes); + encoded.clear(); + const auto command_payload = encode_command(command); + append_frame(encoded, Message::Command, std::string_view(command_payload)); + require(encoded == command_bytes); + encoded.clear(); + const auto receipt_payload = encode_receipt(receipt); + append_frame(encoded, Message::Receipt, std::string_view(receipt_payload)); + require(encoded == receipt_bytes); + + const auto hello_frame = next_frame(hello_bytes); + require(hello_frame && hello_frame->message == Message::Hello && hello_frame->size == hello_bytes.size()); + const auto decoded_hello = decode_hello(hello_frame->payload); + require(decoded_hello && decoded_hello->version == 11 && decoded_hello->key == hello.key); + require(!decode_hello(hello_frame->payload.substr(1))); + require(!decode_hello(std::string(hello_frame->payload) + '\0')); + + const auto command_frame = next_frame(command_bytes); + require(command_frame && command_frame->message == Message::Command && command_frame->size == command_bytes.size()); + const auto decoded_command = decode_command(command_frame->payload); + require(decoded_command.has_value()); + require(decoded_command->player == 2); + require(decoded_command->sequence == command.sequence); + require(decoded_command->kind == command.kind); + require(decoded_command->cell == command.cell); + require(decoded_command->value == command.value); + require(decoded_command->destination == command.destination); + require(decoded_command->resident == command.resident); + require(!decode_command(command_frame->payload.substr(1))); + require(!decode_command(std::string(command_frame->payload) + '\0')); + + const auto receipt_frame = next_frame(receipt_bytes); + require(receipt_frame && receipt_frame->message == Message::Receipt && receipt_frame->size == receipt_bytes.size()); + const auto decoded_receipt = decode_receipt(receipt_frame->payload); + require(decoded_receipt && decoded_receipt->status == receipt.status && + decoded_receipt->next_sequence == receipt.next_sequence); + require(!decode_receipt(receipt_frame->payload.substr(1))); + require(!decode_receipt(std::string(receipt_frame->payload) + '\0')); +} + +Test LanTests::test_fragmented_and_coalesced_frames() { + using namespace lan_wire; + std::string received(command_bytes.substr(0, 3)); + require(!next_frame(received)); + received.append(command_bytes.substr(3, 8)); + require(!next_frame(received)); + received.append(command_bytes.substr(11)); + received.append(ping_bytes); + received.append(hello_bytes.substr(0, 5)); + + std::size_t consumed = 0; + { + const auto command = next_frame(received); + require(command && command->message == Message::Command && command->size == command_bytes.size()); + require(command->payload.data() == received.data() + 5); + require(command->payload == command_bytes.substr(5)); + + const auto ping = next_frame(std::string_view(received).substr(command->size)); + require(ping && ping->message == Message::Ping && ping->payload.empty() && ping->size == ping_bytes.size()); + consumed = command->size + ping->size; + require(!next_frame(std::string_view(received).substr(consumed))); + } + + received.erase(0, consumed); + received.append(hello_bytes.substr(5)); + const auto hello = next_frame(received); + require(hello && hello->message == Message::Hello && hello->size == received.size()); + require(hello->payload == hello_bytes.substr(5)); +} + +Test LanTests::test_frame_size_limits() { + using namespace lan_wire; + constexpr auto empty_prefix = "\x00\x00\x00\x00"sv; + constexpr auto max_prefix = "\x00\x00\x40\x00"sv; + constexpr auto oversized_prefix = "\x01\x00\x40\x00"sv; + + require(!next_frame(empty_prefix.substr(0, 3))); + require(!next_frame(oversized_prefix.substr(0, 3))); + expect_throw([] { static_cast(next_frame(empty_prefix)); }); + expect_throw([] { static_cast(next_frame(oversized_prefix)); }); + require(!next_frame(max_prefix)); + + std::string output; + append_frame(output, Message::Ping); + require(output == ping_bytes); + + std::string payload(4 * 1024 * 1024 - 1, '\xa5'); + output.clear(); + append_frame(output, Message::Snapshot, payload); + require(output.starts_with(max_prefix)); + { + const auto snapshot = next_frame(output); + require(snapshot && snapshot->message == Message::Snapshot && snapshot->size == output.size()); + require(snapshot->payload == payload); + payload.front() = '\0'; + require(snapshot->payload.front() == '\xa5'); + } + + payload.push_back('\0'); + expect_throw([&] { append_frame(output, Message::Snapshot, payload); }); + require(output.size() == ping_bytes.size() + payload.size() - 1); +} + Test LanTests::test_shared_colony_over_loopback() { auto authoritative = make_first_colony(4); auto client_view = make_first_colony(4); @@ -47,23 +175,20 @@ Test LanTests::test_shared_colony_over_loopback() { guest.join("127.0.0.1", wrong_code, port); pump_until([&] { return guest.state() == LanState::GuestDisconnected; }, "a guest with the wrong code was not disconnected"); - require(host.state() == LanState::Hosting, "an invalid guest occupied the player slot"); + require(host.state() == LanState::Hosting); guest.join("127.0.0.1", code, port); pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not join"); - require(client_view->tick() == 25 && client_view->agents().size() == authoritative->agents().size(), - "joining did not deliver the host's current snapshot"); - require(!guest.submit(CommandKind::SetPaused, {}, 1), "a guest could control pause"); - require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast(BedBase::Stone)), - "the guest could not send a build command"); + require(client_view->tick() == 25 && client_view->agents().size() == authoritative->agents().size()); + require(!guest.submit(CommandKind::SetPaused, {}, 1)); + require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast(BedBase::Stone))); pump_until([&] { return client_view->production_orders().size() == 1 && client_view->production_orders().front().position == GridPosition{16, 18} && client_view->production_orders().front().bed_base == BedBase::Stone; }, "the guest's bed was not applied and synchronized"); - require(authoritative->production_orders().front().bed_base == BedBase::Stone, - "the guest's choice of bed material was lost"); - require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0), "the guest could not send a conflicting command"); + require(authoritative->production_orders().front().bed_base == BedBase::Stone); + require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0)); pump_until([&] { const auto rejected = guest.take_rejection(); return rejected && rejected->status == CommandStatus::InvalidTarget && @@ -71,7 +196,7 @@ Test LanTests::test_shared_colony_over_loopback() { rejected->value == 0; }, "a conflicting guest command did not return a rejection"); - require(authoritative->production_orders().size() == 1, "the same cell was claimed twice"); + require(authoritative->production_orders().size() == 1); guest.leave(); pump_until([&] { return host.state() == LanState::Hosting; }, "the guest slot was not released"); @@ -79,9 +204,8 @@ Test LanTests::test_shared_colony_over_loopback() { guest.join("127.0.0.1", code, port); pump_until([&] { return guest.state() == LanState::GuestConnected; }, "the guest could not rejoin"); require(client_view->tick() == authoritative->tick() && client_view->next_command_sequence(2) == 2 && - client_view->production_orders().size() == 1, - "rejoining did not restore the current colony and guest sequence"); - require(guest.submit(CommandKind::SetForaging, {14, 12}, 1), "the reconnected guest could not send a command"); + client_view->production_orders().size() == 1); + require(guest.submit(CommandKind::SetForaging, {14, 12}, 1)); pump_until([&] { if (client_view->next_command_sequence(2) != 3) return false; for (const auto& node : client_view->resource_nodes()) { @@ -96,13 +220,13 @@ Test LanTests::test_shared_colony_over_loopback() { return false; }; for (int i = 0; i < 600 && !owner_sleeping(*authoritative); ++i) authoritative->step(); - require(owner_sleeping(*authoritative), "the owner went without sleep"); + require(owner_sleeping(*authoritative)); pump_until([&] { return client_view->tick() == authoritative->tick() && owner_sleeping(*client_view); }, "the host's sleep state did not reach the guest"); const GridPosition field{14, 15}; const GridPosition new_field{14, 17}; - require(guest.submit(CommandKind::PlaceBerryField, field, 0), "the guest could not plant a field"); + require(guest.submit(CommandKind::PlaceBerryField, field, 0)); const auto has_field = [&](GridPosition position) { for (const auto& node : client_view->resource_nodes()) { if (node.site == ResourceSite::BerryField && node.position == position) return true; @@ -110,24 +234,23 @@ Test LanTests::test_shared_colony_over_loopback() { return false; }; pump_until([&] { return has_field(field); }, "the planted field was not synchronized"); - require(guest.submit(CommandKind::MoveObject, field, 0, new_field), "the guest could not move the field"); + require(guest.submit(CommandKind::MoveObject, field, 0, new_field)); pump_until([&] { return has_field(new_field) && !has_field(field); }, "the move destination was not synchronized"); - require(guest.submit(CommandKind::DemolishObject, new_field, 0), "the guest could not remove the field"); + require(guest.submit(CommandKind::DemolishObject, new_field, 0)); pump_until([&] { return !has_field(new_field); }, "demolishing a field was not synchronized"); const auto resident = authoritative->agents().back().id; - require(guest.submit(CommandKind::AssignProfession, {}, static_cast(Profession::Miner), {}, resident), - "the guest could not assign a profession"); + require(guest.submit(CommandKind::AssignProfession, {}, static_cast(Profession::Miner), {}, resident)); pump_until([&] { return client_view->agents().back().id == resident && client_view->agents().back().profession == Profession::Miner; }, "the assigned profession was not synchronized"); - require(guest.submit(CommandKind::PlaceFlaxField, field, 0), "the guest could not plant flax"); + require(guest.submit(CommandKind::PlaceFlaxField, field, 0)); pump_until([&] { return client_view->resource_nodes().back().site == ResourceSite::FlaxField && client_view->resource_nodes().back().position == field; }, "the flax field did not arrive in the guest snapshot"); - require(guest.submit(CommandKind::PlaceLoom, new_field, 0), "the guest could not place a loom"); + require(guest.submit(CommandKind::PlaceLoom, new_field, 0)); pump_until([&] { const auto& orders = client_view->production_orders(); return orders.size() >= 2 && orders.back().recipe == RecipeId::CraftLoom && @@ -138,7 +261,7 @@ Test LanTests::test_shared_colony_over_loopback() { authoritative->step(); } require(authoritative->resource_nodes().back().needs_tending() && - authoritative->resource_nodes().back().reserved_workers == 1, "no resident reserved the field for sowing"); + authoritative->resource_nodes().back().reserved_workers == 1); pump_until([&] { return client_view->tick() == authoritative->tick() && client_view->resource_nodes().back().needs_tending() && @@ -154,30 +277,22 @@ Test LanTests::test_shared_colony_over_loopback() { found_room = true; } } - require(found_room, "could not find a test plot for a room"); + require(found_room); const auto entrance = static_cast(room.entrance); const auto previous_size = authoritative->production_orders().size(); - require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), - "guest could not send the room"); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last)); pump_until([&] { return client_view->production_orders().size() == previous_size + 10 && client_view->production_orders().back().recipe == RecipeId::CraftWoodenDoor; }, "snapshot did not carry the room and carpenter's order"); - require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), - "guest could not send the conflicting room"); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last)); pump_until([&] { const auto rejected = guest.take_rejection(); return rejected && rejected->kind == CommandKind::PlaceRoom && rejected->cell == room.first && rejected->destination == room.last && rejected->value == entrance && rejected->status == CommandStatus::InvalidTarget; }, "room rejection lost the geometry needed to restore the draft"); - require(authoritative->production_orders().size() == previous_size + 10, "room conflict scheduled extra work"); - std::cout << "Loopback LAN checks passed.\n"; - return {}; + require(authoritative->production_orders().size() == previous_size + 10); } } // namespace - -int main(int argc, char** argv) { - return LanTests::run(argc, argv); -} diff --git a/tests/test_main.cpp b/tests/test_main.cpp new file mode 100644 index 0000000..27c43fc --- /dev/null +++ b/tests/test_main.cpp @@ -0,0 +1,40 @@ +#include + +#include +#include +#include +#include + +int main(int argc, char** argv) { + // Void parses its own options but ignores stray positional arguments. + constexpr std::array options_with_values{ + "--filter", "--suite", "--reporter", "--output", "--tag", + "--log-file", "--selftest-child", "--seed", "--repeat", "--parallel", + }; + for (int i = 1; i < argc; ++i) { + const std::string_view argument = argv[i]; + if (!argument.starts_with('-')) { + std::cerr << "error: Unexpected positional argument '" << argument << "'\n"; + return 2; + } + if (argument == "--tag" && (i + 1 == argc || argv[i + 1][0] == '\0')) { + std::cerr << "error: --tag requires a non-empty value\n"; + return 2; + } + if (i + 1 < argc && std::ranges::contains(options_with_values, argument)) { + ++i; + } + } + + auto& runner = Void::Testing::Runner::instance(); + auto config = runner.parse_args(argc, argv); + // An explicit match-all filter makes an empty registry fail on a default run. + if (config.filter_pattern.empty()) { + config.filter_pattern = ".*"; + } + const auto result = runner.run(config); + if (!result.config_error.empty()) { + return 2; + } + return result.failed > 0 || result.crashed > 0 ? 1 : 0; +} diff --git a/tests/testing.hpp b/tests/testing.hpp deleted file mode 100644 index 4805f03..0000000 --- a/tests/testing.hpp +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Void::Testing { - -struct Test {}; - -struct AnnotationText { - char text[96]{}; - - consteval AnnotationText(std::string_view value) { - if (value.size() >= sizeof(text)) throw "Test annotation is too long"; - value.copy(text, value.size()); - } - - constexpr std::string_view view() const noexcept { return text; } -}; - -struct Tag { AnnotationText value; }; -struct Skip { AnnotationText value; }; - -consteval Tag tag(std::string_view value) { return {value}; } -consteval Skip skip(std::string_view reason) { return {reason}; } - -namespace detail { - -namespace meta = std::meta; - -template -std::vector annotation_values() { - std::vector values; - template for (constexpr auto a : std::define_static_array(meta::annotations_of_with_type(Member, ^^Annotation))) { - constexpr auto annotation = meta::extract(a); - values.emplace_back(annotation.value.view()); - } - return values; -} - -consteval bool is_test(meta::info member) { - return meta::is_function(member) && !meta::is_static_member(member) && - !meta::is_constructor(member) && !meta::is_destructor(member) && - meta::parameters_of(member).empty() && meta::return_type_of(member) == ^^Test; -} - -} // namespace detail - -template -struct Suite { - template - static void expect_eq(const Actual& actual, const Expected& expected, - std::source_location at = std::source_location::current()) { - if (!(actual == expected)) { - throw std::runtime_error(std::string(at.file_name()) + ":" + std::to_string(at.line()) + - ": expected equal values"); - } - } - - static int run(int argc, char** argv) { - std::string_view selected_tag; - if (argc == 3 && std::string_view(argv[1]) == "--tag" && argv[2][0] != '\0') { - selected_tag = argv[2]; - } else if (argc != 1) { - std::cerr << "Usage: " << argv[0] << " [--tag NAME]\n"; - return 1; - } - namespace meta = std::meta; - int matched = 0, failed = 0, skipped = 0; - template for (constexpr auto member : std::define_static_array(meta::members_of(^^Derived, - meta::access_context::current()))) { - if constexpr (detail::is_test(member)) { - const auto tags = detail::annotation_values(); - if (selected_tag.empty() || std::ranges::find(tags, selected_tag) != tags.end()) { - ++matched; - constexpr auto name = meta::identifier_of(member); - const auto reasons = detail::annotation_values(); - if (!reasons.empty()) { - ++skipped; - std::cout << "[SKIP] " << name << " (" << reasons.front() << ")\n"; - } else { - try { - Derived suite{}; - if constexpr (requires { suite.setup(); }) suite.setup(); - suite.[:member:](); - std::cout << "[PASS] " << name << '\n'; - } catch (const std::exception& error) { - ++failed; - std::cerr << "[FAIL] " << name << ": " << error.what() << '\n'; - } catch (...) { - ++failed; - std::cerr << "[FAIL] " << name << ": unexpected exception\n"; - } - } - } - } - } - if (matched == 0) { - std::cerr << "No tests matched"; - if (!selected_tag.empty()) std::cerr << " tag " << selected_tag; - std::cerr << '\n'; - return 1; - } - std::cout << matched - failed - skipped << " passed, " << failed << " failed, " << skipped << " skipped\n"; - return failed == 0 ? 0 : 1; - } -}; - -} // namespace Void::Testing