Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
596b491acf | ||
|
|
180506d414 | ||
|
|
e6a01bedcc | ||
|
|
db0a8720a6 | ||
|
|
b7f18c094b | ||
|
|
535424196e | ||
|
|
a8cd7bb415 | ||
|
|
2a3ec924de | ||
|
|
9a248c31ac | ||
|
|
2a5df1a18b | ||
|
|
aa4e271ab4 | ||
|
|
eef69caa0e | ||
|
|
09545bfe85 | ||
|
|
ce814767fb |
No files matched your search
+11
-1
@@ -89,16 +89,21 @@ target_link_libraries(settlement_lan
|
||||
)
|
||||
|
||||
enable_language(RC)
|
||||
add_library(settlement_client STATIC app/viewer_session.cpp)
|
||||
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_client PUBLIC settlement_core)
|
||||
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)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
if(MSVC)
|
||||
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
|
||||
else()
|
||||
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_link_options(settlement_viewer PRIVATE -municode)
|
||||
target_compile_options(settlement_viewer PRIVATE
|
||||
@@ -118,6 +123,7 @@ if(BUILD_TESTING)
|
||||
tests/core_tests.cpp
|
||||
tests/executor_tests.cpp
|
||||
tests/identity_tests.cpp
|
||||
tests/production_identity_tests.cpp
|
||||
tests/profile_tests.cpp
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
@@ -133,4 +139,8 @@ if(BUILD_TESTING)
|
||||
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)
|
||||
|
||||
add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp)
|
||||
target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing)
|
||||
add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests)
|
||||
endif()
|
||||
@@ -7,6 +7,8 @@
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace settlement { class SimulationRuntime; }
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
|
||||
@@ -20,6 +22,15 @@ struct LanRejection {
|
||||
GridPosition destination;
|
||||
};
|
||||
|
||||
struct LanCommandResult {
|
||||
CommandStatus status;
|
||||
CommandKind kind;
|
||||
GridPosition cell;
|
||||
std::uint8_t value;
|
||||
GridPosition destination;
|
||||
AgentId resident;
|
||||
};
|
||||
|
||||
class LanSession {
|
||||
public:
|
||||
LanSession();
|
||||
@@ -39,7 +50,14 @@ public:
|
||||
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
|
||||
GridPosition destination = {}, AgentId resident = 0);
|
||||
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
|
||||
// poll_guest pauses further sends until this one retained result is drained.
|
||||
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
|
||||
[[nodiscard]] std::unique_ptr<World> poll(World& world);
|
||||
// Protocol 11 accepts the compiled default rules and a 32x32 active colony.
|
||||
// Calls never wait for the owner. An admitted guest operation survives peer
|
||||
// turnover, so poll_host must continue with the same owner until it settles.
|
||||
void poll_host(SimulationRuntime& runtime);
|
||||
[[nodiscard]] std::unique_ptr<World> poll_guest();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
|
||||
+180
-31
@@ -6,6 +6,7 @@
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -153,6 +154,12 @@ struct Action {
|
||||
} // namespace
|
||||
|
||||
struct LanSession::Impl {
|
||||
struct PendingCommand {
|
||||
std::future<RuntimeResult> completion;
|
||||
Void::Uuid::Uuid session;
|
||||
std::uint64_t peer_generation;
|
||||
};
|
||||
|
||||
bool winsock = false;
|
||||
Socket listener;
|
||||
Channel peer;
|
||||
@@ -167,12 +174,18 @@ struct LanSession::Impl {
|
||||
std::string notice;
|
||||
std::deque<Action> actions;
|
||||
std::optional<LanRejection> rejected_command;
|
||||
std::optional<LanCommandResult> command_result;
|
||||
bool result_backpressure = false;
|
||||
std::uint64_t guest_sequence = 0;
|
||||
Clock::time_point last_ping{};
|
||||
Clock::time_point last_snapshot{};
|
||||
std::uint64_t sent_tick = 0;
|
||||
std::uint64_t sent_host_sequence = 0;
|
||||
std::uint64_t sent_guest_sequence = 0;
|
||||
std::uint64_t peer_generation = 0;
|
||||
std::optional<Void::Uuid::Uuid> runtime_session;
|
||||
std::optional<RulesManifest> compatibility_rules;
|
||||
std::optional<PendingCommand> pending_command;
|
||||
|
||||
Impl() {
|
||||
WSADATA data{};
|
||||
@@ -185,14 +198,18 @@ struct LanSession::Impl {
|
||||
}
|
||||
|
||||
void drop_peer() noexcept {
|
||||
++peer_generation;
|
||||
peer = Channel{};
|
||||
connecting = authenticated = reject_pending = false;
|
||||
awaiting_receipt.reset();
|
||||
guest_sequence = 0;
|
||||
actions.clear();
|
||||
rejected_command.reset();
|
||||
command_result.reset();
|
||||
last_snapshot = {};
|
||||
last_ping = {};
|
||||
// pending_command belongs to the authenticated guest slot, even after
|
||||
// its socket disappears. A later peer waits for this result to settle.
|
||||
}
|
||||
|
||||
void accept_guest() {
|
||||
@@ -223,17 +240,21 @@ struct LanSession::Impl {
|
||||
connecting = false;
|
||||
}
|
||||
|
||||
void authenticate(Message message, std::string_view payload) {
|
||||
if (reject_pending) return;
|
||||
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;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
}
|
||||
|
||||
void handle_host(World& world, Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
if (reject_pending) return;
|
||||
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;
|
||||
}
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
@@ -244,6 +265,83 @@ struct LanSession::Impl {
|
||||
peer.queue(Message::Receipt, std::string_view(reply));
|
||||
}
|
||||
|
||||
void reply(CommandStatus status, const World& world) {
|
||||
const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)});
|
||||
peer.queue(Message::Receipt, std::string_view(bytes));
|
||||
}
|
||||
|
||||
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
|
||||
Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
authenticate(message, payload);
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
|
||||
if (!command) throw std::runtime_error("Invalid guest command.");
|
||||
if (pending_command) throw std::runtime_error("A guest command is already pending.");
|
||||
if (command->sequence != snapshot.world->next_command_sequence(guest_player)) {
|
||||
reply(CommandStatus::WrongSequence, *snapshot.world);
|
||||
return;
|
||||
}
|
||||
const auto& identity = snapshot.identity;
|
||||
const CommandEnvelope envelope{
|
||||
command_envelope_version, identity.world, identity.session, identity.city,
|
||||
snapshot.next_requests[guest_player - 1],
|
||||
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
|
||||
};
|
||||
auto submitted = runtime.try_submit({guest_player}, envelope);
|
||||
if (submitted.admission == RuntimeAdmission::Accepted) {
|
||||
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
|
||||
} else if (submitted.admission == RuntimeAdmission::Busy) {
|
||||
reply(CommandStatus::Busy, *snapshot.world);
|
||||
} else {
|
||||
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
|
||||
}
|
||||
}
|
||||
|
||||
void complete_runtime_command() {
|
||||
if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return;
|
||||
auto pending = std::move(*pending_command);
|
||||
pending_command.reset();
|
||||
const auto result = pending.completion.get();
|
||||
if (pending.peer_generation != peer_generation || !authenticated ||
|
||||
!runtime_session || pending.session != *runtime_session) return;
|
||||
if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot ||
|
||||
result.snapshot->identity.session != pending.session) {
|
||||
throw std::runtime_error("The authoritative guest command did not commit.");
|
||||
}
|
||||
const auto& receipt = *result.receipt;
|
||||
if (receipt.status == DispatchStatus::Completed) {
|
||||
reply(receipt.command_status, *result.snapshot->world);
|
||||
} else if (receipt.status == DispatchStatus::Busy) {
|
||||
reply(CommandStatus::Busy, *result.snapshot->world);
|
||||
} else {
|
||||
throw std::runtime_error("The guest command belongs to an obsolete or conflicting request.");
|
||||
}
|
||||
}
|
||||
|
||||
void bind_runtime(const RuntimeView& view) {
|
||||
if (!compatibility_rules) {
|
||||
auto rules = default_rules_manifest();
|
||||
if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules.");
|
||||
compatibility_rules = std::move(*rules);
|
||||
}
|
||||
if (view.state != RuntimeState::Running || !view.snapshot) {
|
||||
throw std::runtime_error("The authoritative owner is unavailable.");
|
||||
}
|
||||
const auto& snapshot = *view.snapshot;
|
||||
if (!snapshot.rules || *snapshot.rules != *compatibility_rules) {
|
||||
throw std::runtime_error("Protocol 11 requires the compiled default rules.");
|
||||
}
|
||||
if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size ||
|
||||
snapshot.world->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
|
||||
}
|
||||
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
|
||||
runtime_session = snapshot.identity.session;
|
||||
}
|
||||
|
||||
void handle_guest(std::unique_ptr<World>& 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) {
|
||||
@@ -264,6 +362,8 @@ struct LanSession::Impl {
|
||||
}
|
||||
const auto status = receipt->status;
|
||||
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
|
||||
command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident};
|
||||
if (status != CommandStatus::Accepted) {
|
||||
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination};
|
||||
@@ -291,6 +391,7 @@ struct LanSession::Impl {
|
||||
|
||||
void send_action() {
|
||||
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
|
||||
if (result_backpressure && command_result) return;
|
||||
const Action action = actions.front();
|
||||
const auto payload = lan_wire::encode_command(
|
||||
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
|
||||
@@ -298,6 +399,31 @@ struct LanSession::Impl {
|
||||
actions.pop_front();
|
||||
awaiting_receipt = action;
|
||||
}
|
||||
|
||||
template<class Receive, class SendHost>
|
||||
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
|
||||
if (listener && accept_allowed) accept_guest();
|
||||
if (!peer.socket) return;
|
||||
const auto now = Clock::now();
|
||||
if ((!authenticated && now - peer.opened > 8s) ||
|
||||
(authenticated && now - peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connecting) finish_connection();
|
||||
if (connecting) return;
|
||||
peer.receive(receive);
|
||||
if (authenticated && guest) {
|
||||
send_action();
|
||||
if (!peer.pending() && now - last_ping >= 2s) {
|
||||
peer.queue(Message::Ping);
|
||||
last_ping = now;
|
||||
}
|
||||
} else if (authenticated) {
|
||||
send_host(now);
|
||||
}
|
||||
peer.flush();
|
||||
if (reject_pending && !peer.pending()) drop_peer();
|
||||
}
|
||||
};
|
||||
|
||||
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
|
||||
@@ -397,34 +523,57 @@ std::optional<LanRejection> LanSession::take_rejection() noexcept {
|
||||
return std::exchange(impl_->rejected_command, std::nullopt);
|
||||
}
|
||||
|
||||
std::optional<LanCommandResult> LanSession::take_result() noexcept {
|
||||
return std::exchange(impl_->command_result, std::nullopt);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll(World& world) {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = false;
|
||||
std::unique_ptr<World> latest;
|
||||
try {
|
||||
if (connection.listener) connection.accept_guest();
|
||||
if (!connection.peer.socket) return nullptr;
|
||||
const auto now = Clock::now();
|
||||
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
|
||||
(connection.authenticated && now - connection.peer.last_received > 15s)) {
|
||||
throw std::runtime_error("The peer did not respond.");
|
||||
}
|
||||
if (connection.connecting) connection.finish_connection();
|
||||
if (connection.connecting) return nullptr;
|
||||
connection.peer.receive([&](Message message, std::string_view payload) {
|
||||
if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner.");
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
if (connection.guest) connection.handle_guest(latest, message, payload);
|
||||
else connection.handle_host(world, message, payload);
|
||||
});
|
||||
if (connection.authenticated && connection.guest) {
|
||||
connection.send_action();
|
||||
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
|
||||
connection.peer.queue(Message::Ping);
|
||||
connection.last_ping = now;
|
||||
}
|
||||
} else if (connection.authenticated) {
|
||||
connection.send_snapshot(world, now);
|
||||
}
|
||||
connection.peer.flush();
|
||||
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
|
||||
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
latest.reset();
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
void LanSession::poll_host(SimulationRuntime& runtime) {
|
||||
auto& connection = *impl_;
|
||||
if (!connection.listener || connection.guest) return;
|
||||
try {
|
||||
connection.complete_runtime_command();
|
||||
// Completion may have published a newer next-request number. Re-read it
|
||||
// before admitting a reconnect or decoding any further guest intent.
|
||||
const auto view = runtime.view();
|
||||
connection.bind_runtime(view);
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
connection.handle_runtime_host(runtime, *view.snapshot, message, payload);
|
||||
}, [&](Clock::time_point now) {
|
||||
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
|
||||
}, !connection.pending_command);
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<World> LanSession::poll_guest() {
|
||||
auto& connection = *impl_;
|
||||
connection.result_backpressure = true;
|
||||
std::unique_ptr<World> latest;
|
||||
if (!connection.guest) return nullptr;
|
||||
try {
|
||||
connection.poll_network([&](Message message, std::string_view payload) {
|
||||
connection.handle_guest(latest, message, payload);
|
||||
}, [](Clock::time_point) {});
|
||||
} catch (const std::exception& error) {
|
||||
connection.notice = error.what();
|
||||
connection.drop_peer();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -19,6 +20,7 @@ constexpr int title_coop_id = 1103;
|
||||
constexpr int title_exit_id = 1104;
|
||||
constexpr int title_saves_id = 1105;
|
||||
constexpr int title_open_id = 1106;
|
||||
constexpr int title_rules_id = 1107;
|
||||
|
||||
inline std::filesystem::path saves_directory() {
|
||||
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
|
||||
@@ -51,6 +53,14 @@ public:
|
||||
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
|
||||
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
|
||||
rules_label_ = CreateWindowExW(0, L"STATIC", L"Правила только новой колонии:", WS_CHILD,
|
||||
0, 0, 0, 0, owner, nullptr, instance, nullptr);
|
||||
rules_ = CreateWindowExW(0, L"COMBOBOX", L"Правила новой колонии",
|
||||
WS_CHILD | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST,
|
||||
0, 0, 0, 0, owner, id(title_rules_id), instance, nullptr);
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Поэтапная кровать: опора и 2 ткани"));
|
||||
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Простая кровать: 1 доска"));
|
||||
SendMessageW(rules_, CB_SETCURSEL, 0, 0);
|
||||
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
|
||||
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
|
||||
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
|
||||
@@ -58,6 +68,8 @@ public:
|
||||
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(saves_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(open_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_label_, WM_SETFONT, font, FALSE);
|
||||
SendMessageW(rules_, WM_SETFONT, font, FALSE);
|
||||
}
|
||||
|
||||
void reload_saves() {
|
||||
@@ -90,6 +102,8 @@ public:
|
||||
for (const auto button : buttons_) ShowWindow(button, flags);
|
||||
ShowWindow(saves_, flags);
|
||||
ShowWindow(open_, flags);
|
||||
ShowWindow(rules_label_, flags);
|
||||
ShowWindow(rules_, flags);
|
||||
}
|
||||
|
||||
void update(bool can_resume, bool offline) const {
|
||||
@@ -98,6 +112,7 @@ public:
|
||||
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
|
||||
EnableWindow(open_, offline && selected_index() < saves.size());
|
||||
EnableWindow(saves_, offline);
|
||||
EnableWindow(rules_, offline);
|
||||
}
|
||||
|
||||
HBRUSH paint_list_background(HWND control, HDC dc) const {
|
||||
@@ -116,6 +131,10 @@ public:
|
||||
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
|
||||
}
|
||||
|
||||
[[nodiscard]] ColonyProfile new_colony_profile() const {
|
||||
return SendMessageW(rules_, CB_GETCURSEL, 0, 0) == 1 ? ColonyProfile::PlankBeds : ColonyProfile::Default;
|
||||
}
|
||||
|
||||
void layout(int width, int height) const {
|
||||
const RECT panel = bounds(width, height);
|
||||
for (std::size_t i = 0; i < buttons_.size(); ++i) {
|
||||
@@ -123,6 +142,8 @@ public:
|
||||
}
|
||||
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
|
||||
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
|
||||
position(rules_label_, panel.left + 28, panel.top + 358, panel.right - panel.left - 56, 23);
|
||||
position(rules_, panel.left + 28, panel.top + 383, panel.right - panel.left - 56, 100);
|
||||
}
|
||||
|
||||
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
|
||||
@@ -160,7 +181,7 @@ public:
|
||||
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
|
||||
&saves_label, DT_SINGLELINE | DT_VCENTER);
|
||||
if (!notice.empty()) {
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
|
||||
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.top + 355};
|
||||
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
|
||||
}
|
||||
SetTextColor(dc, ink);
|
||||
@@ -209,7 +230,7 @@ private:
|
||||
|
||||
static RECT bounds(int width, int height) {
|
||||
constexpr int panel_width = 704;
|
||||
constexpr int panel_height = 365;
|
||||
constexpr int panel_height = 430;
|
||||
const int left = (width - panel_width) / 2;
|
||||
const int top = (height - panel_height) / 2;
|
||||
return {left, top, left + panel_width, top + panel_height};
|
||||
@@ -233,6 +254,8 @@ private:
|
||||
std::array<HWND, 5> buttons_{};
|
||||
HWND saves_ = nullptr;
|
||||
HWND open_ = nullptr;
|
||||
HWND rules_label_ = nullptr;
|
||||
HWND rules_ = nullptr;
|
||||
HBRUSH list_background_ = nullptr;
|
||||
HFONT font_ = nullptr;
|
||||
std::vector<SaveFile> saves;
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
#include "viewer_session.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
template<class T>
|
||||
bool ready(std::future<T>& completion) {
|
||||
return completion.valid() && completion.wait_for(std::chrono::seconds{0}) == std::future_status::ready;
|
||||
}
|
||||
|
||||
RulesManifest supported_rules() {
|
||||
auto manifest = default_rules_manifest();
|
||||
if (!manifest) throw std::runtime_error(manifest.error().message);
|
||||
return std::move(*manifest);
|
||||
}
|
||||
|
||||
void validate_supported(const WorldCheckpoint& candidate) {
|
||||
const auto valid = validate_colony_checkpoint(candidate);
|
||||
if (!valid) throw std::runtime_error(valid.error().message);
|
||||
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
|
||||
candidate.world->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
}
|
||||
|
||||
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
|
||||
validate_supported(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
|
||||
auto candidate = make_colony_checkpoint(profile, workers);
|
||||
if (!candidate) throw std::runtime_error(candidate.error().message);
|
||||
return std::move(*candidate);
|
||||
}
|
||||
|
||||
RuntimeOptions suspended(RuntimeOptions options) {
|
||||
options.ticking = false;
|
||||
return options;
|
||||
}
|
||||
|
||||
std::string exception_message() {
|
||||
try { throw; }
|
||||
catch (const std::exception& error) { return error.what(); }
|
||||
catch (...) { return "The operation failed."; }
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
|
||||
: ViewerSession(initial_colony(workers), workers, std::move(options)) {}
|
||||
|
||||
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
|
||||
: workers_(workers), command_capacity_(options.command_capacity),
|
||||
supported_rules_(supported_rules()),
|
||||
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
|
||||
files_(std::move(options.files)) {
|
||||
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
|
||||
}
|
||||
|
||||
ViewerSession::~ViewerSession() = default;
|
||||
|
||||
std::shared_ptr<const World> ViewerSession::world() const {
|
||||
return guest_ || (changing_world_ && guest_view_) ? guest_view_ : runtime_.latest()->world;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_submit() const {
|
||||
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
|
||||
}
|
||||
|
||||
bool ViewerSession::can_host_legacy() const {
|
||||
const auto current = runtime_.view();
|
||||
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
|
||||
current.snapshot->rules && *current.snapshot->rules == supported_rules_;
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
|
||||
if (!can_submit()) return std::nullopt;
|
||||
for (const auto& intent : intents_) {
|
||||
if (intent.payload == payload) return intent.id;
|
||||
}
|
||||
if (intents_.size() == command_capacity_ || next_intent_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto id = next_intent_;
|
||||
intents_.push_back({id, std::move(payload)});
|
||||
++next_intent_;
|
||||
return id;
|
||||
}
|
||||
|
||||
bool ViewerSession::pending(std::uint64_t id) const noexcept {
|
||||
for (const auto& intent : intents_) if (intent.id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadTicket ViewerSession::begin_change() {
|
||||
if (generation_ == std::numeric_limits<std::uint64_t>::max()) {
|
||||
throw std::overflow_error("The client operation counter is exhausted.");
|
||||
}
|
||||
auto ticket = runtime_.begin_load();
|
||||
if (!ticket) throw std::runtime_error("The simulation cannot accept a world change.");
|
||||
++generation_;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
events_.clear();
|
||||
changing_world_ = true;
|
||||
return *ticket;
|
||||
}
|
||||
|
||||
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
|
||||
validate_supported(candidate);
|
||||
}
|
||||
|
||||
void ViewerSession::replace(WorldCheckpoint candidate) {
|
||||
validate_candidate(candidate);
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, std::move(candidate)});
|
||||
}
|
||||
|
||||
void ViewerSession::new_colony(ColonyProfile profile) {
|
||||
replace(initial_colony(workers_, profile));
|
||||
}
|
||||
|
||||
void ViewerSession::load(const std::filesystem::path& path) {
|
||||
if (guest_) throw std::runtime_error("Only the host can load a world.");
|
||||
const auto ticket = begin_change();
|
||||
try {
|
||||
auto operation = files_.try_load(path, workers_);
|
||||
if (operation.admission != CheckpointLoadAdmission::Accepted) {
|
||||
throw std::runtime_error("The file reader is busy or unavailable. Try again.");
|
||||
}
|
||||
preparing_.emplace(Preparing{ticket, std::move(operation.completion)});
|
||||
} catch (...) {
|
||||
changing_world_ = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::save(const std::filesystem::path& path) {
|
||||
if (guest_ || changing_world_) throw std::runtime_error("The current world cannot be saved yet.");
|
||||
poll_saves();
|
||||
const auto snapshot = runtime_.snapshot_for_save();
|
||||
if (!snapshot) throw std::runtime_error("Load a valid world before saving after a simulation failure.");
|
||||
// Reserve result tracking before accepting a write so allocation cannot lose
|
||||
// the newest request's completion or its originating session.
|
||||
saving_.reserve(saving_.size() + 1);
|
||||
auto operation = files_.try_save(path, *snapshot);
|
||||
if (operation.admission != SaveAdmission::Accepted) {
|
||||
throw std::runtime_error("The save queue is busy or unavailable. Try again.");
|
||||
}
|
||||
latest_save_ = operation.request_id;
|
||||
saving_.push_back({generation_, operation.request_id, (*snapshot)->identity.session,
|
||||
std::move(operation.completion)});
|
||||
}
|
||||
|
||||
void ViewerSession::enter_guest() {
|
||||
static_cast<void>(begin_change());
|
||||
guest_ = true;
|
||||
changing_world_ = false;
|
||||
guest_world_.reset();
|
||||
guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::receive_guest(std::unique_ptr<World> world) {
|
||||
if (!guest_ || !world) return;
|
||||
auto view = world->capture();
|
||||
guest_world_ = std::move(world);
|
||||
guest_view_ = std::move(view);
|
||||
}
|
||||
|
||||
void ViewerSession::leave_guest() {
|
||||
if (!guest_) return;
|
||||
if (guest_world_) {
|
||||
auto id = Void::Uuid::try_v4();
|
||||
if (!id) throw std::runtime_error("Could not create a world identity.");
|
||||
if (guest_world_->width() != first_colony_map_size || guest_world_->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
|
||||
}
|
||||
// All fallible preparation precedes moving the last received world.
|
||||
auto rules = supported_rules_;
|
||||
const auto ticket = begin_change();
|
||||
installing_.emplace(Installing{ticket, {std::move(guest_world_), *id, 1, std::move(rules)}});
|
||||
} else {
|
||||
static_cast<void>(begin_change());
|
||||
changing_world_ = false;
|
||||
}
|
||||
guest_ = false;
|
||||
if (!changing_world_) guest_view_.reset();
|
||||
}
|
||||
|
||||
void ViewerSession::fail_change(std::string message) {
|
||||
preparing_.reset();
|
||||
installing_.reset();
|
||||
install_completion_ = {};
|
||||
changing_world_ = false;
|
||||
if (!guest_) guest_view_.reset();
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable, std::move(message)});
|
||||
}
|
||||
|
||||
void ViewerSession::poll_changes() {
|
||||
if (preparing_ && ready(preparing_->completion)) {
|
||||
const auto ticket = preparing_->ticket;
|
||||
auto prepared = preparing_->completion.get();
|
||||
preparing_.reset();
|
||||
if (runtime_.latest()->identity.session != ticket.expected_session) {
|
||||
fail_change("The load belongs to an earlier session.");
|
||||
return;
|
||||
}
|
||||
if (!prepared) {
|
||||
fail_change(prepared.error().message);
|
||||
return;
|
||||
}
|
||||
validate_candidate(*prepared);
|
||||
installing_.emplace(Installing{ticket, std::move(*prepared)});
|
||||
}
|
||||
if (installing_) {
|
||||
auto result = runtime_.try_install(installing_->ticket, installing_->candidate);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
install_completion_ = std::move(result.completion);
|
||||
installing_.reset();
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
fail_change("The simulation could not install this world.");
|
||||
}
|
||||
}
|
||||
if (ready(install_completion_)) {
|
||||
const auto result = install_completion_.get();
|
||||
changing_world_ = false;
|
||||
if (result.outcome == RuntimeOutcome::Completed && result.snapshot &&
|
||||
result.snapshot->identity.session == runtime_.latest()->identity.session) {
|
||||
guest_view_.reset();
|
||||
fault_reported_ = false;
|
||||
events_.push_back({ViewerEventKind::Replaced, 0, {}, CommandStatus::Unavailable, {}});
|
||||
} else {
|
||||
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable,
|
||||
"The world change failed or was superseded. The current view is retained."});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_commands() {
|
||||
if (ready(command_completion_)) {
|
||||
auto result = command_completion_.get();
|
||||
if (!intents_.empty()) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
const auto status = result.outcome == RuntimeOutcome::Completed && result.receipt &&
|
||||
result.receipt->status == DispatchStatus::Completed
|
||||
? result.receipt->command_status : CommandStatus::Unavailable;
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), status, {}});
|
||||
}
|
||||
}
|
||||
if (command_completion_.valid() || intents_.empty() || !can_submit()) return;
|
||||
const auto current = runtime_.latest();
|
||||
const CommandEnvelope command{command_envelope_version, current->identity.world, current->identity.session,
|
||||
current->identity.city, current->next_requests[colony_host - 1], intents_.front().payload};
|
||||
auto result = runtime_.try_submit({colony_host}, command);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
command_completion_ = std::move(result.completion);
|
||||
} else if (result.admission != RuntimeAdmission::Busy) {
|
||||
auto intent = std::move(intents_.front());
|
||||
intents_.pop_front();
|
||||
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), CommandStatus::Unavailable, {}});
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_saves() {
|
||||
for (auto item = saving_.begin(); item != saving_.end();) {
|
||||
if (!ready(item->completion)) {
|
||||
++item;
|
||||
continue;
|
||||
}
|
||||
const auto result = item->completion.get();
|
||||
if (item->generation == generation_ && item->request == latest_save_ &&
|
||||
item->session == runtime_.latest()->identity.session && !guest_) {
|
||||
events_.push_back({result.succeeded() ? ViewerEventKind::Saved : ViewerEventKind::Error,
|
||||
0, {}, CommandStatus::Unavailable,
|
||||
result.succeeded() ? "" : result.visible_on_disk
|
||||
? "The new save is visible, but its final disk status could not be confirmed."
|
||||
: "The save failed. The previous slot remains available."});
|
||||
}
|
||||
item = saving_.erase(item);
|
||||
}
|
||||
}
|
||||
|
||||
void ViewerSession::poll_ticking() {
|
||||
if (ready(ticking_completion_)) {
|
||||
const auto result = ticking_completion_.get();
|
||||
// The owner applies its ticking flag even while its world is faulted.
|
||||
if (result.outcome == RuntimeOutcome::Completed || result.outcome == RuntimeOutcome::Faulted) {
|
||||
applied_ticking_ = requested_ticking_;
|
||||
}
|
||||
}
|
||||
const bool desired = desired_ticking_ && !guest_ && !changing_world_;
|
||||
if (ticking_completion_.valid() || desired == applied_ticking_) return;
|
||||
auto result = runtime_.set_ticking(desired);
|
||||
if (result.admission == RuntimeAdmission::Accepted) {
|
||||
requested_ticking_ = desired;
|
||||
ticking_completion_ = std::move(result.completion);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ViewerEvent> ViewerSession::poll() {
|
||||
try {
|
||||
poll_changes();
|
||||
poll_commands();
|
||||
poll_saves();
|
||||
poll_ticking();
|
||||
} catch (...) {
|
||||
fail_change(exception_message());
|
||||
}
|
||||
if (!guest_ && runtime_.view().state == RuntimeState::Faulted && !fault_reported_) {
|
||||
fault_reported_ = true;
|
||||
intents_.clear();
|
||||
command_completion_ = {};
|
||||
events_.push_back({ViewerEventKind::Fault, 0, {}, CommandStatus::Unavailable,
|
||||
"The simulation stopped at its last completed state. Load a save to continue."});
|
||||
}
|
||||
return std::exchange(events_, {});
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/checkpoint_files.hpp"
|
||||
#include "settlement/core/colony_profile.hpp"
|
||||
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
enum class ViewerEventKind { Replaced, Command, Saved, Error, Fault };
|
||||
|
||||
struct ViewerEvent {
|
||||
ViewerEventKind kind;
|
||||
std::uint64_t command = 0;
|
||||
std::optional<SessionPayload> payload;
|
||||
CommandStatus status = CommandStatus::Unavailable;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct ViewerSessionOptions {
|
||||
RuntimeOptions runtime;
|
||||
CheckpointFilesOptions files;
|
||||
std::size_t command_capacity = 64;
|
||||
};
|
||||
|
||||
// Called only by the UI thread. Polling owns completion delivery; rendering holds
|
||||
// an immutable view independently of owner progress and nested window messages.
|
||||
class ViewerSession {
|
||||
public:
|
||||
explicit ViewerSession(std::size_t workers, ViewerSessionOptions options = {});
|
||||
ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options = {});
|
||||
~ViewerSession();
|
||||
|
||||
[[nodiscard]] SimulationRuntime& runtime() noexcept { return runtime_; }
|
||||
[[nodiscard]] std::shared_ptr<const World> world() const;
|
||||
[[nodiscard]] bool guest() const noexcept { return guest_; }
|
||||
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
|
||||
[[nodiscard]] bool can_submit() const;
|
||||
[[nodiscard]] bool can_host_legacy() const;
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept { return generation_; }
|
||||
[[nodiscard]] std::optional<std::uint64_t> submit(SessionPayload payload);
|
||||
[[nodiscard]] bool pending(std::uint64_t id) const noexcept;
|
||||
void set_ticking(bool enabled) noexcept { desired_ticking_ = enabled; }
|
||||
[[nodiscard]] std::vector<ViewerEvent> poll();
|
||||
|
||||
void new_colony(ColonyProfile profile = ColonyProfile::Default);
|
||||
void load(const std::filesystem::path& path);
|
||||
void save(const std::filesystem::path& path);
|
||||
void enter_guest();
|
||||
void receive_guest(std::unique_ptr<World> world);
|
||||
void leave_guest();
|
||||
|
||||
private:
|
||||
struct Intent {
|
||||
std::uint64_t id;
|
||||
SessionPayload payload;
|
||||
};
|
||||
struct Preparing {
|
||||
LoadTicket ticket;
|
||||
std::future<CheckpointLoadResult> completion;
|
||||
};
|
||||
struct Installing {
|
||||
LoadTicket ticket;
|
||||
WorldCheckpoint candidate;
|
||||
};
|
||||
struct Saving {
|
||||
std::uint64_t generation;
|
||||
std::uint64_t request;
|
||||
Void::Uuid::Uuid session;
|
||||
std::future<SaveResult> completion;
|
||||
};
|
||||
[[nodiscard]] LoadTicket begin_change();
|
||||
void replace(WorldCheckpoint candidate);
|
||||
void validate_candidate(const WorldCheckpoint& candidate) const;
|
||||
void fail_change(std::string message);
|
||||
void poll_changes();
|
||||
void poll_commands();
|
||||
void poll_saves();
|
||||
void poll_ticking();
|
||||
|
||||
std::size_t workers_;
|
||||
std::size_t command_capacity_;
|
||||
RulesManifest supported_rules_;
|
||||
SimulationRuntime runtime_;
|
||||
CheckpointFiles files_;
|
||||
std::shared_ptr<const World> guest_view_;
|
||||
std::unique_ptr<World> guest_world_;
|
||||
std::deque<Intent> intents_;
|
||||
std::future<RuntimeResult> command_completion_;
|
||||
std::optional<Preparing> preparing_;
|
||||
std::optional<Installing> installing_;
|
||||
std::future<RuntimeResult> install_completion_;
|
||||
std::vector<Saving> saving_;
|
||||
std::vector<ViewerEvent> events_;
|
||||
std::future<RuntimeResult> ticking_completion_;
|
||||
bool requested_ticking_ = false;
|
||||
bool applied_ticking_ = false;
|
||||
bool desired_ticking_ = false;
|
||||
bool guest_ = false;
|
||||
bool changing_world_ = false;
|
||||
bool fault_reported_ = false;
|
||||
std::uint64_t generation_ = 1;
|
||||
std::uint64_t next_intent_ = 1;
|
||||
std::uint64_t latest_save_ = 0;
|
||||
};
|
||||
|
||||
} // namespace settlement::viewer
|
||||
+368
-189
@@ -11,6 +11,7 @@
|
||||
#include "map_camera.hpp"
|
||||
#include "lan_session.hpp"
|
||||
#include "title_screen_win32.hpp"
|
||||
#include "viewer_session.hpp"
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -22,6 +23,7 @@
|
||||
#include <fstream>
|
||||
#include <initializer_list>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
@@ -116,7 +118,8 @@ struct DockLayout {
|
||||
};
|
||||
DockLayout dock_layout;
|
||||
std::array<HWND, 3> dock_section_buttons{};
|
||||
std::unique_ptr<settlement::World> world;
|
||||
std::shared_ptr<const settlement::World> world;
|
||||
std::unique_ptr<settlement::viewer::ViewerSession> session;
|
||||
namespace title = settlement::viewer;
|
||||
title::TitleScreen title_screen;
|
||||
bool showing_title = true;
|
||||
@@ -132,8 +135,9 @@ constexpr const wchar_t* building_view_labels[] = {
|
||||
L"Вид: полный", L"Вид: без крыш", L"Вид: без стен и крыш",
|
||||
};
|
||||
using settlement::viewer::LanState;
|
||||
settlement::viewer::LanSession lan;
|
||||
auto lan = std::make_unique<settlement::viewer::LanSession>();
|
||||
LanState displayed_lan_state = LanState::Offline;
|
||||
std::uint64_t lan_generation = 1;
|
||||
const auto local_worker_count = std::clamp<std::size_t>(
|
||||
std::thread::hardware_concurrency(), settlement::min_worker_count, 8);
|
||||
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room };
|
||||
@@ -200,6 +204,11 @@ constexpr const wchar_t* house_contents[] = {
|
||||
L"Каменная кровать и стойка с инструментами",
|
||||
L"Деревянная кровать и ткацкий станок",
|
||||
};
|
||||
constexpr const wchar_t* simple_house_contents[] = {
|
||||
L"Кровать: 1 доска; аптечный шкаф",
|
||||
L"Кровать: 1 доска; стойка с инструментами",
|
||||
L"Кровать: 1 доска; ткацкий станок",
|
||||
};
|
||||
std::array<HICON, 3> house_artwork{};
|
||||
struct DockSection {
|
||||
WorkPanel panel;
|
||||
@@ -244,6 +253,25 @@ ResidentRoster roster;
|
||||
std::optional<settlement::BedBase> selected_bed_base;
|
||||
std::vector<settlement::viewer::BlueprintPart> blueprint;
|
||||
std::vector<settlement::RoomPlan> room_blueprints;
|
||||
struct PendingDraft {
|
||||
std::uint64_t command;
|
||||
std::uint64_t revision;
|
||||
settlement::SessionPayload payload;
|
||||
std::optional<settlement::RoomPlan> room;
|
||||
std::optional<settlement::viewer::BlueprintPart> part;
|
||||
bool guest;
|
||||
};
|
||||
std::vector<PendingDraft> pending_drafts;
|
||||
struct GuestIntent {
|
||||
std::uint64_t command;
|
||||
std::uint64_t generation;
|
||||
settlement::SessionPayload payload;
|
||||
};
|
||||
std::vector<GuestIntent> guest_intents;
|
||||
constexpr std::size_t guest_intent_capacity = 64;
|
||||
std::uint64_t draft_revision = 0;
|
||||
std::uint64_t guest_command_id = 0;
|
||||
bool host_after_replacement = false;
|
||||
std::optional<settlement::GridPosition> room_anchor;
|
||||
settlement::RoomTemplate selected_room_template = settlement::RoomTemplate::Empty;
|
||||
std::optional<settlement::RoomSide> preferred_room_entrance;
|
||||
@@ -266,6 +294,9 @@ std::optional<settlement::GridPosition> hover_cell;
|
||||
std::optional<settlement::AgentId> selected_resident;
|
||||
std::wstring placement_message;
|
||||
|
||||
void pump_session(HWND window);
|
||||
void reconcile_ticking();
|
||||
|
||||
int dock_pixels(int pixels) {
|
||||
return MulDiv(pixels, dock_layout.scale, 100);
|
||||
}
|
||||
@@ -798,7 +829,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) {
|
||||
}
|
||||
|
||||
bool can_give_orders() {
|
||||
return !lan.is_guest() || lan.state() == LanState::GuestConnected;
|
||||
return world && session && (lan->is_guest() ? lan->state() == LanState::GuestConnected : session->can_submit());
|
||||
}
|
||||
|
||||
void update_roster_details() {
|
||||
@@ -974,6 +1005,8 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message
|
||||
}
|
||||
|
||||
void clear_blueprints() {
|
||||
++draft_revision;
|
||||
pending_drafts.clear();
|
||||
blueprint.clear();
|
||||
room_blueprints.clear();
|
||||
room_anchor.reset();
|
||||
@@ -988,15 +1021,16 @@ void toggle_work_panel(HWND window, WorkPanel panel) {
|
||||
}
|
||||
|
||||
bool can_resume_session() {
|
||||
return has_session && lan.state() != LanState::Connecting && lan.state() != LanState::GuestDisconnected;
|
||||
return has_session && lan->state() != LanState::Connecting && lan->state() != LanState::GuestDisconnected;
|
||||
}
|
||||
|
||||
void update_title_controls() {
|
||||
title_screen.update(can_resume_session(), lan.state() == LanState::Offline);
|
||||
title_screen.update(can_resume_session(), lan->state() == LanState::Offline);
|
||||
}
|
||||
|
||||
void show_title_screen(HWND window, bool visible) {
|
||||
showing_title = visible;
|
||||
reconcile_ticking();
|
||||
if (visible) {
|
||||
if (roster.window) DestroyWindow(roster.window);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
@@ -1025,15 +1059,11 @@ void show_title_screen(HWND window, bool visible) {
|
||||
}
|
||||
|
||||
void reset_world(HWND window) {
|
||||
world = settlement::make_first_colony(local_worker_count);
|
||||
session->new_colony(title_screen.new_colony_profile());
|
||||
host_after_replacement = false;
|
||||
clear_blueprints();
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None);
|
||||
show_title_screen(window, false);
|
||||
update_status();
|
||||
placement_message = L"Создаём поселение…";
|
||||
reconcile_ticking();
|
||||
invalidate_scene(window);
|
||||
}
|
||||
|
||||
@@ -1062,59 +1092,28 @@ std::optional<std::filesystem::path> choose_save_file(HWND window, bool saving)
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void save_world_file(const std::filesystem::path& path) {
|
||||
// Stage the complete file beside its destination before replacing an existing save.
|
||||
wchar_t temporary[MAX_PATH]{};
|
||||
if (GetTempFileNameW(path.parent_path().c_str(), L"stl", 0, temporary) == 0) {
|
||||
throw std::runtime_error("Could not create a temporary save in this folder.");
|
||||
}
|
||||
try {
|
||||
std::ofstream stream(std::filesystem::path(temporary), std::ios::binary | std::ios::trunc);
|
||||
if (!stream) throw std::runtime_error("Could not open the temporary save for writing.");
|
||||
world->write_save(stream);
|
||||
stream.close();
|
||||
if (!stream) throw std::runtime_error("Could not finish writing the temporary save.");
|
||||
if (!MoveFileExW(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
||||
throw std::runtime_error("Could not move the completed save into place.");
|
||||
}
|
||||
} catch (...) {
|
||||
DeleteFileW(temporary);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void handle_save_menu(HWND window, bool saving, std::optional<std::filesystem::path> selected = std::nullopt) {
|
||||
if (file_dialog_active || (saving && !world)) return;
|
||||
if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return;
|
||||
if (lan->is_guest() || (!saving && lan->state() != LanState::Offline)) return;
|
||||
file_dialog_active = true;
|
||||
reconcile_ticking();
|
||||
struct RestoreTimer {
|
||||
~RestoreTimer() { file_dialog_active = false; }
|
||||
~RestoreTimer() { file_dialog_active = false; reconcile_ticking(); }
|
||||
} restore_timer;
|
||||
|
||||
try {
|
||||
const auto path = selected ? std::move(selected) : choose_save_file(window, saving);
|
||||
if (!path) return;
|
||||
if (saving) {
|
||||
save_world_file(*path);
|
||||
placement_message = L"Поселение сохранено.";
|
||||
invalidate_scene(window);
|
||||
return;
|
||||
session->save(*path);
|
||||
placement_message = L"Сохраняем поселение…";
|
||||
} else {
|
||||
session->load(*path);
|
||||
host_after_replacement = false;
|
||||
clear_blueprints();
|
||||
placement_message = L"Загружаем поселение…";
|
||||
}
|
||||
std::ifstream stream(*path, std::ios::binary);
|
||||
if (!stream) throw std::runtime_error("Could not open the requested save.");
|
||||
auto loaded = settlement::World::read_save(stream, local_worker_count);
|
||||
if (loaded->width() != map_size || loaded->height() != map_size) {
|
||||
throw std::runtime_error("This viewer opens saves with a 32 by 32 map.");
|
||||
}
|
||||
world = std::move(loaded);
|
||||
clear_blueprints();
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None, L"Поселение загружено.");
|
||||
show_title_screen(window, false);
|
||||
update_status();
|
||||
invalidate_scene(window);
|
||||
} catch (const std::exception& error) {
|
||||
const std::string_view details(error.what());
|
||||
const std::wstring message = std::wstring(saving ? L"Не удалось сохранить поселение.\n" :
|
||||
@@ -1217,14 +1216,15 @@ void show_lan_info(HWND window) {
|
||||
const auto addresses = settlement::viewer::local_lan_addresses();
|
||||
const auto text = L"Передайте другу IPv4 вашего компьютера и код партии.\n\nIPv4: " +
|
||||
(addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) +
|
||||
L"\nКод партии: " + widen_ascii(lan.join_code()) +
|
||||
L"\nПорт TCP: " + std::to_wstring(lan.port()) +
|
||||
L"\nКод партии: " + widen_ascii(lan->join_code()) +
|
||||
L"\nПорт TCP: " + std::to_wstring(lan->port()) +
|
||||
L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться к другу…» в главном меню.";
|
||||
MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION);
|
||||
}
|
||||
|
||||
void refresh_lan_controls(HWND window) {
|
||||
const auto state = lan.state();
|
||||
const auto state = lan->state();
|
||||
if (state != displayed_lan_state) ++lan_generation;
|
||||
displayed_lan_state = state;
|
||||
const bool disconnected = state == LanState::GuestDisconnected;
|
||||
const wchar_t* suffix = L"";
|
||||
@@ -1258,48 +1258,71 @@ void refresh_lan_controls(HWND window) {
|
||||
void handle_lan_menu(HWND window, int command) {
|
||||
if (!showing_title) return;
|
||||
try {
|
||||
if (command == lan_host_id && lan.state() == LanState::Offline) {
|
||||
auto colony = !has_session || !world || !world->scenario_active()
|
||||
? settlement::make_first_colony(local_worker_count) : nullptr;
|
||||
lan.host();
|
||||
if (colony) {
|
||||
world = std::move(colony);
|
||||
clear_blueprints();
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
if (command == lan_host_id && lan->state() == LanState::Offline) {
|
||||
// Modal menus pump loads, so inspect the authoritative publication
|
||||
// here, immediately before any listener or replacement is started.
|
||||
if (!session->can_host_legacy()) {
|
||||
throw std::runtime_error("LAN requires a ready colony with the default rules. Wait for loading to finish.");
|
||||
}
|
||||
const auto current = session->runtime().latest();
|
||||
if (!has_session || !current->world->scenario_active()) {
|
||||
session->new_colony();
|
||||
host_after_replacement = true;
|
||||
clear_blueprints();
|
||||
placement_message = L"Создаём сетевую колонию…";
|
||||
reconcile_ticking();
|
||||
invalidate_scene(window);
|
||||
return;
|
||||
}
|
||||
lan->host();
|
||||
has_session = true;
|
||||
placement_message = L"Сетевая колония открыта. Нажмите «Продолжить», чтобы войти.";
|
||||
refresh_lan_controls(window);
|
||||
show_lan_info(window);
|
||||
return;
|
||||
} else if (command == lan_join_id &&
|
||||
(lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) {
|
||||
(lan->state() == LanState::Offline || lan->state() == LanState::GuestDisconnected)) {
|
||||
const auto request = ask_join_address(window);
|
||||
if (!request) return;
|
||||
if (!world) world = settlement::make_first_colony(local_worker_count);
|
||||
lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
|
||||
// Stage networking first. A rejected address or owner admission must
|
||||
// retain the previous disconnected replica and connection state.
|
||||
auto incoming = std::make_unique<settlement::viewer::LanSession>();
|
||||
incoming->join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
|
||||
session->enter_guest();
|
||||
lan.swap(incoming);
|
||||
guest_intents.clear();
|
||||
world = session->world();
|
||||
host_after_replacement = false;
|
||||
clear_blueprints();
|
||||
enter_game_on_snapshot = true;
|
||||
selected_resident.reset();
|
||||
sync_resident_roster(true);
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None, L"Подключаемся к хозяину…");
|
||||
} else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) {
|
||||
} else if (command == lan_info_id && !lan->is_guest() && lan->state() != LanState::Offline) {
|
||||
show_lan_info(window);
|
||||
return;
|
||||
} else if (command == lan_reconnect_id && lan.state() == LanState::GuestDisconnected) {
|
||||
lan.reconnect();
|
||||
} else if (command == lan_reconnect_id && lan->state() == LanState::GuestDisconnected) {
|
||||
lan->reconnect();
|
||||
enter_game_on_snapshot = true;
|
||||
placement_message = L"Подключаемся к хозяину…";
|
||||
} else if (command == lan_leave_id) {
|
||||
lan.leave();
|
||||
const bool was_guest = lan->is_guest();
|
||||
if (was_guest) session->leave_guest();
|
||||
lan->leave();
|
||||
guest_intents.clear();
|
||||
if (was_guest) {
|
||||
clear_blueprints();
|
||||
world = session->world();
|
||||
}
|
||||
enter_game_on_snapshot = false;
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена.");
|
||||
}
|
||||
refresh_lan_controls(window);
|
||||
reconcile_ticking();
|
||||
} catch (const std::exception& error) {
|
||||
if (session->guest() && !lan->is_guest()) session->leave_guest();
|
||||
const auto text = L"Не удалось выполнить действие.\n" + widen_ascii(error.what());
|
||||
MessageBoxW(window, text.c_str(), L"Кооператив", MB_OK | MB_ICONERROR);
|
||||
}
|
||||
@@ -1316,7 +1339,7 @@ void handle_title_command(HWND window, int command, int notification) {
|
||||
open_coop_menu(window);
|
||||
return;
|
||||
}
|
||||
const bool offline = lan.state() == LanState::Offline;
|
||||
const bool offline = lan->state() == LanState::Offline;
|
||||
if (command == title::title_continue_id && notification == BN_CLICKED && can_resume_session()) {
|
||||
show_title_screen(window, false);
|
||||
refresh_lan_controls(window);
|
||||
@@ -1352,19 +1375,36 @@ const settlement::ResourceNode* berry_source(settlement::GridPosition cell) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
settlement::CommandStatus submit_command(settlement::CommandKind kind, settlement::GridPosition cell,
|
||||
std::uint8_t value, settlement::GridPosition destination = {},
|
||||
settlement::AgentId resident = 0) {
|
||||
if (lan.is_guest()) {
|
||||
return lan.submit(kind, cell, value, destination, resident) ? settlement::CommandStatus::Accepted :
|
||||
settlement::CommandStatus::Unavailable;
|
||||
std::optional<std::uint64_t> enqueue_command(settlement::SessionPayload payload) {
|
||||
if (!can_give_orders()) return std::nullopt;
|
||||
if (lan->is_guest()) {
|
||||
const auto* command = std::get_if<settlement::CommandPayload>(&payload);
|
||||
for (const auto& pending : guest_intents) {
|
||||
if (pending.payload == payload) return pending.command;
|
||||
}
|
||||
if (!command || guest_intents.size() == guest_intent_capacity ||
|
||||
guest_command_id == std::numeric_limits<std::uint64_t>::max()) return std::nullopt;
|
||||
guest_intents.reserve(guest_intents.size() + 1);
|
||||
if (!lan->submit(command->kind, command->cell, command->value, command->destination, command->resident)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto id = ++guest_command_id;
|
||||
guest_intents.push_back({id, session->generation(), std::move(payload)});
|
||||
return id;
|
||||
}
|
||||
constexpr auto host = settlement::colony_host;
|
||||
return world->apply_command({host, world->next_command_sequence(host), kind, cell, value, destination, resident}).status;
|
||||
return session->submit(std::move(payload));
|
||||
}
|
||||
|
||||
bool submit_command(settlement::CommandKind kind, settlement::GridPosition cell,
|
||||
std::uint8_t value, settlement::GridPosition destination = {},
|
||||
settlement::AgentId resident = 0) {
|
||||
const bool queued = enqueue_command(settlement::CommandPayload{kind, cell, value, destination, resident}).has_value();
|
||||
placement_message = queued ? L"Команда ожидает подтверждения…" : L"Очередь занята. Попробуйте ещё раз.";
|
||||
return queued;
|
||||
}
|
||||
|
||||
bool send_command(settlement::CommandKind kind, settlement::GridPosition cell = {}, std::uint8_t value = 0) {
|
||||
return submit_command(kind, cell, value) == settlement::CommandStatus::Accepted;
|
||||
return submit_command(kind, cell, value);
|
||||
}
|
||||
|
||||
bool valid_edit_cell(settlement::GridPosition cell) {
|
||||
@@ -1455,6 +1495,12 @@ void rotate_room_preview(HWND window, int direction) {
|
||||
|
||||
void edit_room_blueprint(HWND window, settlement::GridPosition cell, bool shift) {
|
||||
if (!can_give_orders()) return;
|
||||
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
|
||||
[cell](const auto& pending) { return pending.room && pending.room->contains(cell); })) {
|
||||
placement_message = L"Комната ожидает подтверждения.";
|
||||
invalidate_scene(window);
|
||||
return;
|
||||
}
|
||||
using settlement::RoomSide;
|
||||
if (room_draft_move) {
|
||||
auto& original = room_blueprints[room_draft_move->index];
|
||||
@@ -1534,6 +1580,12 @@ std::optional<settlement::viewer::BlueprintPart> preview_blueprint(settlement::G
|
||||
|
||||
void edit_blueprint(HWND window, settlement::GridPosition cell) {
|
||||
if (!can_give_orders()) return;
|
||||
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
|
||||
[cell](const auto& pending) { return pending.part && pending.part->cell == cell; })) {
|
||||
placement_message = L"Объект ожидает подтверждения.";
|
||||
invalidate_scene(window);
|
||||
return;
|
||||
}
|
||||
if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) {
|
||||
placement_message = L"Объект убран из чертежа.";
|
||||
} else if (const auto part = preview_blueprint(cell);
|
||||
@@ -1552,47 +1604,188 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) {
|
||||
void submit_blueprint(HWND window) {
|
||||
if (!world || !has_blueprint() || room_draft_move || !can_give_orders()) return;
|
||||
using settlement::CommandKind;
|
||||
using settlement::CommandPayload;
|
||||
using settlement::RecipeId;
|
||||
const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) {
|
||||
return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first,
|
||||
room.placement_value(), room.last) == settlement::CommandStatus::Accepted;
|
||||
});
|
||||
const auto objects_sent = std::erase_if(blueprint, [](const auto& part) {
|
||||
const auto queue = [&](settlement::SessionPayload payload, std::optional<settlement::RoomPlan> room,
|
||||
std::optional<settlement::viewer::BlueprintPart> part) {
|
||||
if (std::any_of(pending_drafts.begin(), pending_drafts.end(),
|
||||
[&](const auto& pending) { return pending.payload == payload; })) return;
|
||||
pending_drafts.reserve(pending_drafts.size() + 1);
|
||||
if (const auto id = enqueue_command(payload)) {
|
||||
pending_drafts.push_back({*id, draft_revision, std::move(payload), room, part, lan->is_guest()});
|
||||
}
|
||||
};
|
||||
for (const auto& room : room_blueprints) {
|
||||
if (world->can_place_room(room)) {
|
||||
queue(CommandPayload{CommandKind::PlaceRoom, room.first, room.placement_value(), room.last}, room, {});
|
||||
}
|
||||
}
|
||||
for (const auto& part : blueprint) {
|
||||
switch (part.recipe) {
|
||||
case RecipeId::BuildBed:
|
||||
return world->can_place_bed(part.cell) &&
|
||||
send_command(CommandKind::PlaceBed, part.cell, static_cast<std::uint8_t>(part.base));
|
||||
case RecipeId::WeaveCloth:
|
||||
return world->can_place_storage(part.cell) && send_command(CommandKind::PlaceLoom, part.cell);
|
||||
case RecipeId::BuildCabin:
|
||||
try {
|
||||
world->queue_cabin(part.cell, sawmill, stonecutter);
|
||||
return true;
|
||||
} catch (const std::invalid_argument&) {
|
||||
return false;
|
||||
if (world->can_place_bed(part.cell)) {
|
||||
queue(CommandPayload{CommandKind::PlaceBed, part.cell, static_cast<std::uint8_t>(part.base)}, {}, part);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
break;
|
||||
case RecipeId::WeaveCloth:
|
||||
if (world->can_place_storage(part.cell)) queue(CommandPayload{CommandKind::PlaceLoom, part.cell}, {}, part);
|
||||
break;
|
||||
case RecipeId::BuildCabin:
|
||||
queue(settlement::LegacyCabinPayload{part.cell, sawmill, stonecutter}, {}, part);
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
placement_message = pending_drafts.empty() ? L"Проверьте свободные клетки и доступ к площадке." :
|
||||
L"Ожидают подтверждения мест: " + std::to_wstring(pending_drafts.size()) + L".";
|
||||
update_blueprint_controls(window);
|
||||
invalidate_scene(window);
|
||||
}
|
||||
|
||||
void complete_command(std::uint64_t id, const settlement::SessionPayload& payload,
|
||||
settlement::CommandStatus status, bool guest) {
|
||||
const bool accepted = status == settlement::CommandStatus::Accepted;
|
||||
auto pending = std::find_if(pending_drafts.begin(), pending_drafts.end(), [&](const auto& entry) {
|
||||
return entry.guest == guest && entry.command == id;
|
||||
});
|
||||
const std::wstring count = std::to_wstring(rooms_sent + objects_sent);
|
||||
if (has_blueprint()) {
|
||||
placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " +
|
||||
std::to_wstring(blueprint.size() + room_blueprints.size()) +
|
||||
(lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." :
|
||||
L". Проверьте, свободны ли клетки и есть ли к ним проход.");
|
||||
if (pending != pending_drafts.end()) {
|
||||
if (accepted && pending->revision == draft_revision) {
|
||||
if (pending->room) {
|
||||
const auto room = *pending->room;
|
||||
const auto removed = std::find_if(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) {
|
||||
return other.first == room.first && other.last == room.last &&
|
||||
other.entrance == room.entrance && other.layout == room.layout;
|
||||
});
|
||||
if (removed != room_blueprints.end()) {
|
||||
const auto index = static_cast<std::size_t>(removed - room_blueprints.begin());
|
||||
if (room_draft_move) {
|
||||
if (room_draft_move->index == index) room_draft_move.reset();
|
||||
else if (room_draft_move->index > index) --room_draft_move->index;
|
||||
}
|
||||
room_blueprints.erase(removed);
|
||||
}
|
||||
}
|
||||
if (pending->part) {
|
||||
const auto part = *pending->part;
|
||||
std::erase_if(blueprint, [&](const auto& other) {
|
||||
return other.cell == part.cell && other.recipe == part.recipe && other.base == part.base;
|
||||
});
|
||||
}
|
||||
}
|
||||
pending_drafts.erase(pending);
|
||||
}
|
||||
if (accepted) {
|
||||
placement_message = L"Команда выполнена.";
|
||||
if (const auto* command = std::get_if<settlement::CommandPayload>(&payload)) {
|
||||
if (command->kind == settlement::CommandKind::MoveObject && move_source == command->cell) {
|
||||
move_source.reset();
|
||||
}
|
||||
if (command->kind == settlement::CommandKind::AssignProfession && selected_resident == command->resident &&
|
||||
roster.pending_role == static_cast<Profession>(command->value)) {
|
||||
roster.pending_role.reset();
|
||||
if (roster.notice) SetWindowTextW(roster.notice, L"Профессия назначена. Житель закончит поручение.");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L".";
|
||||
placement_message = status == settlement::CommandStatus::Busy
|
||||
? L"Объект занят. Дождитесь окончания работы или сна."
|
||||
: L"Команда отклонена. Проверьте клетку и доступ к ней. Чертёж сохранён.";
|
||||
}
|
||||
if (rooms_sent != 0 && world->scenario_active() && !has_carpenter()) {
|
||||
placement_message += L" Деревянные двери изготавливает плотник. Его можно назначить в списке «Жители».";
|
||||
}
|
||||
|
||||
void reconcile_ticking() {
|
||||
if (!session) return;
|
||||
const bool network_host = lan->state() == LanState::Hosting || lan->state() == LanState::HostConnected;
|
||||
session->set_ticking(!lan->is_guest() && !file_dialog_active &&
|
||||
(network_host || (has_session && !showing_title && !pause_menu_open)));
|
||||
}
|
||||
|
||||
void pump_session(HWND window) {
|
||||
static bool pumping = false;
|
||||
if (!session || pumping) return;
|
||||
pumping = true;
|
||||
struct Finish { ~Finish() { pumping = false; } } finish;
|
||||
reconcile_ticking();
|
||||
auto events = session->poll();
|
||||
if (lan->is_guest()) {
|
||||
if (auto incoming = lan->poll_guest()) {
|
||||
session->receive_guest(std::move(incoming));
|
||||
has_session = true;
|
||||
}
|
||||
} else if (lan->state() != LanState::Offline) {
|
||||
lan->poll_host(session->runtime());
|
||||
}
|
||||
world = session->world();
|
||||
for (const auto& event : events) {
|
||||
switch (event.kind) {
|
||||
case settlement::viewer::ViewerEventKind::Replaced:
|
||||
clear_blueprints();
|
||||
camera = {};
|
||||
selected_resident.reset();
|
||||
has_session = true;
|
||||
set_work_panel(window, WorkPanel::None);
|
||||
set_placement_mode(window, PlacementMode::None, L"Поселение готово.");
|
||||
if (std::exchange(host_after_replacement, false)) {
|
||||
if (lan->state() == LanState::Offline && session->can_host_legacy()) {
|
||||
lan->host();
|
||||
placement_message = L"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
|
||||
} else {
|
||||
placement_message = L"Кооператив требует готовую колонию со стандартными правилами.";
|
||||
}
|
||||
} else {
|
||||
show_title_screen(window, false);
|
||||
}
|
||||
sync_resident_roster(true);
|
||||
refresh_lan_controls(window);
|
||||
break;
|
||||
case settlement::viewer::ViewerEventKind::Command:
|
||||
if (event.payload) complete_command(event.command, *event.payload, event.status, false);
|
||||
break;
|
||||
case settlement::viewer::ViewerEventKind::Saved:
|
||||
placement_message = L"Поселение сохранено.";
|
||||
if (showing_title) title_screen.reload_saves();
|
||||
break;
|
||||
case settlement::viewer::ViewerEventKind::Fault:
|
||||
case settlement::viewer::ViewerEventKind::Error:
|
||||
host_after_replacement = false;
|
||||
placement_message = widen_ascii(event.message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (const auto result = lan->take_result()) {
|
||||
const settlement::SessionPayload payload = settlement::CommandPayload{result->kind, result->cell,
|
||||
result->value, result->destination, result->resident};
|
||||
if (!guest_intents.empty()) {
|
||||
const auto intent = std::move(guest_intents.front());
|
||||
guest_intents.erase(guest_intents.begin());
|
||||
if (intent.generation == session->generation() && intent.payload == payload) {
|
||||
complete_command(intent.command, payload, result->status, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (showing_title && enter_game_on_snapshot && !coop_menu_open &&
|
||||
lan->state() == LanState::GuestConnected && world) show_title_screen(window, false);
|
||||
if (lan->state() != displayed_lan_state) {
|
||||
if (lan->state() == LanState::GuestDisconnected) {
|
||||
pending_drafts.clear();
|
||||
guest_intents.clear();
|
||||
}
|
||||
refresh_lan_controls(window);
|
||||
}
|
||||
if (world) sync_resident_roster();
|
||||
update_blueprint_controls(window);
|
||||
update_status();
|
||||
reconcile_ticking();
|
||||
invalidate_scene(window);
|
||||
}
|
||||
|
||||
void edit_at_cell(HWND window, settlement::GridPosition cell) {
|
||||
if (!can_give_orders()) return;
|
||||
const auto held_world = world;
|
||||
const auto generation = session->generation();
|
||||
const auto installed_session = session->runtime().latest()->identity.session;
|
||||
const auto network_generation = lan_generation;
|
||||
const auto* connection = lan.get();
|
||||
using settlement::CommandKind;
|
||||
using settlement::CommandStatus;
|
||||
using settlement::StorageKind;
|
||||
@@ -1625,6 +1818,9 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) {
|
||||
world->object_status(cell, false) == CommandStatus::Accepted &&
|
||||
MessageBoxW(window, L"Снести склад вместе с его запасами?", L"Снос склада",
|
||||
MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) != IDYES) return;
|
||||
if (generation != session->generation() ||
|
||||
installed_session != session->runtime().latest()->identity.session ||
|
||||
network_generation != lan_generation || connection != lan.get() || !can_give_orders()) return;
|
||||
} else if (placement_mode == PlacementMode::BerryField) {
|
||||
command = CommandKind::PlaceBerryField;
|
||||
} else if (placement_mode == PlacementMode::FlaxField) {
|
||||
@@ -1639,17 +1835,8 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) {
|
||||
StorageKind::Materials);
|
||||
}
|
||||
|
||||
const auto result = submit_command(command, source, value, destination);
|
||||
if (result == CommandStatus::Accepted) {
|
||||
move_source.reset();
|
||||
placement_message = lan.is_guest() ? L"Команда отправлена хозяину." : L"Готово.";
|
||||
} else if (result == CommandStatus::Busy) {
|
||||
placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна.";
|
||||
} else {
|
||||
if (command == CommandKind::MoveObject && world->object_status(source, true) != CommandStatus::Accepted) {
|
||||
move_source.reset();
|
||||
}
|
||||
placement_message = L"Действие недоступно для выбранной клетки.";
|
||||
if (submit_command(command, source, value, destination)) {
|
||||
placement_message = L"Команда ожидает подтверждения…";
|
||||
}
|
||||
update_status();
|
||||
invalidate_scene(window);
|
||||
@@ -1671,22 +1858,17 @@ HMENU create_work_menu() {
|
||||
void apply_resident_role(HWND owner) {
|
||||
const auto* resident = selected_agent();
|
||||
if (!resident || !roster.pending_role || *roster.pending_role == resident->profession || !can_give_orders()) return;
|
||||
using settlement::CommandStatus;
|
||||
const auto result = submit_command(settlement::CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(*roster.pending_role), {}, resident->id);
|
||||
if (result == CommandStatus::Accepted) {
|
||||
roster.pending_role.reset();
|
||||
SetWindowTextW(roster.notice, lan.is_guest() ? L"Назначение отправлено хозяину." :
|
||||
L"Профессия назначена. Житель закончит текущее поручение.");
|
||||
} else {
|
||||
SetWindowTextW(roster.notice, L"Не удалось назначить профессию.");
|
||||
}
|
||||
const bool queued = submit_command(settlement::CommandKind::AssignProfession, {},
|
||||
static_cast<std::uint8_t>(*roster.pending_role), {}, resident->id);
|
||||
SetWindowTextW(roster.notice, queued ? L"Назначение ожидает подтверждения…" : L"Очередь занята.");
|
||||
sync_resident_roster();
|
||||
update_roster_details();
|
||||
invalidate_scene(owner);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
const auto held_world = world;
|
||||
try {
|
||||
const auto owner = GetWindow(window, GW_OWNER);
|
||||
switch (message) {
|
||||
case WM_CREATE: {
|
||||
@@ -1797,6 +1979,14 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, wparam, lparam);
|
||||
} catch (const std::exception& error) {
|
||||
placement_message = widen_ascii(error.what());
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
} catch (...) {
|
||||
placement_message = L"Не удалось выполнить действие.";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void show_resident_roster(HWND owner) {
|
||||
@@ -1879,8 +2069,8 @@ std::wstring resident_details() {
|
||||
profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%";
|
||||
if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой";
|
||||
else if (resident->state == settlement::AgentState::Eating) text += L" Ест";
|
||||
else if (resident->production_index != settlement::no_entity_index &&
|
||||
settlement::is_carpentry_recipe(world->production_orders()[resident->production_index].recipe)) {
|
||||
else if (world->find_production(resident->production_id) != nullptr &&
|
||||
settlement::is_carpentry_recipe(world->find_production(resident->production_id)->recipe)) {
|
||||
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
|
||||
L" Везёт материалы в мастерскую";
|
||||
}
|
||||
@@ -2026,7 +2216,8 @@ void draw_world(HDC dc, int width, int height) {
|
||||
DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
|
||||
auto details = has_blueprint() ? blueprint_details() :
|
||||
selected_room_template != settlement::RoomTemplate::Empty
|
||||
? std::wstring(house_contents[static_cast<std::size_t>(selected_room_template) - 1])
|
||||
? std::wstring((world->staged_beds() ? house_contents : simple_house_contents)
|
||||
[static_cast<std::size_t>(selected_room_template) - 1])
|
||||
: resident_details();
|
||||
if (work_panel == WorkPanel::Carpenter) {
|
||||
const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(),
|
||||
@@ -2078,6 +2269,8 @@ settlement::viewer::SceneView scene_view(int width, int height) {
|
||||
}
|
||||
|
||||
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
const auto held_world = world;
|
||||
try {
|
||||
if (message == WM_NCHITTEST) return HTTRANSPARENT;
|
||||
if (message == WM_ERASEBKGND) return 1;
|
||||
if (message == WM_PAINT) {
|
||||
@@ -2098,6 +2291,14 @@ LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPA
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, wparam, lparam);
|
||||
} catch (const std::exception& error) {
|
||||
placement_message = widen_ascii(error.what());
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
} catch (...) {
|
||||
placement_message = L"Не удалось выполнить действие.";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct MenuAction {
|
||||
@@ -2248,17 +2449,18 @@ void open_pause_menu(HWND window) {
|
||||
if (!world || showing_title || pause_menu_open) return;
|
||||
camera_drag.reset();
|
||||
if (GetCapture() == window) ReleaseCapture();
|
||||
const bool offline = lan.state() == LanState::Offline;
|
||||
const bool offline = lan->state() == LanState::Offline;
|
||||
const auto interface_caption = L"Масштаб панели · " + std::to_wstring(interface_scale) + L"%…";
|
||||
const MenuAction actions[] = {
|
||||
{IDOK, L"Продолжить"},
|
||||
{save_menu_id, L"Сохранить поселение…", !lan.is_guest()},
|
||||
{save_menu_id, L"Сохранить поселение…", !lan->is_guest()},
|
||||
{load_menu_id, L"Загрузить поселение…", offline},
|
||||
{interface_scale_id, interface_caption.c_str()},
|
||||
{title_menu_id, L"Главное меню"},
|
||||
{exit_menu_id, L"Выйти из игры"},
|
||||
};
|
||||
pause_menu_open = true;
|
||||
reconcile_ticking();
|
||||
const auto action = choose_menu_action(window, offline ? L"Меню паузы" : L"Меню игры", actions);
|
||||
switch (action) {
|
||||
case IDOK:
|
||||
@@ -2282,12 +2484,13 @@ void open_pause_menu(HWND window) {
|
||||
break;
|
||||
}
|
||||
pause_menu_open = false;
|
||||
reconcile_ticking();
|
||||
if (IsWindow(window)) SetFocus(window);
|
||||
}
|
||||
|
||||
void open_coop_menu(HWND window) {
|
||||
std::vector<MenuAction> actions;
|
||||
switch (lan.state()) {
|
||||
switch (lan->state()) {
|
||||
case LanState::Offline:
|
||||
actions.push_back({lan_host_id, has_session && world && world->scenario_active()
|
||||
? L"Открыть текущую колонию для друга…" : L"Создать сетевую колонию…"});
|
||||
@@ -2315,10 +2518,9 @@ void open_coop_menu(HWND window) {
|
||||
const auto action = choose_menu_action(window, L"Кооператив", actions);
|
||||
coop_menu_open = false;
|
||||
if (action == pause_button_id &&
|
||||
(lan.state() == LanState::Hosting || lan.state() == LanState::HostConnected)) {
|
||||
(lan->state() == LanState::Hosting || lan->state() == LanState::HostConnected)) {
|
||||
static_cast<void>(send_command(settlement::CommandKind::SetPaused, {},
|
||||
static_cast<std::uint8_t>(!world->paused())));
|
||||
placement_message = world->paused() ? L"Сетевая колония на паузе." : L"Сетевая колония продолжает работу.";
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
} else if (action >= lan_host_id && action <= lan_leave_id) {
|
||||
handle_lan_menu(window, action);
|
||||
@@ -2326,6 +2528,8 @@ void open_coop_menu(HWND window) {
|
||||
}
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
const auto held_world = world;
|
||||
try {
|
||||
switch (message) {
|
||||
case WM_GETMINMAXINFO: {
|
||||
auto& size = *reinterpret_cast<MINMAXINFO*>(lparam);
|
||||
@@ -2447,11 +2651,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
world && world->carpenter_workshop() && can_give_orders()) {
|
||||
const bool is_furniture_order = LOWORD(wparam) != craft_door_id;
|
||||
const int furniture_index = static_cast<int>(LOWORD(wparam)) - first_furniture_craft_id;
|
||||
const bool accepted = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {},
|
||||
const bool queued = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {},
|
||||
static_cast<std::uint8_t>(furniture_products[static_cast<std::size_t>(furniture_index)])) :
|
||||
send_command(settlement::CommandKind::CraftDoor);
|
||||
if (accepted) {
|
||||
placement_message = lan.is_guest() ? L"Заказ отправлен хозяину." : L"Заказ принят мастерской.";
|
||||
if (queued) {
|
||||
placement_message = L"Заказ ожидает подтверждения…";
|
||||
}
|
||||
SetFocus(window);
|
||||
invalidate_scene(window);
|
||||
@@ -2469,12 +2673,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
HIWORD(wparam) == BN_CLICKED) {
|
||||
const auto choices = work_choices();
|
||||
const auto index = static_cast<std::size_t>(LOWORD(wparam) - first_work_choice_id);
|
||||
if (index >= choices.size() || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0;
|
||||
if (index >= choices.size() || (lan->is_guest() && lan->state() != LanState::GuestConnected)) return 0;
|
||||
SendMessageW(window, WM_COMMAND, static_cast<WPARAM>(choices[index].command), 0);
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) >= berry_field_id && LOWORD(wparam) <= demolish_id) {
|
||||
if (!world || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0;
|
||||
if (!world || (lan->is_guest() && lan->state() != LanState::GuestConnected)) return 0;
|
||||
constexpr PlacementMode modes[] = {PlacementMode::BerryField, PlacementMode::TreePlot,
|
||||
PlacementMode::Mine, PlacementMode::Storage, PlacementMode::Pantry, PlacementMode::Move,
|
||||
PlacementMode::Demolish};
|
||||
@@ -2549,7 +2753,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) == forage_action_id && HIWORD(wparam) == BN_CLICKED && world &&
|
||||
(!lan.is_guest() || lan.state() == LanState::GuestConnected)) {
|
||||
(!lan->is_guest() || lan->state() == LanState::GuestConnected)) {
|
||||
set_placement_mode(window, placement_mode == PlacementMode::Foraging ?
|
||||
PlacementMode::None : PlacementMode::Foraging);
|
||||
SetFocus(window);
|
||||
@@ -2728,49 +2932,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
}
|
||||
break;
|
||||
case WM_TIMER:
|
||||
if (wparam == timer_id && world) {
|
||||
const auto state = lan.state();
|
||||
if (showing_title && (state == LanState::Offline || state == LanState::GuestDisconnected)) return 0;
|
||||
if (!file_dialog_active && !lan.is_guest() &&
|
||||
(state != LanState::Offline || (!showing_title && !pause_menu_open))) world->step();
|
||||
if (auto snapshot = lan.poll(*world)) {
|
||||
world = std::move(snapshot);
|
||||
has_session = true;
|
||||
}
|
||||
if (showing_title && enter_game_on_snapshot && !coop_menu_open && lan.state() == LanState::GuestConnected) {
|
||||
show_title_screen(window, false);
|
||||
}
|
||||
sync_resident_roster();
|
||||
if (lan.state() != displayed_lan_state) refresh_lan_controls(window);
|
||||
if (const auto rejection = lan.take_rejection()) {
|
||||
using settlement::CommandKind;
|
||||
using settlement::RecipeId;
|
||||
const bool bed = rejection->kind == CommandKind::PlaceBed;
|
||||
if (rejection->kind == CommandKind::PlaceRoom) {
|
||||
const auto room = settlement::RoomPlan::from_placement(
|
||||
rejection->cell, rejection->destination, rejection->value);
|
||||
if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(),
|
||||
[&](const auto& other) { return other.first == room.first && other.last == room.last; })) {
|
||||
room_blueprints.push_back(room);
|
||||
update_blueprint_controls(window);
|
||||
}
|
||||
placement_message = L"Хозяин отклонил площадку. Комната возвращена в чертёж.";
|
||||
} else if (bed || rejection->kind == CommandKind::PlaceLoom) {
|
||||
if (std::none_of(blueprint.begin(), blueprint.end(),
|
||||
[&](const auto& part) { return part.cell == rejection->cell; })) {
|
||||
blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth,
|
||||
static_cast<settlement::BedBase>(rejection->value)});
|
||||
update_blueprint_controls(window);
|
||||
}
|
||||
placement_message = L"Клетка отклонена хозяином и оставлена в чертеже.";
|
||||
} else {
|
||||
placement_message = rejection->status == settlement::CommandStatus::Busy
|
||||
? L"Объект занят. Дождитесь окончания работы или сна."
|
||||
: L"Хозяин отклонил команду. Проверьте выбранную клетку.";
|
||||
}
|
||||
}
|
||||
update_status();
|
||||
invalidate_scene(window);
|
||||
if (wparam == timer_id) {
|
||||
pump_session(window);
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
@@ -2809,7 +2972,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
}
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, timer_id);
|
||||
lan.leave();
|
||||
lan->leave();
|
||||
graphics.reset();
|
||||
if (dock_font) DeleteObject(std::exchange(dock_font, nullptr));
|
||||
scene_window = nullptr;
|
||||
@@ -2817,11 +2980,26 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(window, message, wparam, lparam);
|
||||
} catch (const std::exception& error) {
|
||||
placement_message = widen_ascii(error.what());
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
} catch (...) {
|
||||
placement_message = L"Не удалось выполнить действие.";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
try {
|
||||
session = std::make_unique<settlement::viewer::ViewerSession>(local_worker_count);
|
||||
} catch (const std::exception& error) {
|
||||
const auto text = widen_ascii(error.what());
|
||||
MessageBoxW(nullptr, text.c_str(), L"Не удалось открыть поселение", MB_OK | MB_ICONERROR);
|
||||
return 1;
|
||||
}
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
WNDCLASSEXW window_class_info{};
|
||||
@@ -2852,5 +3030,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
session.reset();
|
||||
return static_cast<int>(message.wParam);
|
||||
}
|
||||
@@ -87,3 +87,9 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
|
||||
В `cf0cc2f` объединены проверенные коммиты S19 `de38aff` и S01 `68f91a2`. После объединения под Wine 11 прошли 51 из 51 теста ядра и 4 из 4 тестов LAN, включая формат сохранений 13 и протокол 11. Независимый проверяющий сверил обе родительские версии, наследование параметров компиляции и встроенную реализацию SHA-256. [План владельца симуляции](tasks/M01-P2.md) · [Проверка библиотеки](tasks/M01-R2.md) · [Разбор отказов](tasks/M01-F2.md) · [Принятые контракты](tasks/M01-F3.md) · [Проверка S01 и S19](tasks/M01-V2.md) · [Проверка интеграции](tasks/M01-V3.md)
|
||||
|
||||
Срез S06 сохранил ссылки на склады и источники при удалении более раннего элемента. Два контрольных набора из 738 386 и 393 857 байтов совпали со старой сборкой в последовательном режиме и на 2/6/12 потоках. Второй набор включает разбор склада во время многоэтапной доставки. Изменения опубликованы отдельно в [S06 #11](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11). В `4ba64f7` также вошла фоновая подготовка старых и новых сохранений. В объединённой Windows x64-сборке под Wine прошли 106 тестов ядра и 4 LAN. Публичный аналог ограниченного чтения в Windows отслеживается в [Void/Library #9](https://git.faumaray.com/Void/Library/issues/9). [Проверка двух компонентов](tasks/M01-V8.md) · [Интеграционная проверка](tasks/M01-V9.md)
|
||||
|
||||
Хост протокола 11 теперь передаёт приказы авторитетной симуляции, а гость получает подтверждение и снимок завершённого состояния. После смены сеанса старому гостю требуется новое подключение. Старая и новая сборки обменялись приказами в обеих ролях. В `aa4e271` под Wine прошли 106 из 106 тестов ядра и 9 из 9 LAN. Отдельно проверены переподключение при незавершённом приказе и разные правила нумерации отклонённых приказов у старого клиента и нового владельца. [Ветка S16](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/9) · [Проверка интеграции](tasks/M01-V10.md)
|
||||
|
||||
В `a8cd7bb` объединены заказы с постоянными ID и два варианта правил строительства кровати. Формат контрольной точки 2 сохраняет ID заказов и следующий свободный ID. Прежние контрольные точки и обычные сохранения версии 13 продолжают загружаться. Оба варианта правил прошли строительство реальных кроватей, сохранение во время доставки и сравнение продолжений на 1/2/6/12 исполнителях. В объединённой сборке под Wine прошли 122 теста ядра и 9 LAN. Аппаратная Windows ещё не проверена. [Заказы S04](../plan/systems/S04.md) · [Правила S19](../plan/systems/S19.md) · [Интеграционная проверка](tasks/M01-V11.md)
|
||||
|
||||
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Recheck production identity safety and preflight a selectable colony rule
|
||||
|
||||
Task ID: M01-F6
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root at 60154bd. S04-01 contract in s04 checkout (4ba64f7) includes the two M01-V9 findings. In S19 M01-P4 examines new world profile selection reusing existing simple vs staged bed paths. Default built-in manifest content must remain compatible.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Immediately recheck S04 exact guards and, separately, preflight the first selectable rules behavior with a validated default/legacy compatibility policy. No actual code review or implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only S04-01 revised contract and S19 feature preflight. Exclude further stack/transfer/production implementation.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect s04/docs/agent-workflow/tasks/S04-01.md sections 6–10 and World::edit_object/CommandDispatcher::apply. For S19 read M01-P4, world.cpp bed construction, legacy codec/staged flag, generator/first_colony, rules_manifest, runtime/file/load and default-only LAN contracts. Implementation worktrees outside main have direct read evidence.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote writes/branch ops/children or shared Serena activation. Other workers continue on their own files.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S04 confirm hypothetical exhaustion guards precompute post-demolition totals exactly across all affected supplies before erasing or queue changes, preserve accepted receipt semantics for proved cabin preflight Busy separately from mutation faults. Genuine v1/body1–13 and current2/14 mapping, negative checks and older file test version. Send scoped approval immediately if corrected.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S19 proposal: compiled default first-colony behavior stays staged recipes and two-package original frozen manifest, content digest unchanged; optional exact pinned, additive package selects existing simple/plank recipe path at world creation. Encode enacted policy in World at initialization, existing staged_beds state and manifest saved, normal creation can choose default/alternative. Add game-specific supported profile compiler using actual typed data and package closure; reject unsupported modified digest before installation by viewer, generic resolver/decoder retains broad catalog tools behavior. Important: previous v1 checkpoints and imported historical worlds could legitimately carry DEFAULT manifest with staged_beds=false, and inactive world is valid. Describe migration rule that preserves these old states/bytes; distinguish strict alternate invariant from accepted old default data, and verify clean subsequent saves on current envelope. Future S19/UI APIs and compatibility choices from M01-P4 confirmed by root prior to implementation.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
S04 and S19 can use isolated branches; parent serializes shared World/factory/file semantics and S18 normal UI selector after core approval. Keep legacy LAN default-profile-only and preserve old default digest/test fixtures. Do not equate illustrative board ticks=8 with actual compiled tick count.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check nonempty real colony resources/producer/receipt for both bed paths, UI stone vs wood selection, immutable held snapshot and save-load continuation, partial bed materials, old format 1–13 valid imports, malformed optional profile/default unknown package gate, credible negative tests. No fabricated ACE parity.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate S04 corrected or material outstanding. 2. S19 preflight verdict with explicit compatibility and required exact negative/normal tests. 3. Record what can proceed with certainty and facts needing further root commitment.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read actual source/contract targets and M01-P4; compare default manifests/code and World legacy flags; no build required. Check git status/refs to identify exact code.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Read only. Return S04 verdict immediately then S19. No new external service or changes to accepted user scope.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root requests follow-up after exact S04 corrections and planner-backed S19 technical preflight. User authorizes signed-off coding only through root.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F6 two scoped verdicts with evidence, precise blockers/solutions and pending real integration tests.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Check the contract for atomic reserved pickups and client rule selection
|
||||
|
||||
Task ID: M01-F7
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
M01 parent 9a248c3 has S19-02 compiled profile and S06-ID data. S04-01 adds production identities and body14 in isolated s04. S18-01 canonical client still in isolated s18 resolving modal input findings. M01-P5 proposed a bounded reserved-quantity pickup used by actual meal and construction stops.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Preflight the first S06 quantity transaction and bounded S18 followup that wires approved profile to the New/Load/Host UI. Return separate actionable corrections before component implementation.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
The S06 step preflights a single existing storage→resident pickup atomically, including all materials at one construction stop. Later stack identity, cancel, site ownership and replay ledger remain P5-dependent. S18 selection is only New colony and coherent support/legacy compatibility; no new game settings or traffic.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root world.hpp, world.cpp functions finish_meal_step/advance_construction_delivery/take_reserved_material/finish_production, profile public API/first_colony/tests, s04 working diff and actual s18 viewer_session/viewer_win32/title_screen, LAN default gate, docs S04/S06/S18/S19 and M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posts/other agents or Serena switch. Root decides subsequent contracts and serializes worktrees/CMake changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S06 proposed NEW internal bounded reserved pickup with one validated StorageId per operation, max item_type_count distinct items (all lines at stop aggregated before any mutation), reject zero/None/unknown ID, reserved>physical, insufficient reserved/quantity or target sum overflow using Void::Numeric; commit all source counts/reserve/zero-stack removal/destination changes without further allocation or throwable effects. Success keeps meal, route cursor, order/worker behavior and v13 projection/corpora unchanged. Failure immediately leaves source+inventory and stop/actor bookkeeping unchanged; impossible invariant failure may fault owner while preserving last healthy publication. Existing non-pickup recipe paths must be accounted for. Identify any missing edge or side effect.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S18 followup proposed initial selector defaults staged, allows existing alternative single plank profile in title New, Continue/Open ignores current selection; factory+validator before runtime construct and after latest load prepared, preserve exact default old simple/inactive, refuse forged/extra or optional staged, both immediate and deferred legacy-host gates require exact default, failed admission leaves world/guest unchanged. Rename/conditionally hide staged base UI choices in plank-only worlds; confirm existing placement validation behavior. Verify title keyboard/mouse handling and no accidental persisted settings.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Depends on S19-02 and S18-01 review, S06-02 first consumer should merge after S04-01 with tests and version untouched. Root will own separate follow-up schema migration and M01-P5 final decisions; legacy cancellation compatibility remains.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check non-throwing commit including vector erase/multi-type and destination Inventory bounds, zeros/duplicates, capacity reserve for carpentry and any work cursor mutation. Check modal callbacks/error feedback, unsupported profiles advertised to LAN, save/restore exact active legacy mode.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per contract before dispatch. 2. Concrete trigger and correction for any inconsistency. 3. Exact tests that would fail on a partial batch and incorrect selection or post-load gate. The stages do not approve future implementation.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse at each worktree, scoped rg and direct source/graph coverage. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{tag,ctest}.log and existing client-session/GUI smoke source if needed. No new builds.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No new general inventory database, domain mechanics or UI expansion, no duplicate library issues. Report prerequisites immediately; defer review of actual changes until implemented. No charges/remote operations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, including stable single-owner items, selectable new rules, per-branch publishing and generic Void issues. Root retains mutation authority.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-F7 PREFLIGHT disposition for S06 and S18 separately; exact invariants/tests and any blocking oversight backed by existing source.
|
||||
|
||||
Preflight required the pickup owner to validate the post-withdrawal occupancy and the carpentry output slot together, aggregate repeated lines, and preserve the state at pickup entry on rejection. Direct storage-to-recipe conversion keeps its own path. For profile selection, deny starting a legacy host while a replacement is pending, recheck after a modal menu, then check the installed authoritative default manifest immediately before either host call. The simple-bed house preview must describe the actual one-plank recipe for every house type.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Specify the first authoritative inventory and transfer operations
|
||||
|
||||
Task ID: M01-P5
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root M01 2a5df1a. S06 IDs 8260e09 are integrated. The developing S04-01 converts production orders/agent links to ProductionId, current save body14/outer2 and typed legacy import. Previous M01-P3 mapped object domains, but actual quantities still live in storage/resident representations and construction drops cargo on arrival. This is the detailed technical handoff for M01.2.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Freeze a small end-to-end migration for S06-02 and S04-02 with exact authoritative ownership, identity allocation, operations and backward projection. Suggest genuinely independent implementation segments that can be dispatched before large World edits.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Focus on objects/recipes already present, order-reservations/haul/consumption/cancel/demolition, no new gameplay, extra protocols, catalog or general database. Domain-level transfer retry/retention must have explicit bounds.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root docs/plan/systems/{S04,S06}.md, M01, M01-P3, engine/include/settlement/core/world.hpp and actual Inventory/Storage definitions, engine/src/world{,_save}.cpp plus tests for logistics/production/replay and resource/food handling. Inspect s04 worktree public diff for actual ProductionId and NEW current14 schema; never modify it. Review pinned Void Numeric, upstream #7/#8 linked in docs/plan/void-library.md.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switches or children. Parent owns root/remote and serializes World/codec ownership. Work from actual source and verified graph coverage.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Trace every quantity introduction, split/move, take_reserved_material, pickup, in-transit cancellation, construction worksite arrival/delivery, consumption, eating, storage demolition and factory stock. Identify minimum source of truth. Design checked before-effect atomic operations, stable nonzero StackId by world, one current owner per stack, explicit material balance opening/sink, exact held amounts, and reliable projection to old fields. Avoid persisting parallel quantity ledgers without enforced consistency. Characterize active/inactive imported orders to preserve v1–14 continuation, including mid-site delivery. Product keeps pre-existing demolition's removal of stock and records its amount/reason.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Give exact proposed NEW operation types, identities/high-water constraints, on-disk version steps, and API surfaces for S04 claims vs S06 actual stock. Pin behavior on outcomes AlreadyApplied/Duplicate/Conflict/Busy and stale retries even after bounded receipt retention and save/load, deterministic order vs multi-actor concurrency. Name genuine policy questions; choose bounded defaults for reversible design.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
An independently testable ledger module before World integration may be parallel if it has a real consuming path and fixed grounded seam. S04-01 must integrate first for worksite references, and S19 touches only scenario setup. Summarize actual changes needed in UI for preserving displayed amounts.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound memory by current existing file/collection capacities, handle zero and uint64/int quantity overflow, reserve IDs without partial mutation including splits/exhaustion, owner removal after pickup, no-free-space redirects, capacity races, negative/cross-owner dangling state, and loaded modern wrong digest. Avoid quadratic hot paths; identify realistic measurement checks.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Source-grounded transition and migration tables; 2. First independently deliverable task with exact scope and tests that leads to real stock; 3. Subsequent isolated work packages with complete modern migration path; 4. Leverage correct Void utilities and #7/#8 where adequate; 5. Declare present limits in legacy raw13/network11 projection.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD, actual scoped rg -n on add_item, take_reserved_material, advance_construction_delivery, finish_production, reserved_slots, item inventory and stock, scoped current/load/save comparisons, local Void pin as needed. Check graph identity/coverage for relied-on root code; isolated s04 working diff uses direct reads. No compilation required.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first technical seam early, then full report. Do not assign new IDs by vector position, silently destroy cargo on cancel, break legacy binary projections or start new worktrees/remote Git. If uncertainty materially changes the product scope, identify the specific branch and continue other evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Approved M01 hard requirements and earlier planner M01-P3 permit this focused design of actual custody. Root decides integration order and product-preserving defaults. No release or merge to main.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P5 READY/PARTIAL, exact grounded operations and claimed invariants, owners/paths, test and version matrix, bounded retention/performance policy plus actionable blockers only.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Define the remaining client frame and replay acceptance work
|
||||
|
||||
Task ID: M01-P6
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Root db0a872 merges S18 b7f18c0, S19 selectable rules, S04 Current14, S01 owner and legacy LAN. Actual client WM_TIMER pumps every 60 ms while camera input can invalidate on demand and scene Present uses 0. Existing replay on serial and 2/6/12, last meal, synchronous structural barriers and faulted owner recovery pass. M01 needs independent client frames and an evidenced worker completion-order adversary/first divergent IDs.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare two independent real work packages for S17-W01 render frame delivery and S21-W01 deterministic replay diagnostics. Identify acceptance already satisfied vs missing. Recommend minimal source-grounded additions that can proceed alongside full S06/S04 custody.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
No implementation, new M02 terrain, mesh engine overhaul, native performance claims, general benchmark infrastructure or speculative production hooks. Preserve S18 title/rules changes and S06 current schema.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M01.md, systems/S01,S17,S21; app/viewer_win32.cpp pump_session/scene/view/HUD/camera/modal/WM_PAINT/WM_TIMER, app/d3d_scene_win32.* and public draw interface, existing client_* smoke and tests; engine worker_pool/world scheduling/hooks, runtime/dispatcher, tests/replay_tests.cpp/executor_tests.cpp/runtime_tests.cpp, benchmarks as pertinent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote/children or Serena switch. Root plans separate branches, S18 owns title and profile logic, S06/S04 own inventory world paths. Use current root graph only after coverage check and read missed lines.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S17 identify how to prepare/pin immutable frame data once, main+child/software/D3D and nested UI callbacks, decouple scene refresh from event/network pump and authoritative 50 ms tick, avoid busy loop/rebuilding expensive static geometry solely for unchanged state, camera movement during gated world and file work. Match existing Win32 design and keep title/minimize/pause behavior; future D3D chunk cache is M02. State how real harness could assert camera changed and original tick stayed fixed without treating Wine fps as native.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
S21 locate how last-item/resource arbitration relates to actual parallel batches and stable tie order. Design test/harness that PROVES opposing order of completed tasks (not just ordering hook starts/sleeps) for an actual contested outcome and canonical state. If after callback needed, preserve WorkerPool completion/exception/move-only behavior and use least invasive grounded seam. Check stale results after load owner barrier, real two client idempotent and save+camera. Recommend first-divergent tick/ID (inventory/actor/job/command) reporting and repeatable command entry/tag. Avoid duplicated serializers that drift; existing current14 soon current15. Derive calls/files from source.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Align S17 renderer-owned files vs S18 title/client profiles and CMake/worker code ownership. S21 can adapt test golden canonical encoding immediately independent of future custody, document which invariants extend after body15. Flag any truly missing generic primitive and check pinned Void facilities before suggesting upstream issue.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Check UI timers/window events after destroyed, minimized/hidden, modal subloops and GPU resource lifecycle/race. Race tests deterministic using bounded waits and release cleanup even on assertion. Never rely on exact Wine wall scheduling or declare physical 60fps. Prevent deadlocks at 2 workers or queue capacity 1.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate executable contracts with exact paths and acceptance. 2. Clear proof of forced completion and stale fencing/diagnostic usefulness. 3. Real GUI cadence event and pinning acceptance with labels and stable source ownership. 4. Mark which existing evidence suffices. 5. No broad refactors outside M01.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git rev-parse HEAD; scoped graph search/trace and snippets plus coverage ranges. Read actual integrated CTest/GUI logs m01-viewer-{build,ctest,ui-smoke}.log and /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. No builds needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Send first independent S17/S21 seam early. Avoid new protocol/settings, general policy changes or altering product contracts in design. No remote actions/children.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes complete roadmap and per-system development branches. Root owns product/integration/publication. Preliminary design may proceed while S18 title and S06 custody progress.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-P6 READY/PARTIAL per system, current verified behavior, scope/paths, exact measurable tests, remaining gaps/dependencies and likely performance implications.
|
||||
@@ -46,3 +46,11 @@ User authorizes complete plan and system/milestone commits/MRs accumulating on r
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V10 separate S16/S18 findings with actual tests, changed paths and limitations. No children.
|
||||
|
||||
The S16 adapter has been integrated at `aa4e271` (parents `60154bd` and `09545bf`). Recheck the transport, legacy codec and test blobs against the reviewed branch, confirm the absence of merge edits to the owner or file adapter, and inspect `m01-lan-{build,ctest}.log` before publication. This additional check is read-only. The combined suite passed 106 core and 9 LAN tests.
|
||||
|
||||
Stage A passed the integrated review at `aa4e271`. For stage B inspect the actual tracked and new S18 files in the `s18` worktree based at `eef69ca`, including `viewer_session`, the Win32 entry point, CMake and the viewer suite. Inspect `client-{build,ctest,ui-smoke}.log` and `client_ui_smoke.cpp` under the temporary evidence directory above. The smoke used three real viewer processes with isolated save data. Check title, modal navigation, successful and failed load, guest transitions and truthful pending-blueprint outcomes. The contract still distinguishes the initial compiled default profile from the separately scheduled S19 selection. Return a defect report or READY for S18 without changes to the checkout.
|
||||
|
||||
Stage B initially required three corrections. Recheck the finished fixes for identity after modal demolition, rejected guest rejoin preserving the retained replica, and ticking acknowledgements across fault recovery. Inspect the updated committed-quantity and request-path checks in `client_{handlers,regression}_smoke.cpp`, the corresponding `client-{handlers,regression}-smoke.log`, the final viewer build, the three-process smoke and `client-ctest.log` (99 core, 9 LAN, 10 viewer). Separate integrated audit follows when root supplies the merged ref.
|
||||
|
||||
Stage B fixes passed review and were committed as `b7f18c0`. Integrated commit `db0a872` has parents `5354241` and `b7f18c0`. Confirm that the resident panel uses approved resource/storage/production IDs while the view remains pinned, both UI and core suites register, and the merged application’s three-process smoke passed. Check `m01-viewer-{build,ctest,ui-smoke}.log` under the temporary evidence directory.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Review durable order identity and compiled colony profiles
|
||||
|
||||
Task ID: M01-V11
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Independent review in two phases. S04-01 isolated worktree s04 based 4ba64f7 with production order IDs, body14 and outer checkpoint2, existing schema1 real fixture. S19-02 isolated s19 based 60154bd with first optional package/profile, old default retained. S19 and S04 are expected to touch adjacent World declarations/CMake; root will supply combined refs for final checks. Baseline S16/S06/S15 already published.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide separate disposition for actual S19-02 and S04-01, then for a root-supplied integrated result if requested. Alert root quickly on reproducible failure before workers retire.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
S19 backend, old/new data and S04 current changes including codec, command handling, real placement/reservations and lifecycle. S18 screen/selector verification belongs to a separate client review. This review covers the public core seams that later UI calls.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect actual tracked/untracked files in sibling worktrees /home/faumaray/Projects/stoneheart_at_home-worktrees/{s19,s04}, including all new headers/sources/tests, full surrounding world, checkpoint/readers, rules_manifest, first_colony, command_dispatcher, changed CMake and docs; baseline legacy tests + new fixtures actual consumed bytes. Read contracts S04-01/S19-02 there and root M01-F6.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote postings or children. Parent owns commits/resolution. Use direct scoped reads for separate worktrees, shared root graph with coverage/direct missed lines if used. Do not change project activation.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
S19 audit exact old default manifest/hash, optional package deterministic compile of real recipes vs forged/missing/additions and unsupported profiles, factory UUID/canonical rules, no mutable after-start rule switching. Check active staged optional refusal, default raw/simple/inactive/saved historical compatibility, actual input requirements/duration simple vs staged, finished beds and room. S04 review full ID allocation, batch production scheduling incl replenishment simulated post-demolition, before/after failures transactional, exact Busy narrow no domain next seq mutation; new ID in all actor references, cancellation, finishing order and find; explicit codec boundaries, bounds/duplicates/noncanonical/high-water/dangling, v1 authentic + modern pair and replay.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Public profile functions colony_rules/compile_colony_rules/make_colony_checkpoint/validate_colony_checkpoint and staged/default initializers preserve calling contracts; strict profile policy only at game/client gate, generic codecs/runtime remain reusable. ProductionId 0 absent, MAX exhausted with last valid MAX-1. Compare both double dispatch (legacy/direct/modern) where relevant to tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Order of branch signoff independent. On integrated stage confirm the raw/outer and profile gates and all added tests coexist under root CMake/World changes. Native hardware/real LAN separate. Root will send ready marker and evidence directory for each phase; do not approve unseen results.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Watch O(N²) references in hot/hostile save path, exhaustion partial mutations after storage erasure/cabin terrain / counters/room placements, v13 and LAN11 byte drift, accidental implicit fallback on unauthenticated or modified data, restoring historical default simple and optional staged mismatch. Confirm authentic fixtures frozen using prechange binary; never log private data.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate READY/CHANGES_REQUIRED per component with concrete reproduction and severity. 2. Compare targeted/final logs and actual old corpus bytes, not just worker report. 3. Root integration evidence after selected branches merged must identify any new cross-contract issue. 4. Document unverified native/product gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Use git -C <wt> rev-parse HEAD; git -C <wt> diff --check and --stat; read status/new paths and inspect source directly. Inspect /tmp/stoneheart-milestones.xprJ2SVp/profile-{baseline,tag,ctest,compatibility}.log and production-id-{final-tag,ctest}.log plus archived production replay/corpus logs as provided. For merge phase compare relevant actual branch/HEAD blobs and final CTest logs.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Give findings as soon as evidence warrants; no remote or code writes, no plan beyond requested changes. Hold component approval if final tests not yet recorded or actual source still changing. Two failed same-cause fixes escalate via root.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes roadmap/push/MRs/upstream issues; root alone owns those actions. Preflight M01-F6 explicitly passed under default simple/inactive compatibility policy and scoped capacity exception contract.
|
||||
|
||||
## 14. Return format
|
||||
Return M01-V11 S19/S04 separate verdict, file/line, trigger, actual tests/artifacts and remaining gaps. Later verify corrected diff or integrated refs when supplied.
|
||||
|
||||
Both component reviews returned READY. Audit integration commit `a8cd7bb`, parents `9a248c3` (which includes S19 `2759563`) and S04 `2a3ec92`. CMake kept both new test sources during conflict resolution. Check the merged World initialization and stable production fields, old/new checkpoint and profile behavior, selection tests using the real current encoder, and the unchanged legacy host gate. Windows x64 logs `m01-orders-profiles-{build,ctest}.log` cover 122 core and 9 LAN cases. S18 initial viewer and follow-up title selection have separate reviews. Scope here is the integrated core and runtime LAN behavior.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Verify library support for voxel coordinates, chunks and surface picking
|
||||
|
||||
Task ID: M02-R1
|
||||
Role: astra_researcher
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Approved game roadmap, M02 follows M01 and calls for an editable finite voxel region with 32³ chunks, consistent coordinate/picking/navigation interpretation. No M02 code or branch started. Game root current 60154bd/aa4e271, Void exact CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 confirmed equal upstream HEAD, source/tests available locally.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Prepare reusable API and missing-feature evidence so S02/S03/S17 can start under the user's Void-first dependency rule when M01 entry gates settle.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only M02-specific official/pinned API audit, exact target semantics and minimal verification/issue ideas. Not a game implementation, upstream write, or M02 completion claim.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M02.md, systems/S02/S03/S17, prior void-library matrix and first_colony/world terrain/render picking, deterministic_rng.hpp. Pin clone /tmp/stoneheart-verify.KoZwE4o8/candidate/_deps/void_library-src including CMake modules, include and tests. Inspect official library headers before claiming absent.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations to tracked/user data, Git/remote writes, public issue creation or children. Parent owns upstream tickets. Temporary isolated compilation probe in /tmp allowed if evidence is genuinely needed; no editing any shared build dir.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Determine exact public support for (1) signed 3D integer coordinates with correct floor division at negative boundaries, checked conversion, fixed-size contiguous chunk index and 6 neighbors; (2) deterministic seed/coordinate hashing and stateful portable random streams with fixed parameters and import/state or existing game RNG; (3) bounded sparse/finite chunk storage, generation version/edit delta/revisions; (4) grid DDA/voxel surface hit and path invalidation by touched chunk revision. Test/document any claimed coverage. Distinguish math primitives to use directly from game-specific policy and genuinely reusable missing capabilities. Check actual dev/test modules/adapters on Windows x64.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Return concrete interface names when present with source/tests at pin and what they guarantee. Root needs precise issue titles, reproducible inputs and replacement tests for actual generic gaps only; avoid a broad request to build the entire game in a shared library. Cover local coords at -1/0/31/32, extreme ranges, 3D axis convention and cross-chunk picking ties.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
M01 stable world ID/epoch/snapshot/checkpoint ownership upstream, future S02 data constructor and S17 ray picking consume that. No assumption M01 fully done; preparatory research only. Confirm whether upstream moved relative to pin via read-only ref if necessary.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Do not suggest library nondeterministic RNG for authoritative state when serialization/stream portability absent. Observe D3D renderer right-handed coordinate/picking constraints locally, storage limits and floating vs integer choices needed. Cite files, no private data outside approved repo/library.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Separate supported modules with test evidence vs missing subcontracts; 2. Bounded ownership and exact replacement tests for future implementation; 3. Identify native/other gaps and M02 code dependencies. 4. Relay first actionable library finding early.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
git rev-parse HEAD and git -C <pin> rev-parse HEAD, targeted rg --files and rg -n on actual symbols and tests, project graph with coverage/direct reads for current app/World when relevant. Source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any standalone Windows probe, no global changes.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not open remote tickets or implement new types; notify root with exact evidence. No speculation solely from CMake module names. No further agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User mandates Void support/issue linkage for real gaps; root authorizes this preparatory evidence in parallel with M01 work, without marking M02 started or complete.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-R1 VERIFIED/PARTIAL, pinned paths/API/test names, minimal concrete missing-feature cases and upstream lookup/filing suggestions, native/target limitations.
|
||||
|
||||
The Windows x64 probe passed under Wine 11 with GCC 16.2. Native Windows and MSVC remain unverified. Numeric, canonical little-endian Binary fields, FNV-1a, seeded raw Xoshiro output and graph traversal limits are available on this target. Each missing reusable operation has its consumer and replacement check in the [dependency matrix](../../plan/void-library.md#подготовка-воксельного-мира-m02). Upstream records cover [restorable random streams](https://git.faumaray.com/Void/Library/issues/10), [Euclidean division](https://git.faumaray.com/Void/Library/issues/11), [grid ray traversal](https://git.faumaray.com/Void/Library/issues/12), [revision dependencies](https://git.faumaray.com/Void/Library/issues/13) and [atomic sparse volume edits](https://git.faumaray.com/Void/Library/issues/14).
|
||||
@@ -0,0 +1,50 @@
|
||||
# Persist production order identities and allocate complete command batches atomically
|
||||
|
||||
Task ID: S04-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s04 system/s04-jobs-reservations base 4ba64f7. WorldState includes capture, S06 durable storage/node refs. S15 envelope v1 accepts raw World v1–13. M01-P3/V9 identified all insertion and refusal paths including storage demolition replenishment and LegacyCabinPayload in S16. Upstream durable allocator #7.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Give every production order a persistent World-scoped ID, remove stored positional production references, preserve identity history in modern checkpoints while keeping original saves/wire exact, and make all order-allocating business commands reject exhaustion without partial effects.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Production identity, high-water mark, ABI/caller migration, modern raw/envelope generation and validated v1 import. Keep zero none, leave new stack/ownership/transfer records and broad economy behavior to later slices. Preserve historical default formatting/encoding and v11 public network.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp all insertion/erase/use sites and missing_carpentry_orders, world_save.cpp body/validate, checkpoint.cpp/.hpp/checkpoint_files.cpp, command_dispatcher.cpp catches LegacyCabinPayload, viewer resident detail, existing tests and old baselines. F3/F5, M01-P3/V9. Inspect/preserve exact pinned Void Numeric/Binary/Crypto and prior deterministic corpus.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/command_dispatcher.cpp (only legacy cabin exhausted outcome); app/viewer_win32.cpp (resident production details only); tests/core_tests.cpp; tests/identity_tests.cpp; tests/replay_tests.cpp; tests/production_identity_tests.cpp (NEW); tests/checkpoint_tests.cpp; tests/checkpoint_file_tests.cpp; tests/session_tests.cpp; CMakeLists.txt; docs/plan/systems/S04.md
|
||||
Only touch listed affected tests/callers as needed. Other owners touch UI, files, profiles elsewhere. You are not alone; root integrates branches. Do not edit other worktrees/Git/Serena.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Add real ProductionId, immutable order identity, WorldState::next_production_id_, Agent::production_id (0 absent), bounded sorted lookup, erase without index repair. Centralize all order insertion incl queue_production and both direct PlaceRoom loops. Calculate exact whole ID requirement and incrementable successors before any command/domain side effect. Single and multi-order (bed, loom, workshop, rooms/furnishings, direct cabin and implicit replenishments) precheck numeric exhaustion as well as vector allocation. MAX terminal valid, last allocatable MAX-1. Calculate EXACT post-demolition missing carpentry counts across products/requirements WITHOUT erasing/mutating storage first, reserve all IDs before deleting stock or appending any order. If full batch cannot fit return nonmutating Busy with exact old storage/stock/sequence and counters. For LegacyCabinPayload use explicit testable pre-mutation exhaustion result/exception, narrowly translate THIS proven refusal to completed Busy in CommandDispatcher::apply, retain exact repeat while session remains healthy. Do not catch a generic error that could follow partial mutation. Other unexpected errors use F3 fault boundary. Avoid duplicated independent registries.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Default World::write_save(std::ostream&) still emits exact v13 bytes and historical positional links, old callers incl LAN11 unchanged. Add explicit modern World write mode v14 (new actual enum or method) using same codec/body, include stable refs / order IDs/high-water; now World::read_save handles appropriately. Checkpoint encode becomes schema2/modern body14. Decode authentic schema1/inner1–13 and schema2/inner14 only, verify signature & checksum using common codec, latest high-water after deleting last/highest/all survives. Historical import assigns IDs deterministically in vector order with next > live max; no new UUID on modern reload. Validate sorted unique nonzero ProductionIds, strictly larger next (MAX valid), referenced target existence/state before indexing. Keep envelope magic unchanged. Old file-adapter test hardcodes unsupported next value 2: change to actually unsupported value and retain a true pre-change v1 fixture, not just changing expected bytes. Tell root exact frozen API early.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns final merge. S18 worker also touches UI but not resident-detail lookup; S19 profiles separate. File reader matches same signature and uses generic decode; ensure outer/inner pairing tests even when attacker recalculates both checksums. Registry consumers continue using const World. Use existing checked arithmetic; local implementation+replacement link Void/Library #7 in docs and allocation source where useful.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Avoid O(N²) repeated scans of million-record parsed data; legacy index projection/import bounded as in S06. Active resident must keep same original order when lower deleted. All domain normal refusal keeps previous capacity/contents/command seq; last accepted identifier remains unaffected by vector erasure, world capture or save. Ensure no different command arbitration/legacy behavior on ordinary non-exhaustion. Preserve legal old v1–v13 payload behavior. Do not overwrite any user save.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Deleting lower/highest/all orders followed by v2 reload + allocating another never reuses IDs, actual mid-haul agent remains bound; corrupt ID/dangling/current combinations rejected. 2. MAX/MAX-1 single and multi batch incl room/cabin/stock demolition with multiple products, verify byte-identical complete current state/unchanged seq after Busy, and exact replayed cabin Busy with healthy runtime. 3. Authentic checkpoint v1 lower inner and v13 accepted, wrong pairing incl v1/14, v2/13 rejected with valid checksums. 4. Per-tick MODERN canonical replay including ID state across serial/2/6/12, old default v13/legacy benchmark data compare exact. 5. All cross suites pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/production-id-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe --tag production-id, full verbose CTest, git diff --check; fixed binary compatibility corpora at /tmp/stoneheart-milestones.xprJ2SVp/old-trajectory.bin and identity-compat-old.bin, baseline 4ba64f7 artifacts. Save logs production-id-*. No synthetic recreation of a golden old checkpoint with the new encoder.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No broad rewrite or custom replacement for supported Void primitives, branch changes or further agents. If existing unknown pre/post mutation exception means a Busy lie, stop and send contract+counterexample. After two failed repairs raise distinct hypothesis with evidence.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system features, commits/push and merge requests. M01-V9 requested exact demolition and cabin corrections; parent obtains narrow preflight recheck before dispatch. Root owns all side effects.
|
||||
|
||||
## 14. Return format
|
||||
Return S04-01 READY/BLOCKED, public format and ID APIs, actual coverage of all allocation sites, clean failure outcomes, compatibility corpora hashes/tests, and remaining later custody/native risks. No children/commits/push.
|
||||
|
||||
The middle-of-delivery assertion in `tests/snapshot_tests.cpp` also reads the removed production index. The implementer owns its equivalent check of the stored nonzero production ID.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Serve compatible LAN clients from the immutable authoritative runtime
|
||||
|
||||
Task ID: S16-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16, system/s16-authority fast-forwarded to 8c4c1fe. Existing LanSession::poll(World&) protocol11 is tested (4 cases/baseline binary interop). Runtime and command dispatcher new headers exist. M01-F4 identified manifest and outstanding-command reconnect gates, included below.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Add production host polling that consumes immutable runtime views and submits authenticated guest actions to the owner asynchronously. Add guest-only polling usable by a view-only client, preserve current hardcoded two slots and old packet format.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Legacy LAN11 compatibility adapter and actual loopback tests. No public new protocol/version or remote rollout, no new internet exposure. Preserve existing poll(World&) entry/fixtures for old API clients. Viewer source is owned separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect app/lan_session.hpp, app/lan_session_win32.cpp, app/lan_wire.hpp/.cpp, tests/lan_tests.cpp, simulation_runtime.hpp, command_dispatcher.hpp, world.hpp, rules_manifest.hpp, docs/plan/systems/S16.md. Read /tmp/stoneheart-verify.KoZwE4o8/interop.cpp/.py for existing binary interop.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/lan_session.hpp; app/lan_session_win32.cpp; tests/lan_tests.cpp; docs/plan/systems/S16.md
|
||||
If an identified shared codec change is necessary, contact root first; no data layout redesign. Other workers own Win32 viewer/core. You are not alone, do not change Git/Serena/other worktrees.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
NEW poll_host(SimulationRuntime&) and poll_guest() (or equally explicit) for real viewer. Wire11 Hello carries no manifest/epoch, so allow ONLY default compatibility manifest (verified frozen identity); close incompatible connection before exposing a snapshot/command. Bind host session incarnation; detecting replacement drops peer & requires new hello before serving new world. Existing TCP framing/auth and slot validation retained. Read current immutable published World and prepare v13 snapshots with current bounds. No direct mutation in new host path. Screen sends one action at a time; bound hostile/pipelined volume, keep pings/timeouts/disconnect progress, never wait on a long owner while polling socket. Serialize one outstanding valid command per authenticated guest slot.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Wire request IDs are legacy World::next_command_sequence(guest), only accepted gameplay increments them. Modern envelope number from committed PublishedSnapshot::next_requests[guest] also advances on domain rejection. Precheck wire sequence without mutating state; old wrong-sequence -> expected number. Submit trusted guest=2, verified UUIDs/world/city/version, exact payload; report the correct legacy result and next wire sequence only from corresponding committed runtime result. Reject unsupported actions using existing authority. Track one outstanding admitted operation across TCP disconnect/rebind; suppress old-connection replies by connection generation, hold/reconcile its completion before next guest's sequence or authentication/publication is used, prevent reusing in-flight modern request number. On epoch change fence old future before new peer bind. No borrowed runtime pointer persisted. Expose status to viewer on incompatible rules/fault. Send early public signatures.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns actual Win32 viewer integration. Runtime consumers now available at baseline; old standalone overload remains tested. Add only in-process loopback tests using random port/loopback flag. Reuse existing socket implementation and avoid duplicate dispatch/snapshot logic. Legacy reader file/body remains format13 and lower limits; world with unsupported future schema must be rejected explicitly in later change.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
On Busy/Closed/Faulted/superseded/out-of-order preserve protocol-correct old next id and prevent lost reported effects. Guest can correct a rejected action using same old number. Do not retain retired peer's optimistic blueprint metadata. Check long owner tick does not block server pings/poll; settled work from old peer cannot reply to a new one. Enforce bounded admission and no logs of join codes. Test a publication at same tick.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Old-style genuine guest joins runtime-owned host and receives actual committed world; user action, domain rejection and corrected next command preserve legacy sequences. 2. Deliberately blocked/delayed command, disconnect/reconnect, no old receipt to new peer, sequential guest slot safely resumes. 3. New epoch and non-default manifest refuse or reauthenticate before any legacy snapshot. 4. Both existing LAN11 fixtures and old API work; deterministic cross-version loopback including old guest executable. 5. Real x64 tests and warning status.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_lan_tests.exe --tag lan (or registered runtime LAN tag plus full target), verbose CTest, git diff --check. Logs lan-owner-*. Root can stage external original-binary harness if needed.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No changes to socket reachability, authentication standards, new transport, UI or unrelated game state. Two failed fixes for the same defect -> send evidence and changed hypothesis to root. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User approved milestone/system work, commits/PRs/accumulation. M01-F3/F4 require authenticated owner entry and preserved old-wire rules. Root handles final integration.
|
||||
|
||||
## 14. Return format
|
||||
Return S16-02 status, early exact caller entry points, peer/session tracking contracts, actual test evidence/counts/interop and any native limitations.
|
||||
|
||||
The client also needs positive acknowledgements to remove committed draft parts. The approved preferred guest interface exposes `take_result()` with the full accepted or rejected intent, including resident ID. Retain one completion until the preferred caller drains it, clear stale results across connection generations and preserve legacy `take_rejection()` behavior. The loopback cases cover accepted and rejected results.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Drive the Win32 client from committed world views and async results
|
||||
|
||||
Task ID: S18-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s18 system/s18-client at 512c9ef. Runtime reviewed at 7979fff and M01 8c4c1fe. S15-03 and S16-02 are in separate worktrees and root will supply reviewed commits to this checkout before final build. S18-W01 owns separating snapshot reads and command submission from window handlers. M01-F4 identified title/menu, lifetime, admission and rules gates.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Wire the actual Win32 viewer to the single-owner runtime for offline play and hosting, immutable guest view, bounded async command handling and real background checkpoint save/load. Keep title/new/continue, legacy scenario/cabin controls and LAN guest usable.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Normal Windows app entry points plus focused testable client-state handling. This first S18 slice does not include unrelated keyboard/scale/sound settings, new internet protocol or UI for metadata-only rule selections. Show only supported default-profile new games; S19 adds genuine selectable behavior separately.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read app/viewer_win32.cpp all session lifecycle/menu/paint/blueprint/command handlers, app/title_screen_win32.hpp, D3D const World entry, LAN and CheckpointFiles headers in sibling s16/s15, frozen simulation_runtime.hpp/impl, raw world factory/first_colony, and existing tests/smoke source /tmp/stoneheart-verify.KoZwE4o8/viewer_smoke.cpp. Watch S06-01 resident detail index access intentionally owned by another worktree.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/viewer_win32.cpp; app/viewer_session.hpp and app/viewer_session.cpp (NEW if needed for testable state); tests/viewer_session_tests.cpp (NEW); CMakeLists.txt (viewer_session target/tests only); docs/plan/systems/S18.md
|
||||
Do not edit other worktrees, shared Serena or Git, or overhaul unrelated UI. Keep resident-detail lookup changes minimal where S06 branch also edits one line; parent integrates. Native normal entry is mandatory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
One window-lifetime owner runtime where possible. New/reset/load install prepared WorldCheckpoint with fresh incarnation; reuse the long-lived runtime or retire former owners off UI without joins, keeping retirement bounded. Guest reads latest received world immutably, never steps/applies; suspend local owner when guest, fence pending UI/authority. Preserve playable disconnected/leave behavior: keep last received guest World privately owned to import into a fresh local session on deliberate leave if prior behavior allows continuing that colony. Fresh first colony uses nonnil stable UUID+resolved default manifest. Gate viewer installs to exact supported compiled-rules profile/32x32 dimensions, preserve legacy imported world. Use consistent shared const world/view per frame and protect raw references across nested window messages/modal confirmations by pin or revalidate after dialogs. Render/HUD paths must stay safe on title with no world. WM_TIMER pumps file/network/runtime completions and reconciles desired ticking state BEFORE ANY title/offline/file-dialog/UI early return. Never step/serialize mutable World on UI. File picker is normal modal selection; picker open affects presentation pause without blocking owner polling or completion processing. Anchor title/hidden, pause-menu, file-dialog, guest/host and shared World::paused semantics to existing user-facing choices; no flood of set_ticking when unchanged or Busy. Fault visible, rendering last head and explicit load still usable.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Expected seam: S15 CheckpointFiles(options) with try_save(path,shared_ptr<const PublishedSnapshot>), try_load(path,workers,mode) → admission/request/future<expected<WorldCheckpoint,CheckpointFileDiagnostic>>, one process-level instance, survives reset across slots. Viewer obtains snapshot_for_save(), tracks completion by request+epoch, only reports latest relevant result. At selected load intent issue runtime begin_load even if ensuing file decode fails so stale older prepare cannot undo latest request; file result independent, filter UI ticket/generation+epoch, install checks again, preserve display on invalid/busy/superseded. S16 provides void poll_host(SimulationRuntime&) and unique_ptr<World> poll_guest(); guest presentation stores owned snapshot only, legacy standalone poll(World&) is for old consumers. Attach local controls/host and legacy cabin to modern CommandEnvelope, trusted host slot, via ONE bounded per-client intent queue and at most one runtime submission awaiting reply; allocate number from latest committed next_requests, never consume on Busy; retries do not duplicate. Pending blueprint/room IDs or exact generation-marked metadata ensure only an actually accepted part is cleared, rejected/busy remains editable, repeated click cannot resubmit pending. Other accepted-only statuses after commit. On reset/join/load, disconnect or retired epoch fence stale results and preserve unrelated current edits. Explicit local effects and connection authority; no GTK/web UI.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root merges reviewed S15/S16 deps into s18 checkout before final build; send dependency requests early. Development may start on public seam/logical model; verify actual source before final compile. F4 corrections per exact contract. Existing tests and external Wine UI smoke must still run. Current UI actions should remain meaningful. No fake alternate rules advertising. Preserve old compatible file extension/recent saves and existing no-guest-save host policy.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
UI must remain responsive during deliberately long tick/file write, complete results on title/modal loops, avoid dereferencing stale selected_agent pointer, actively fence prior session commands/loads, avoid starving owner and don't freeze on reset/new/join. No stateful dangling callbacks on WM_DESTROY; orderly shutdown can drain on app exit. Queue memory and ongoing operations bounded by documented capacity. No unchecked exceptions escaping Win32 callbacks or stale feedback after generation change. Use deterministic gates for tests; actual end-to-end app path observable.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Launch actual viewer, start and advance local colony; deferred owner command incl cabin, pause/unpause while at same tick; no WM_TIMER direct world->step/World::apply_command. 2. Open modern and old saves from title, save during progress, update status only on newest completion; malformed/superseded/unsupported rule loads preserve current session. 3. UI reader can repaint/pan while owner/writer blocked; no synchronous join resetting/joining. 4. Host and guest continue through correct polling and domain-rejection/blueprint sequencing; stale queued intent/load cannot affect new session. 5. All Windows x64 tests and real viewer smoke, including title load if possible, with recorded native gaps.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run wine <dir>/settlement_core_tests.exe or viewer suite as actually registered, CTest -V, git diff --check. Reuse local isolated Win32 smoke harness for real viewer title/new/close and extend temporary harness for title/save/load as feasible; no disk writes to real user saves. Keep logs client-*.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits to S06, raw game rules, runtime, file service or LAN wire. Stop if exact external API differs or a product decision is needed, continue independent work. After two failed repairs of the same issue escalate. No children/Git/remote mutations.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestones, per-system branches, commits/push and merge requests. F3/F4 and subsequent corrective recheck apply; parent owns branch merges/remote publication, no release.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-01 status, actual changed behavior/lifetime/queue and gates, owned files, exact tests and Win32 smoke evidence, pending native validation. Communicate frozen helper/normal UI entry paths early.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Select supported rules when starting a colony in the Win32 client
|
||||
|
||||
Task ID: S18-02
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated s18 worktree after root fast-forwards to db0a872 or a descendant containing the reviewed b7f18c0 client and 2759563 compiled profiles. S18-01 uses a long-lived runtime, exact default-only constructor/load, healthy views, transactional guest admission and fresh session identity. S19 core factory and validator already run the two real cost chains. M01-F6/F7 require validating initial, asynchronous and legacy hosts.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Make the actual Russian title screen offer staged beds (default) or one-plank beds for a new colony, apply the selected compiled rules to the new world, reload either supported profile exactly, and restrict LAN protocol 11 to default rules before any network side effect.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only S18 profile selection/validation and accurate colony presentation. Preserve general S19 resolver, format1–14, LAN bridge/wire, legacy guest leave and unrelated keyboard/settings. Initial factory default stays staged, UI title selection is local to this process and only affects New.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read root/s18 actual app/title_screen_win32.hpp, viewer_win32.cpp, viewer_session.hpp/.cpp, tests/viewer_session_tests.cpp, colony_profile.hpp/.cpp (colony_rules, compile_colony_rules, make_colony_checkpoint, validate_colony_checkpoint), S19 profile_tests and S18/S19 docs. Inspect LAN direct and deferred host event paths BEFORE making changes, current supported_rules_ also supplies legacy guest import. Actual smoke sources client_{ui,handlers,regression}_smoke.cpp in temp.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/title_screen_win32.hpp; app/viewer_win32.cpp (title/new/host/bed labels only); app/viewer_session.hpp and .cpp (factory/validator/host readiness); tests/viewer_session_tests.cpp; docs/plan/systems/S18.md
|
||||
Isolated s18 only. Other workers edit separate branches. Do not revert others' changes or modify CMake/other components. Root owns all Git/remote operations. Distinct test build directory.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use one accessible native control for a clearly labeled New-only choice, ensure keyboard (focus/Tab/arrows/Space/Enter as appropriate) and mouse operate at supported dimensions. Preserve title layout/order and new/continue/save list. Factory creates a new UUID and selected actual world; Continue/Open ignore current selector. Run candidate validation for both supplied initial and replacement/latest prepared loads before owner install and preserve current 32×32 restriction. Preserve default simple/inactive historical modes. Display correct cost including Miner house in simple profile; hide staged foundation material controls when simple.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Host immediate path must reject if changing_world or the current authoritative publication does not have exact default rules. Recheck after returning from modal menu before opening a listener; deferred path revalidate the newly installed publication immediately before network start. Error preserves active world/local file operation/peer. Existing default simple legacy world can host if other established gates pass. Legacy guest import still uses exact frozen default. Do not expose optional rules via old wire. Keep S18-01 fresh ticket/epoch gating and bounded queues.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root owns fast-forward to integrated base before starting. Backend S19 and first viewer are independently accepted. New choice has real compiled behavior. Future S17 render-timer changes are separately owned; avoid edits to WM_TIMER or D3D unless a real unexpected dependency is reported.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reject unknown/forged/extra manifests, optional+staged, unusable dimensions/identity before any effect. Restore valid default raw simple, active optional simple and authentic old saves. A superseded valid load followed by failing newest must keep current world. Titles with small width/DPI should retain usable label/control. No external files in real saves, never open real network beyond loopback.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Real title New creates both variants (including exact selected manifest in saved checkpoint and visible costs). 2. Continue/Open preserve saved choice despite different selection, exact default old inactive/simple accepted. 3. Bad initial/load gate leaves session/world untouched. 4. Immediate/deferred legacy Host refusal before listener or peer change, including held optional load over old default. 5. Existing ten viewer tests, integration CTest and prior three-process/handler regressions still pass.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-profiles-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V, viewer suite selectors as actually registered and git diff --check. Run an actual GUI smoke with isolated LOCALAPPDATA, exercise both choices with mouse/key, New, save/open with opposite selector, confirm actual stored manifest/bed mode. Extend /tmp smoke only as appropriate and record client-profile-* source/logs. Named current published checks are baselines.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not change staged vs simple game costs or default digest, add fake settings, change wire or unrelated app controls. No lowering exact-default admission. If title input cannot be exercised with available Windows/Wine tooling, describe specific gap and continue core meaningful checks. No children/commits/push; two failed same-cause fixes escalate.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User asked for complete milestones/system branches and actual compatible module selection. M01-F7 recorded corrective host gate and accurate simple Miner description. Root owns external side effects. Existing upstream #4 tracks generic resolution.
|
||||
|
||||
## 14. Return format
|
||||
Return S18-02 READY/PARTIAL, actual chosen title control + normal flow, exception/load/LAN boundaries, paths, commands/logs and any native UI caveats.
|
||||
@@ -6,7 +6,19 @@
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. В ссылках на материалы и остановки используются индексы контейнеров. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
В текущем `World` общие, ресурсные и производственные задания назначаются разными методами. Ресурсные работы имеют индекс кандидатов по профессиям. Производство перебирает заказы и склады, проверяет занятость позиции и резервирует сырьё после выбора жителя. Материалы и остановки хранят `StorageId`, источники — `ResourceNodeId`, назначения производства — `ProductionId`. Тесты проверяют резервирование, доставку и сохранение незавершённых работ. [Назначение работ](../../../engine/src/world.cpp) · [Структуры заказов](../../../engine/include/settlement/core/world.hpp) · [Тесты](../../../tests/core_tests.cpp)
|
||||
|
||||
## Реализованный срез S04-01: идентичность производства
|
||||
|
||||
У `ProductionOrder` появился постоянный `ProductionId`, а житель хранит `production_id` (`0` означает отсутствие назначения). Единственный счётчик `next_production_id_` входит в копируемое состояние мира. Заказы остаются отсортированными по ID, поиск выполняется через `lower_bound`; удаление нижнего заказа не требует исправлять ссылки жителей. Присвоенный ID не меняется в течение жизни заказа.
|
||||
|
||||
Все вставки, включая обстановку и клетки комнаты, проходят общий метод. До первого изменения проверяются ID и вместимость вектора для всей группы: кровать, ткацкий станок, комната с мебелью, дом и замещающие столярные заказы при сносе склада. Снос вычисляет нехватку каждого затронутого изделия по запасам **после** предполагаемого удаления, учитывая другие склады и уже существующие заказы, затем резервирует всю группу. Недостаток ID возвращает `Busy` без потери запасов, изменения заказов или номера команды. Последний выдаваемый ID — `UINT64_MAX - 1`; `UINT64_MAX` остаётся допустимым исчерпанным счётчиком. Прямой `queue_cabin` сообщает такую проверенную до изменений нехватку через `ProductionCapacityError`; диспетчер сохраняет повторяемый результат `Completed/Busy`, а runtime продолжает принимать команды.
|
||||
|
||||
`World::write_save(stream)` сохраняет прежний формат 13 и позиционные ссылки для совместимости, включая LAN 11. Явный `WorldSaveFormat::Current14` записывает настоящие ID производства, складов и источников, а также следующий ID производства. Новые checkpoint используют внешнюю схему 2 и тело 14. Схема 1 принимает тела 1–13; несовместимые пары отклоняются даже при корректных контрольных суммах. Импорт старого тела назначает производству ID по порядку записей; современные сохранения сохраняют историю выдачи после удаления последнего, максимального или всех заказов. Чтение проверяет ненулевые упорядоченные ID, следующий ID и ссылки до разыменования; новые проверки не добавляют квадратичный поиск.
|
||||
|
||||
Используются закреплённые `Void::Numeric::checked_add`, Binary и Crypto из `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. Отдельного библиотечного восстанавливаемого генератора ID пока нет: [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7). Локальную проверку и продвижение счётчика в `World::reserve_production` / `append_production` можно заменить после подтверждения того же поведения на Windows x64, включая групповую проверку и исчерпание.
|
||||
|
||||
Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06.
|
||||
|
||||
## Данные и владение
|
||||
|
||||
|
||||
@@ -47,6 +47,12 @@
|
||||
|
||||
## Приёмка
|
||||
|
||||
Клиент Windows может обслуживать хост через `LanSession::poll_host(SimulationRuntime&)`, а гостя — через `poll_guest()`. Хост читает опубликованный снимок и отправляет команду доверенного слота 2 владельцу мира. Сетевой опрос продолжает работу, пока симуляция завершает приказ. `take_result()` возвращает гостю результат вместе с исходными параметрами намерения. До чтения результата следующая команда гостя остаётся в ограниченной очереди. [Сетевой интерфейс](../../../app/lan_session.hpp)
|
||||
|
||||
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
|
||||
|
||||
Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp)
|
||||
|
||||
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
|
||||
|
||||
Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# S18. Интерфейс, управление и обратная связь
|
||||
|
||||
Статус — план реализации. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — первый срез S18-W01 и выбор двух встроенных правил S18-02 реализованы: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
|
||||
## Последовательность реализации
|
||||
|
||||
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное, непосредственно заменяемое и последнее подготовленное состояние проходят `validate_colony_checkpoint` из [S19](S19.md) до установки и дополнительно ограничены картой 32×32. Допускаются только точные встроенные составы стандартной колонии и `settlement.plankbeds`; неизвестный, лишний или изменённый пакет, пустой мир, нулевой идентификатор либо поэтапная кровать с простыми правилами отклоняются с сохранением текущего мира.
|
||||
|
||||
На настоящем главном экране нативный список «Правила только новой колонии» выбирает поэтапную кровать с опорой и тканью (исходный выбор) либо простую кровать из одной доски. Выбор живёт в процессе и применяется только кнопкой «Новая колония»: `make_colony_checkpoint` создаёт соответствующий мир, новый UUID и точный манифест. «Продолжить», список сохранений и выбор файла восстанавливают правила самого сохранения. Исторический стандартный мир с простыми кроватями, поэтапными кроватями или без активного сценария принимается без смены режима. В простом режиме описания всех готовых домов, включая дом шахтёра, показывают одну доску; выбор деревянной/каменной опоры скрыт.
|
||||
|
||||
Старый LAN-протокол 11 допускает только точный стандартный манифест из текущей авторитетной публикации. Проверка выполняется при выборе Host после возврата из модального меню, а для отложенного создания — повторно перед запуском сети после установки мира. Пока ожидается любая смена мира, Host отклоняется без замены мира, отмены загрузки или изменения сетевого объекта. Даже если опубликованный старый мир стандартный, ожидающая загрузка простых правил не открывает слушатель. Выход старого гостя по-прежнему присваивает полученному миру замороженные стандартные правила; формат LAN не расширен.
|
||||
|
||||
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
|
||||
|
||||
Сохранение удерживает здоровый опубликованный снимок, а общий файловый сервис сохраняет порядок записей через смену мира. Только последняя актуальная операция обновляет сообщение. Любая новая попытка загрузки сначала отменяет актуальность предыдущего билета, включая попытку открыть повреждённый или отсутствующий файл. Сбой симуляции оставляет последний подтверждённый вид и возможность явной загрузки. [Файлы и восстановление](S15.md) · [Сетевой адаптер](S16.md) · [Проверки состояния клиента](../../../tests/viewer_session_tests.cpp)
|
||||
|
||||
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
|
||||
|
||||
Проверка S18-02: повторная Windows x64 GCC 16.2 сборка и verbose CTest под Wine 11 — 122 проверки ядра, 9 LAN и 14 состояния клиента. Четыре новые проверки покрывают оба профиля при создании/сохранении/повторной загрузке, начальные и асинхронные отказы манифестов и идентификаторов, отмену актуальности старой правильной загрузки последующей несовместимой, исторические режимы и стандартный импорт гостя. Отдельный прогон настоящего приложения в изолированном `LOCALAPPDATA` проверяет окно 775×640, Tab/стрелки и мышь в нативном списке, мышь/Space на «Новая колония», точные манифесты и режимы в реальных сохранениях, продолжение, список и диалог открытия при противоположном выборе новых правил. Новый процесс возвращает стандартный выбор новой колонии и открывает последнее сохранение с простыми правилами. Прогон настоящих обработчиков удерживает загрузку простого мира поверх стандартного при прямом Host и Host из модального меню, проверяет сохранение мира/билета/сетевого объекта/кода/порта и отсутствие слушателя; отложенный Host повторно отклоняет несовместимую установленную публикацию. Проверены скрытие опор и описание дома шахтёра. Нативная Windows, экранный диктор и повышенный DPI остаются отдельной приёмкой.
|
||||
|
||||
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
|
||||
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
|
||||
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
|
||||
@@ -42,7 +56,7 @@
|
||||
|
||||
## VoidLibrary
|
||||
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Выбор S18-02 использует готовые фабрику и проверку профилей S19; общий пробел разрешения пакетов связан с [Void/Library #4](https://git.faumaray.com/Void/Library/issues/4). Схема игровых правил и нативные контролы остаются у игры. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
|
||||
|
||||
## Приёмка
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
## Срез на 2 декабря 2026 года
|
||||
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. CMake игры явно выбирает `Binary` и `Core`, а при включённых тестах ещё `Testing`. Для следующих модулей проверены исходники закреплённой версии. Их включение и измерения в итоговой Windows-сборке входят в соответствующие этапы.
|
||||
Игра закрепляет Void Library 1.2.3 на коммите `7b0fea6095f603f9e1904f66dfdc7752f4be4792`. На момент проверки `main` указывал на тот же коммит. Windows-сборка M01 выбирает `Algorithms`, `Async`, `Binary`, `Core`, `Crypto`, `Data`, `Math`, `Text` и `Time`. При сборке тестов добавляется `Testing`. [Настройки зависимости](../../CMakeLists.txt)
|
||||
|
||||
| Задача игры | Что есть в VoidLibrary | Решение и граница применимости |
|
||||
|---|---|---|
|
||||
@@ -49,4 +49,16 @@
|
||||
|
||||
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
|
||||
|
||||
## Подготовка воксельного мира M02
|
||||
|
||||
Для будущей генерации и навигации проверены публичные заголовки и тесты того же pin. Отдельная программа, собранная для Windows x64 GCC 16.2, прошла под Wine 11. Проверены граничная арифметика, побайтовый FNV-1a, начальное значение Xoshiro256 для seed 42, очередность обхода графа и ограничение объёма поиска. Координаты и seed можно кодировать фиксированными полями через `Binary::Writer::writeLittle` и хешировать средствами `Void::Hash`. Для равных приоритетов поиска порядок задаёт клиент. [Задание исследования](../agent-workflow/tasks/M02-R1.md) · [Числовые операции](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Math/Numeric.hpp)
|
||||
|
||||
| Запрос в Void/Library | Локальный потребитель и проверка замены |
|
||||
|---|---|
|
||||
| [Восстановление потока RNG и воспроизводимый выбор целого, #10](https://git.faumaray.com/Void/Library/issues/10) | [Генератор прототипа](../../engine/include/settlement/core/deterministic_rng.hpp) и [S02](systems/S02.md). Сохранять алгоритм и версию генератора. Сверить фиксированные значения последовательности, продолжение после смешанных вызовов и независимость двух потоков. Исторический SplitMix64 должен воспроизводить старый ландшафт. |
|
||||
| [Частное и остаток для знаковых координат, #11](https://git.faumaray.com/Void/Library/issues/11) | [S02](systems/S02.md). У `checked_div(-1,32)` результат 0. Для чанка требуются чанк −1 и локальная координата 31. Проверить обе стороны каждой границы и предельные значения знакового типа. |
|
||||
| [Обход вокселей лучом, #12](https://git.faumaray.com/Void/Library/issues/12) | [S17](systems/S17.md). Проверить выбранную ячейку и грань при попадании в угол 32³ с обеих сторон, на отрицательных координатах и при ограничении длины. Камера и отсечение высоты принадлежат клиенту. |
|
||||
| [Набор прочитанных ревизий, #13](https://git.faumaray.com/Void/Library/issues/13) | [Маршруты S03](systems/S03.md) и [геометрия S17](systems/S17.md). Смена опоры в соседнем чанке сбрасывает маршрут, открытие границы делает прежний отрицательный ответ устаревшим, а правка непрочитанного чанка сохраняет результат. При смене инкарнации результат устаревает целиком. |
|
||||
| [Ограниченные разреженные объёмы и атомарные правки страниц, #14](https://git.faumaray.com/Void/Library/issues/14) | [Каталог чанков S02](systems/S02.md). Проверить изменение двух чанков одной командой, точный отказ при устаревшей ревизии либо исчерпанном бюджете и воспроизводимый порядок дельт. Генератор, материалы и такт активации остаются в игре. |
|
||||
|
||||
[Мастер-план](../../PLAN.md)
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 1;
|
||||
inline constexpr std::uint32_t checkpoint_version = 2;
|
||||
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
|
||||
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
|
||||
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
|
||||
@@ -47,10 +47,11 @@ struct WorldCheckpoint {
|
||||
RulesManifest rules;
|
||||
};
|
||||
|
||||
// Version 1 stores magic, schema, metadata length and body length, then world UUID,
|
||||
// Both schemas store magic, schema, metadata length and body length, then world UUID,
|
||||
// city, tick, rules fingerprint and the sorted complete package closure. Each
|
||||
// package stores its ID, exact version and SHA-256. The body uses World's save
|
||||
// codec. A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// codec: schema 1 accepts legacy bodies 1–13; schema 2 requires body 14.
|
||||
// A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// The caller holds a stable World for the entire synchronous encode operation.
|
||||
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
const World& world, Void::Uuid::Uuid world_id, std::uint64_t city,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <iosfwd>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -19,6 +20,15 @@ using AgentId = std::uint64_t;
|
||||
using JobId = std::uint64_t;
|
||||
using ResourceNodeId = std::uint64_t;
|
||||
using StorageId = std::uint64_t;
|
||||
using ProductionId = std::uint64_t;
|
||||
|
||||
enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14 };
|
||||
|
||||
// Raised only by a complete production-ID preflight, before any domain effects.
|
||||
class ProductionCapacityError : public std::overflow_error {
|
||||
public:
|
||||
ProductionCapacityError() : std::overflow_error("production identities exhausted") {}
|
||||
};
|
||||
|
||||
struct GridPosition {
|
||||
std::int32_t x = 0;
|
||||
@@ -244,7 +254,7 @@ struct Agent {
|
||||
StorageId storage_id = 0;
|
||||
Inventory inventory;
|
||||
std::vector<GridPosition> haul_route;
|
||||
std::size_t production_index = no_entity_index;
|
||||
ProductionId production_id = 0;
|
||||
std::uint16_t hunger = 0;
|
||||
std::uint16_t fatigue = 0;
|
||||
bool resting_on_ground = false;
|
||||
@@ -331,6 +341,7 @@ struct ConstructionStop {
|
||||
};
|
||||
|
||||
struct ProductionOrder {
|
||||
ProductionId id = 0; // Assigned once on insertion; never changed during its lifetime.
|
||||
GridPosition position;
|
||||
RecipeId recipe;
|
||||
JobState state = JobState::Available;
|
||||
@@ -370,6 +381,7 @@ struct WorldState {
|
||||
JobId next_job_id_ = 1;
|
||||
std::uint64_t next_resource_node_id_ = 1;
|
||||
std::uint64_t next_storage_id_ = 1;
|
||||
ProductionId next_production_id_ = 1;
|
||||
std::vector<std::uint8_t> blocked_;
|
||||
std::vector<Agent> agents_;
|
||||
std::vector<WorkJob> jobs_;
|
||||
@@ -430,7 +442,9 @@ public:
|
||||
[[nodiscard]] ScenarioProgress scenario_progress() const noexcept;
|
||||
void step(TickProfile* profile = nullptr);
|
||||
void write_svg(const std::string& path) const;
|
||||
void write_save(std::ostream& stream) const;
|
||||
// Legacy13 preserves the historical positional wire format. Current14 also
|
||||
// preserves production identities and their allocation history after deletion.
|
||||
void write_save(std::ostream& stream, WorldSaveFormat format = WorldSaveFormat::Legacy13) const;
|
||||
// Called by the owner after every stage has drained. The independent copy
|
||||
// can be retained by readers on other threads while the owner advances.
|
||||
[[nodiscard]] std::shared_ptr<const World> capture() const;
|
||||
@@ -447,6 +461,7 @@ public:
|
||||
[[nodiscard]] const std::vector<ResourceNode>& resource_nodes() const noexcept;
|
||||
[[nodiscard]] const std::vector<Storage>& storages() const noexcept;
|
||||
[[nodiscard]] const Storage* find_storage(StorageId id) const noexcept;
|
||||
[[nodiscard]] const ProductionOrder* find_production(ProductionId id) const noexcept;
|
||||
[[nodiscard]] const ResourceNode* find_resource_node(ResourceNodeId id) const noexcept;
|
||||
[[nodiscard]] const std::vector<ProductionOrder>& production_orders() const noexcept;
|
||||
[[nodiscard]] const ProductionOrder* assigned_bed(AgentId agent) const noexcept;
|
||||
@@ -469,6 +484,9 @@ private:
|
||||
};
|
||||
|
||||
[[nodiscard]] Storage& storage_by_id(StorageId id);
|
||||
[[nodiscard]] ProductionOrder& production_by_id(ProductionId id);
|
||||
[[nodiscard]] bool reserve_production(std::size_t count);
|
||||
void append_production(ProductionOrder order);
|
||||
[[nodiscard]] ResourceNode& resource_node_by_id(ResourceNodeId id);
|
||||
[[nodiscard]] std::size_t cell_index(GridPosition position) const noexcept;
|
||||
[[nodiscard]] PathResult find_path(GridPosition start, GridPosition goal) const;
|
||||
@@ -483,7 +501,8 @@ private:
|
||||
void finish_rest_step(Agent& agent);
|
||||
void advance_construction_delivery(Agent& agent);
|
||||
void finish_production(Agent& agent);
|
||||
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0) const;
|
||||
[[nodiscard]] std::size_t missing_carpentry_orders(ItemType product, std::size_t new_installations = 0,
|
||||
StorageId excluded_storage = 0) const;
|
||||
void update_scenario();
|
||||
[[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept;
|
||||
[[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept;
|
||||
|
||||
@@ -165,7 +165,7 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
|
||||
}
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
auto body = std::move(stream).str();
|
||||
if (body.size() > max_checkpoint_body_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
|
||||
@@ -212,7 +212,8 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
if (!std::ranges::equal(get_bytes(header, checkpoint_signature.size(), "magic"), wire_bytes(checkpoint_signature))) {
|
||||
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
|
||||
}
|
||||
if (get<std::uint32_t>(header, "version") != checkpoint_version) {
|
||||
const auto schema = get<std::uint32_t>(header, "version");
|
||||
if (schema != 1 && schema != checkpoint_version) {
|
||||
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
|
||||
}
|
||||
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
|
||||
@@ -263,6 +264,15 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
}
|
||||
auto rules = validate_rules(saved, fingerprint, installed);
|
||||
const auto body = bytes.substr(header_size + metadata_size, static_cast<std::size_t>(body_size));
|
||||
if (body.size() < 12 || body.substr(0, 8) != "SETTLERS") {
|
||||
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint world header is invalid.");
|
||||
}
|
||||
Void::Binary::Reader body_header(wire_bytes(body).subspan(8, 4));
|
||||
const auto body_version = get<std::uint32_t>(body_header, "world.version");
|
||||
if ((schema == 1 && (body_version < 1 || body_version > 13)) ||
|
||||
(schema == 2 && body_version != 14)) {
|
||||
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint schema and world version do not match.");
|
||||
}
|
||||
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
|
||||
auto world = World::read_save(stream, workers, mode);
|
||||
if (world->tick() != tick) {
|
||||
|
||||
@@ -78,6 +78,8 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const
|
||||
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
|
||||
try {
|
||||
world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter);
|
||||
} catch (const ProductionCapacityError&) {
|
||||
return CommandStatus::Busy;
|
||||
} catch (const std::invalid_argument&) {
|
||||
return CommandStatus::InvalidTarget;
|
||||
}
|
||||
|
||||
+67
-40
@@ -322,6 +322,29 @@ const ResourceNode* World::find_resource_node(ResourceNodeId id) const noexcept
|
||||
return found == resource_nodes_.end() || found->id != id ? nullptr : &*found;
|
||||
}
|
||||
|
||||
const ProductionOrder* World::find_production(ProductionId id) const noexcept {
|
||||
const auto found = record_position(production_orders_, id);
|
||||
return found == production_orders_.end() || found->id != id ? nullptr : &*found;
|
||||
}
|
||||
|
||||
ProductionOrder& World::production_by_id(ProductionId id) {
|
||||
return require_record(production_orders_, id);
|
||||
}
|
||||
|
||||
// Replace with a restorable checked sequence when Void/Library#7 is available:
|
||||
// https://git.faumaray.com/Void/Library/issues/7
|
||||
bool World::reserve_production(std::size_t count) {
|
||||
if (!Void::Numeric::checked_add(next_production_id_, static_cast<std::uint64_t>(count))) return false;
|
||||
production_orders_.reserve(production_orders_.size() + count);
|
||||
return true;
|
||||
}
|
||||
|
||||
void World::append_production(ProductionOrder order) {
|
||||
order.id = next_production_id_;
|
||||
production_orders_.push_back(std::move(order));
|
||||
++next_production_id_;
|
||||
}
|
||||
|
||||
Storage& World::storage_by_id(StorageId id) {
|
||||
return require_record(storages_, id);
|
||||
}
|
||||
@@ -381,12 +404,12 @@ void World::set_blocked(GridPosition position, bool blocked) {
|
||||
}
|
||||
}
|
||||
for (const Agent& agent : agents_) {
|
||||
if (agent.production_index != no_entity_index &&
|
||||
is_carpentry_recipe(production_orders_[agent.production_index].recipe) &&
|
||||
if (agent.production_id != 0 &&
|
||||
is_carpentry_recipe(production_by_id(agent.production_id).recipe) &&
|
||||
std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) {
|
||||
throw std::logic_error("cannot block the carpenter's delivery route");
|
||||
}
|
||||
if (agent.production_index == no_entity_index &&
|
||||
if (agent.production_id == 0 &&
|
||||
agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep &&
|
||||
!is_carpentry_item(agent.inventory.first_item())) continue;
|
||||
const auto remaining = agent.route.begin() + static_cast<std::ptrdiff_t>(agent.route_cursor);
|
||||
@@ -499,10 +522,11 @@ void World::queue_production(GridPosition position, RecipeId recipe) {
|
||||
throw std::invalid_argument("a building occupies the production site");
|
||||
}
|
||||
}
|
||||
if (!reserve_production(1)) throw ProductionCapacityError{};
|
||||
ProductionOrder order{};
|
||||
order.position = position;
|
||||
order.recipe = recipe;
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
|
||||
bool World::can_place_cabin(GridPosition position) const noexcept {
|
||||
@@ -563,7 +587,8 @@ std::array<ItemStack, 2> World::carpentry_materials(RecipeId recipe) const {
|
||||
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
|
||||
}
|
||||
|
||||
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations) const {
|
||||
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations,
|
||||
StorageId excluded_storage) const {
|
||||
const auto craft = recipe_for_carpentry_item(product);
|
||||
std::uint64_t waiting_installations = new_installations, supply = 0;
|
||||
for (const auto& order : production_orders_) {
|
||||
@@ -574,11 +599,12 @@ std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_in
|
||||
}
|
||||
}
|
||||
for (const auto& agent : agents_) {
|
||||
if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) {
|
||||
if (agent.state == AgentState::Hauling && agent.production_id == 0) {
|
||||
supply += agent.inventory.item_count(product);
|
||||
}
|
||||
}
|
||||
for (const auto& storage : storages_) {
|
||||
if (storage.id == excluded_storage) continue;
|
||||
const auto available = storage.available_item_count(product);
|
||||
if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available;
|
||||
}
|
||||
@@ -600,8 +626,9 @@ void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPositio
|
||||
throw std::invalid_argument("the cabin site is disconnected from the workshops");
|
||||
}
|
||||
const Recipe& cabin = recipe_for(RecipeId::BuildCabin);
|
||||
production_orders_.reserve(production_orders_.size() + 1 +
|
||||
cabin.ingredients[0].count + cabin.ingredients[1].count);
|
||||
if (!reserve_production(1 + cabin.ingredients[0].count + cabin.ingredients[1].count)) {
|
||||
throw ProductionCapacityError{};
|
||||
}
|
||||
for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) {
|
||||
queue_production(sawmill, RecipeId::SawPlank);
|
||||
}
|
||||
@@ -691,18 +718,13 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
return CommandStatus::InvalidTarget;
|
||||
}
|
||||
const auto at_position = [position](const auto& item) { return item.position == position; };
|
||||
const auto shift_index = [](std::size_t& index, std::size_t removed) {
|
||||
if (index != no_entity_index && index > removed) --index;
|
||||
};
|
||||
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) {
|
||||
return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry);
|
||||
});
|
||||
if (order != production_orders_.end()) {
|
||||
if (destination) order->position = *destination;
|
||||
else {
|
||||
const auto removed = static_cast<std::size_t>(order - production_orders_.begin());
|
||||
production_orders_.erase(order);
|
||||
for (auto& agent : agents_) shift_index(agent.production_index, removed);
|
||||
}
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
@@ -710,19 +732,23 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
if (storage != storages_.end()) {
|
||||
if (destination) storage->position = *destination;
|
||||
else {
|
||||
std::array<std::uint8_t, std::size(carpentry_products)> lost_products{};
|
||||
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
|
||||
lost_products[i] = storage->item_count(carpentry_products[i]) != 0;
|
||||
}
|
||||
storages_.erase(storage);
|
||||
std::array<std::size_t, std::size(carpentry_products)> replacements{};
|
||||
std::size_t total = 0;
|
||||
if (scenario_active_) {
|
||||
for (std::size_t i = 0; i < std::size(carpentry_products); ++i) {
|
||||
if (!lost_products[i]) continue;
|
||||
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
||||
const auto product = carpentry_products[i];
|
||||
const auto missing = missing_carpentry_orders(product);
|
||||
for (std::size_t j = 0; j < missing; ++j) {
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
|
||||
}
|
||||
if (storage->item_count(product) == 0) continue;
|
||||
replacements[i] = missing_carpentry_orders(product, 0, storage->id);
|
||||
total += replacements[i];
|
||||
}
|
||||
}
|
||||
// Demand is evaluated against the post-removal inventory, without
|
||||
// losing stock or issuing any order until the entire batch fits.
|
||||
if (!reserve_production(total)) return CommandStatus::Busy;
|
||||
storages_.erase(storage);
|
||||
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
||||
for (std::size_t j = 0; j < replacements[i]; ++j) {
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(carpentry_products[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -733,9 +759,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(),
|
||||
[&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); });
|
||||
if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget;
|
||||
const auto removed = static_cast<std::size_t>(floor - production_orders_.begin());
|
||||
production_orders_.erase(floor);
|
||||
for (auto& agent : agents_) shift_index(agent.production_index, removed);
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
if (destination) source->position = *destination;
|
||||
@@ -770,12 +794,12 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
!can_place_bed(command.cell) || !find_path(scenario_sawmill_, command.cell).reachable) {
|
||||
return receipt(CommandStatus::InvalidTarget);
|
||||
}
|
||||
if (!reserve_production(staged_beds_ ? 1 : 2)) return receipt(CommandStatus::Busy);
|
||||
if (staged_beds_) {
|
||||
queue_production(command.cell, RecipeId::BuildBed);
|
||||
production_orders_.back().bed_base = static_cast<BedBase>(command.value);
|
||||
production_orders_.back().bed_stage = BedStage::Foundation;
|
||||
} else {
|
||||
production_orders_.reserve(production_orders_.size() + 2);
|
||||
queue_production(scenario_sawmill_, RecipeId::SawPlank);
|
||||
queue_production(command.cell, RecipeId::BuildBed);
|
||||
}
|
||||
@@ -842,19 +866,22 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
}
|
||||
if (scenario_active_) {
|
||||
const auto missing = missing_carpentry_orders(ItemType::Loom, 1);
|
||||
production_orders_.reserve(production_orders_.size() + 1 + missing);
|
||||
if (!reserve_production(1 + missing)) return receipt(CommandStatus::Busy);
|
||||
queue_production(command.cell, RecipeId::InstallLoom);
|
||||
for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftLoom);
|
||||
} else {
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(command.cell, RecipeId::WeaveCloth);
|
||||
}
|
||||
break;
|
||||
case CommandKind::CraftDoor:
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
||||
break;
|
||||
case CommandKind::CraftFurniture: {
|
||||
const auto product = static_cast<ItemType>(command.value);
|
||||
if (!is_carpentry_item(product) || product == ItemType::WoodenDoor) return receipt(CommandStatus::InvalidTarget);
|
||||
if (!reserve_production(1)) return receipt(CommandStatus::Busy);
|
||||
queue_production(scenario_sawmill_, recipe_for_carpentry_item(product));
|
||||
break;
|
||||
}
|
||||
@@ -871,8 +898,8 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
const auto fixture = furnishings ? room_construction_recipe(furnishings->back().recipe) : RecipeId::BuildFloor;
|
||||
const auto fixture_item = furnishings ? recipe_for(fixture).ingredients.front().type : ItemType::None;
|
||||
const auto fixture_orders = furnishings ? missing_carpentry_orders(fixture_item, 1) : 0;
|
||||
production_orders_.reserve(production_orders_.size() + width * height +
|
||||
(furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders + fixture_orders);
|
||||
if (!reserve_production(width * height + (furnishings ? furnishings->size() : 0) +
|
||||
(legacy_bed ? 1U : 0U) + door_orders + fixture_orders)) return receipt(CommandStatus::Busy);
|
||||
if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank);
|
||||
if (furnishings) {
|
||||
for (const auto& part : *furnishings) {
|
||||
@@ -881,7 +908,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
order.recipe = room_construction_recipe(part.recipe);
|
||||
order.bed_base = part.bed_base;
|
||||
if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation;
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
}
|
||||
for (int y = plan.first.y; y <= plan.last.y; ++y) {
|
||||
@@ -890,7 +917,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) {
|
||||
ProductionOrder order{};
|
||||
order.position = cell;
|
||||
order.recipe = room_construction_recipe(plan.recipe_at(cell));
|
||||
production_orders_.push_back(std::move(order));
|
||||
append_production(std::move(order));
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor);
|
||||
@@ -1420,7 +1447,7 @@ void World::assign_production_tasks(bool weaving) {
|
||||
order.materials = std::move(materials);
|
||||
order.delivery_stops = std::move(stops);
|
||||
order.state = JobState::InProgress;
|
||||
agent.production_index = index;
|
||||
agent.production_id = order.id;
|
||||
agent.route = std::move(path.positions);
|
||||
agent.route_cursor = 0;
|
||||
agent.work_remaining = recipe.ticks;
|
||||
@@ -1553,7 +1580,7 @@ void World::finish_rest_step(Agent& agent) {
|
||||
}
|
||||
|
||||
void World::advance_construction_delivery(Agent& agent) {
|
||||
ProductionOrder& order = production_orders_[agent.production_index];
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
if (order.collected_stops == order.delivery_stops.size()) {
|
||||
for (const auto& material : order.materials) {
|
||||
agent.inventory.remove(material.type, material.count);
|
||||
@@ -1584,7 +1611,7 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
}
|
||||
|
||||
void World::finish_production(Agent& agent) {
|
||||
ProductionOrder& order = production_orders_[agent.production_index];
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
const Recipe recipe = recipe_for(order);
|
||||
assert(!order.materials.empty());
|
||||
if (is_carpentry_recipe(order.recipe)) {
|
||||
@@ -1593,7 +1620,7 @@ void World::finish_production(Agent& agent) {
|
||||
agent.route = std::move(agent.haul_route);
|
||||
agent.haul_route.clear();
|
||||
agent.route_cursor = 0;
|
||||
agent.production_index = no_entity_index;
|
||||
agent.production_id = 0;
|
||||
agent.state = AgentState::Hauling;
|
||||
order.materials.clear();
|
||||
order.state = JobState::Completed;
|
||||
@@ -1619,7 +1646,7 @@ void World::finish_production(Agent& agent) {
|
||||
} else {
|
||||
order.state = JobState::Completed;
|
||||
}
|
||||
agent.production_index = no_entity_index;
|
||||
agent.production_id = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
@@ -1695,7 +1722,7 @@ void World::step(TickProfile* profile) {
|
||||
if (agent.state != AgentState::Working) continue;
|
||||
if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining;
|
||||
if (agent.work_remaining != 0) continue;
|
||||
if (agent.production_index != no_entity_index) continue;
|
||||
if (agent.production_id != 0) continue;
|
||||
|
||||
const auto job = std::lower_bound(
|
||||
jobs_.begin(), jobs_.end(), agent.current_job,
|
||||
@@ -1742,12 +1769,12 @@ void World::step(TickProfile* profile) {
|
||||
finish_rest_step(agent);
|
||||
continue;
|
||||
}
|
||||
if (agent.production_index != no_entity_index && agent.route_cursor == agent.route.size() &&
|
||||
if (agent.production_id != 0 && agent.route_cursor == agent.route.size() &&
|
||||
(agent.state == AgentState::FetchingMaterials || agent.state == AgentState::Hauling)) {
|
||||
advance_construction_delivery(agent);
|
||||
continue;
|
||||
}
|
||||
if (agent.state == AgentState::Working && agent.production_index != no_entity_index &&
|
||||
if (agent.state == AgentState::Working && agent.production_id != 0 &&
|
||||
agent.work_remaining == 0) {
|
||||
finish_production(agent);
|
||||
}
|
||||
|
||||
+42
-19
@@ -18,7 +18,7 @@ namespace settlement {
|
||||
namespace {
|
||||
|
||||
constexpr std::string_view signature = "SETTLERS";
|
||||
constexpr std::uint32_t save_version = 13;
|
||||
constexpr std::uint32_t save_version = 14;
|
||||
constexpr std::uint32_t last_legacy_footer_version = 8;
|
||||
constexpr std::size_t max_records = 1'000'000;
|
||||
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
|
||||
@@ -231,12 +231,13 @@ struct WorldSaveCodec {
|
||||
archive.field(world.next_job_id_);
|
||||
archive.field(world.next_resource_node_id_);
|
||||
archive.field(world.next_storage_id_);
|
||||
if (version >= 14) archive.field(world.next_production_id_);
|
||||
const auto cells = world.blocked_.size();
|
||||
for (auto& cell : world.blocked_) archive.field(cell);
|
||||
|
||||
// Agent links precede their pools in legacy saves. Raw positions stay
|
||||
// loader-owned until the complete, ID-ordered pools are available.
|
||||
std::vector<std::array<std::size_t, 2>> agent_links;
|
||||
std::vector<std::array<std::size_t, 3>> agent_links;
|
||||
sequence(archive, world.agents_, max_records, [&](auto& agent) {
|
||||
archive.field(agent.id);
|
||||
position(archive, agent.position);
|
||||
@@ -245,8 +246,11 @@ struct WorldSaveCodec {
|
||||
route(archive, agent.route, cells);
|
||||
offset(archive, agent.route_cursor);
|
||||
archive.field(agent.work_remaining);
|
||||
if constexpr (Archive::reading) {
|
||||
std::array<std::size_t, 2> links{no_entity_index, no_entity_index};
|
||||
if (version >= 14) {
|
||||
archive.field(agent.resource_node_id);
|
||||
archive.field(agent.storage_id);
|
||||
} else if constexpr (Archive::reading) {
|
||||
std::array<std::size_t, 3> links{no_entity_index, no_entity_index, no_entity_index};
|
||||
index(archive, links[0]);
|
||||
index(archive, links[1]);
|
||||
agent_links.push_back(links);
|
||||
@@ -264,7 +268,9 @@ struct WorldSaveCodec {
|
||||
}
|
||||
}
|
||||
route(archive, agent.haul_route, cells);
|
||||
index(archive, agent.production_index);
|
||||
if (version >= 14) archive.field(agent.production_id);
|
||||
else if constexpr (Archive::reading) index(archive, agent_links.back()[2]);
|
||||
else reference(archive, agent.production_id, world.production_orders_);
|
||||
archive.field(agent.hunger);
|
||||
if (version >= 4) archive.field(agent.fatigue);
|
||||
if (version >= 5) flag(archive, agent.resting_on_ground);
|
||||
@@ -315,6 +321,8 @@ struct WorldSaveCodec {
|
||||
}
|
||||
}
|
||||
sequence(archive, world.production_orders_, max_records, [&](auto& order) {
|
||||
if (version >= 14) archive.field(order.id);
|
||||
else if constexpr (Archive::reading) order.id = world.production_orders_.size();
|
||||
position(archive, order.position);
|
||||
archive.field(order.recipe);
|
||||
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version.");
|
||||
@@ -325,13 +333,15 @@ struct WorldSaveCodec {
|
||||
require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "Unknown recipe for save version.");
|
||||
archive.field(order.state);
|
||||
sequence(archive, order.materials, item_types, [&](auto& material) {
|
||||
reference(archive, material.storage_id, world.storages_);
|
||||
if (version >= 14) archive.field(material.storage_id);
|
||||
else reference(archive, material.storage_id, world.storages_);
|
||||
archive.field(material.type);
|
||||
require_save(material.type <= max_item, "Unknown material for save version.");
|
||||
archive.field(material.count);
|
||||
});
|
||||
sequence(archive, order.delivery_stops, item_types, [&](auto& stop) {
|
||||
reference(archive, stop.storage_id, world.storages_);
|
||||
if (version >= 14) archive.field(stop.storage_id);
|
||||
else reference(archive, stop.storage_id, world.storages_);
|
||||
route(archive, stop.route_to_next, cells);
|
||||
});
|
||||
offset(archive, order.collected_stops);
|
||||
@@ -341,6 +351,14 @@ struct WorldSaveCodec {
|
||||
archive.field(order.bed_stage);
|
||||
}
|
||||
});
|
||||
if constexpr (Archive::reading) {
|
||||
if (version < 14) {
|
||||
world.next_production_id_ = world.production_orders_.size() + 1;
|
||||
for (std::size_t i = 0; i < agent_links.size(); ++i) {
|
||||
world.agents_[i].production_id = reference_id(world.production_orders_, agent_links[i][2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (version >= 2) {
|
||||
flag(archive, world.scenario_active_);
|
||||
flag(archive, world.paused_);
|
||||
@@ -376,6 +394,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
check_ids(world.jobs_, world.next_job_id_);
|
||||
check_ids(world.resource_nodes_, world.next_resource_node_id_);
|
||||
check_ids(world.storages_, world.next_storage_id_);
|
||||
check_ids(world.production_orders_, world.next_production_id_);
|
||||
invalid(world.work_priority_ <= WorkPriority::BuildingFirst);
|
||||
std::uint64_t revision = 0;
|
||||
for (const auto sequence : world.player_sequences_) {
|
||||
@@ -540,12 +559,13 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
valid_route(agent.route);
|
||||
valid_route(agent.haul_route);
|
||||
const bool has_job = agent.current_job != 0;
|
||||
const bool has_order = agent.production_index != no_entity_index;
|
||||
const bool has_order = agent.production_id != 0;
|
||||
const auto* production = world.find_production(agent.production_id);
|
||||
invalid(!has_order || production != nullptr);
|
||||
const bool has_source = agent.resource_node_id != 0;
|
||||
const bool has_storage = agent.storage_id != 0;
|
||||
invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr);
|
||||
const bool carpentry = has_order && agent.production_index < world.production_orders_.size() &&
|
||||
is_carpentry_recipe(world.production_orders_[agent.production_index].recipe);
|
||||
const bool carpentry = has_order && is_carpentry_recipe(production->recipe);
|
||||
invalid(agent.haul_route.empty() || has_source || carpentry);
|
||||
if (has_job) {
|
||||
invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() &&
|
||||
@@ -557,11 +577,11 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
invalid(claimed == 0);
|
||||
claimed = 1;
|
||||
} else if (has_order) {
|
||||
invalid(!has_storage && !has_source && agent.production_index < world.production_orders_.size() &&
|
||||
agent.work_remaining > 0);
|
||||
const auto& order = world.production_orders_[agent.production_index];
|
||||
invalid(order.state == JobState::InProgress && order_claims[agent.production_index] == 0);
|
||||
order_claims[agent.production_index] = 1;
|
||||
invalid(!has_storage && !has_source && agent.work_remaining > 0);
|
||||
const auto order_index = static_cast<std::size_t>(production - world.production_orders_.data());
|
||||
const auto& order = *production;
|
||||
invalid(order.state == JobState::InProgress && order_claims[order_index] == 0);
|
||||
order_claims[order_index] = 1;
|
||||
if (!order.delivery_stops.empty()) {
|
||||
invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling));
|
||||
} else {
|
||||
@@ -579,7 +599,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
if (collected) ++reserved_slots[storage];
|
||||
}
|
||||
for (std::size_t i = 0; i < item_types; ++i) {
|
||||
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[agent.production_index][i]);
|
||||
invalid(agent.inventory.item_count(static_cast<ItemType>(i + 1)) == expected_cargo[order_index][i]);
|
||||
}
|
||||
} else if (has_source) {
|
||||
invalid(world.find_resource_node(agent.resource_node_id) != nullptr &&
|
||||
@@ -654,14 +674,17 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
}
|
||||
}
|
||||
|
||||
void World::write_save(std::ostream& stream) const {
|
||||
void World::write_save(std::ostream& stream, WorldSaveFormat format) const {
|
||||
const auto version = static_cast<std::uint32_t>(format);
|
||||
require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14,
|
||||
"Unsupported save output format.");
|
||||
SaveWriter archive(stream);
|
||||
for (char letter : signature) archive.field(letter);
|
||||
archive.field(save_version);
|
||||
archive.field(version);
|
||||
archive.field(seed_);
|
||||
archive.field(width_);
|
||||
archive.field(height_);
|
||||
WorldSaveCodec::body(archive, *this, save_version);
|
||||
WorldSaveCodec::body(archive, *this, version);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
|
||||
|
||||
@@ -205,7 +205,7 @@ Test CheckpointFileTests::modern_failures_retain_exact_diagnostics() {
|
||||
"modern failure lost its codec diagnostic");
|
||||
}
|
||||
auto unsupported = current;
|
||||
unsupported[8] = 2;
|
||||
unsupported[8] = static_cast<char>(checkpoint_version + 1);
|
||||
write(path, unsupported);
|
||||
const auto version = load(files, path);
|
||||
require(!version && version.error().checkpoint &&
|
||||
|
||||
@@ -112,7 +112,51 @@ std::string package_json(std::string_view id, std::string_view version = "1.0.0"
|
||||
|
||||
RulePackage load(std::string_view json) { return checked(load_rule_package("checkpoint-fixture.json", json)); }
|
||||
|
||||
// Captured before S04 with the baseline 4ba64f7 library, using seed 43,
|
||||
// a 3x3 world, one SawPlank order, default rules, world_id and city 7.
|
||||
// The v13 frame is byte-for-byte original (SHA256
|
||||
// 28043dcc2a9faa6e1b217eb19df5807e159a0ac4bfdcd65de464034527557847).
|
||||
// v1/v8 bodies apply their historical field/footer layout to that fixed fixture.
|
||||
std::string old_checkpoint(std::size_t variant) {
|
||||
constexpr std::array<std::string_view, 3> hex{
|
||||
"53544843484b505401000000b6000000cb000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c4552530d0000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
"000000000000000000bd7066618db314e2ca874c7eae12d9f8cc45a222c446e23906dbd6645710cd62",
|
||||
"53544843484b505401000000b6000000a4000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c455253010000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"000000000000000000000000224ae83870bea33ac3afafcd0190d032cb7b517123fb4ac93479daa4cc71cc74ed17ba385446"
|
||||
"aa69",
|
||||
"53544843484b505401000000b6000000d3000000000000009102030405064708890a0b0c0d0e0f1007000000000000000000"
|
||||
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
|
||||
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
|
||||
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
|
||||
"7124188d337f534554544c455253080000002b00000000000000030000000300000000000000000000000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000001000000000000000100000000000000010000000000000001"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000000"
|
||||
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
"000000000000000000f92cb77443aeca815745b0132cc684f43738865a4034d4474a373902a294e9c31801c47cf80037e4",
|
||||
};
|
||||
std::string result;
|
||||
const auto value = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
|
||||
for (std::size_t i = 0; i < hex[variant].size(); i += 2) {
|
||||
result.push_back(static_cast<char>(value(hex[variant][i]) * 16 + value(hex[variant][i + 1])));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Testing::Suite<CheckpointTests> {
|
||||
[[= Void::Testing::tag("production-id")]] Test test_authentic_v1_import_and_authenticated_schema_body_pairing();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_round_trip_preserves_identity_and_legacy_world_bytes();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_mid_carry_round_trip_continues_the_same_world();
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_selected_rules_survive_catalog_reordering();
|
||||
@@ -123,6 +167,35 @@ struct [[= Void::Testing::name("CheckpointTests")]] CheckpointTests : Void::Test
|
||||
[[= Void::Testing::tag("checkpoint")]] Test test_world_body_larger_than_one_shot_hash_limit();
|
||||
};
|
||||
|
||||
Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pairing() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
for (std::size_t variant = 0; variant < 3; ++variant) {
|
||||
auto imported = decoded(old_checkpoint(variant), catalog);
|
||||
require(imported.world_id == world_id && imported.city == 7 && imported.rules == rules &&
|
||||
imported.world->production_orders().size() == 1 && imported.world->production_orders().front().id == 1,
|
||||
"authentic schema-1 checkpoint did not import its legacy body");
|
||||
imported.world->queue_production({2, 2}, RecipeId::SawPlank);
|
||||
require(imported.world->production_orders().back().id == 2, "legacy import did not set its next production ID");
|
||||
}
|
||||
auto imported = decoded(old_checkpoint(0), catalog);
|
||||
auto current = encoded(*imported.world, rules);
|
||||
require(static_cast<unsigned char>(current[8]) == 2 &&
|
||||
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 14,
|
||||
"new checkpoint lacks the current schema/body pair");
|
||||
auto false_legacy = current;
|
||||
change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy);
|
||||
rejected(false_legacy, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
auto false_current = old_checkpoint(0);
|
||||
change(false_current, 8, std::uint32_t{2}); rehash(false_current);
|
||||
rejected(false_current, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
for (std::size_t variant : {1U, 2U}) {
|
||||
auto wrong = old_checkpoint(variant); // Inner FNV and outer SHA are both valid.
|
||||
change(wrong, 8, std::uint32_t{2}); rehash(wrong);
|
||||
rejected(wrong, catalog, CheckpointError::InvalidWorld, "world.version");
|
||||
}
|
||||
}
|
||||
|
||||
Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes() {
|
||||
const auto catalog = checked(builtin_rule_packages());
|
||||
const auto rules = checked(default_rules_manifest());
|
||||
@@ -137,8 +210,10 @@ Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes(
|
||||
"checkpoint lost stable world identity, city or rules");
|
||||
require(saved_state(*restored.world) == before && saved_state(world) == before,
|
||||
"checkpoint changed the original or restored canonical state");
|
||||
require(bytes.substr(layout(bytes).body_begin, before.size()) == before,
|
||||
"checkpoint did not use the existing world serialization");
|
||||
std::ostringstream modern(std::ios::binary);
|
||||
world.write_save(modern, WorldSaveFormat::Current14);
|
||||
require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(),
|
||||
"checkpoint did not use the current world serialization");
|
||||
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
|
||||
"canonical serialization version changed");
|
||||
require(encoded(*restored.world, restored.rules) == bytes, "re-encoding changed the checkpoint frame");
|
||||
|
||||
+14
-13
@@ -242,7 +242,7 @@ Test CoreTests::test_production_reservations_and_construction() {
|
||||
world.storages()[1].item_count(ItemType::StoneBlock) == 2,
|
||||
"materials left a store before the builder reached it");
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0) continue;
|
||||
if (agent.production_id != orders[0].id) continue;
|
||||
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
|
||||
agent.inventory.item_count(ItemType::StoneBlock) == 0,
|
||||
"the builder's bag does not match the first pickup");
|
||||
@@ -253,14 +253,14 @@ Test CoreTests::test_production_reservations_and_construction() {
|
||||
require(world.storages()[1].item_count(ItemType::StoneBlock) == 0,
|
||||
"the builder did not pick up the second shipment");
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0) continue;
|
||||
if (agent.production_id != orders[0].id) continue;
|
||||
require(agent.inventory.item_count(ItemType::Plank) == 3 &&
|
||||
agent.inventory.item_count(ItemType::StoneBlock) == 2,
|
||||
"the builder's bag does not match the complete haul");
|
||||
}
|
||||
}
|
||||
for (const auto& agent : world.agents()) {
|
||||
if (agent.production_index != 0 || agent.state != settlement::AgentState::Working) continue;
|
||||
if (agent.production_id != orders[0].id || agent.state != settlement::AgentState::Working) continue;
|
||||
require(agent.position == orders[0].position && orders[0].delivery_stops.empty(),
|
||||
"construction started before the builder reached the site with its materials");
|
||||
require(agent.inventory.empty(), "the builder retained the cargo after unloading");
|
||||
@@ -483,15 +483,16 @@ Test CoreTests::test_bed_parts_are_delivered_separately() {
|
||||
for (int tick = 0; tick < 250 && world->scenario_progress().assigned_beds < 2; ++tick) {
|
||||
world->step();
|
||||
for (const auto& agent : world->agents()) {
|
||||
if (agent.production_index == no_entity_index || agent.state != AgentState::Hauling) continue;
|
||||
const auto& order = world->production_orders()[agent.production_index];
|
||||
if (agent.production_id == 0 || agent.state != AgentState::Hauling) continue;
|
||||
const auto& order = *world->find_production(agent.production_id);
|
||||
const auto order_index = static_cast<std::size_t>(&order - world->production_orders().data());
|
||||
const auto expected = order.bed_stage == BedStage::Foundation
|
||||
? (order.position == wood_bed ? ItemType::Wood : ItemType::Stone) : ItemType::Cloth;
|
||||
require(agent.inventory.item_count(expected) == 1,
|
||||
"the resident did not carry the raw material required by this stage");
|
||||
const auto bit = 1U << static_cast<unsigned>(order.bed_stage);
|
||||
if ((seen[agent.production_index] & bit) == 0) {
|
||||
seen[agent.production_index] |= bit;
|
||||
if ((seen[order_index] & bit) == 0) {
|
||||
seen[order_index] |= bit;
|
||||
auto copy = save_roundtrip(*world);
|
||||
copy->step();
|
||||
}
|
||||
@@ -696,7 +697,7 @@ Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignment
|
||||
for (std::size_t index = 0; index < 3; ++index) {
|
||||
require(world.agents()[index].resource_node_id == world.resource_nodes()[index].id, "a specialist chose the wrong resource");
|
||||
}
|
||||
require(world.agents()[3].production_index == 0 && world.agents()[3].resource_node_id == 0,
|
||||
require(world.agents()[3].production_id == world.production_orders().front().id && world.agents()[3].resource_node_id == 0,
|
||||
"the builder did not take the construction job");
|
||||
require(assign(miner, Profession::Woodcutter) == CommandStatus::Accepted &&
|
||||
world.agents()[2].resource_node_id == world.resource_nodes()[2].id,
|
||||
@@ -774,7 +775,7 @@ Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() {
|
||||
saved_flax_in_transit = true;
|
||||
}
|
||||
if (!saved_active_weaving && loom_order.recipe == RecipeId::WeaveCloth && loom_order.state == JobState::InProgress) {
|
||||
require(world.agents()[1].production_index == 0 &&
|
||||
require(world.agents()[1].production_id == world.production_orders().front().id &&
|
||||
world.object_status(moved_loom, true) == CommandStatus::Busy,
|
||||
"the loom was assigned to the wrong worker or could move while active");
|
||||
restored = save_roundtrip(world);
|
||||
@@ -1126,8 +1127,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
|
||||
world->step();
|
||||
const auto& maker = world->agents()[1];
|
||||
if (variant.item == ItemType::MiningRack && !saved_stone_stop &&
|
||||
maker.production_index != no_entity_index &&
|
||||
world->production_orders()[maker.production_index].recipe == variant.craft &&
|
||||
maker.production_id != 0 &&
|
||||
world->find_production(maker.production_id)->recipe == variant.craft &&
|
||||
maker.inventory.item_count(ItemType::Stone) != 0 && maker.inventory.item_count(ItemType::Wood) == 0) {
|
||||
require(world->storages()[1].reserved_slots == 0, "output space was reserved before collecting wood");
|
||||
saved_stone_stop = true;
|
||||
@@ -1135,8 +1136,8 @@ Test CoreTests::test_carpenter_makes_furnishings_for_rooms() {
|
||||
continue;
|
||||
}
|
||||
if (!saved_workshop && maker.state == AgentState::Working && maker.position == workshop &&
|
||||
maker.production_index != no_entity_index &&
|
||||
world->production_orders()[maker.production_index].recipe == variant.craft) {
|
||||
maker.production_id != 0 &&
|
||||
world->find_production(maker.production_id)->recipe == variant.craft) {
|
||||
require(world->storages()[1].reserved_slots == 1, "output space was not reserved while crafting");
|
||||
saved_workshop = true;
|
||||
world = save_roundtrip(*world);
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
#define NOMINMAX
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <spanstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -29,11 +41,128 @@ constexpr auto command_bytes = "\x23\x00\x00\x00\x03"
|
||||
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;
|
||||
|
||||
WorldCheckpoint colony_checkpoint() {
|
||||
auto identity = Void::Uuid::try_v4();
|
||||
auto rules = default_rules_manifest();
|
||||
require(identity.has_value() && rules.has_value());
|
||||
return {make_first_colony(2), *identity, 1, std::move(*rules)};
|
||||
}
|
||||
|
||||
template<class Pump, class Condition>
|
||||
void pump_until(Pump pump, Condition condition, const char* message) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 3s;
|
||||
do {
|
||||
pump();
|
||||
if (condition()) return;
|
||||
std::this_thread::sleep_for(1ms);
|
||||
} while (std::chrono::steady_clock::now() < deadline);
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
struct CaptureGate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool armed = false;
|
||||
bool entered = false;
|
||||
bool released = false;
|
||||
|
||||
void capture(RuntimePhase phase) {
|
||||
if (phase != RuntimePhase::BeforeCapture) return;
|
||||
std::unique_lock lock(mutex);
|
||||
if (!armed) return;
|
||||
entered = true;
|
||||
changed.notify_all();
|
||||
if (!changed.wait_for(lock, 5s, [&] { return released; })) {
|
||||
throw std::runtime_error("LAN test capture gate timed out.");
|
||||
}
|
||||
}
|
||||
|
||||
void arm() { std::lock_guard lock(mutex); armed = true; }
|
||||
bool waiting() { std::lock_guard lock(mutex); return entered; }
|
||||
void release() {
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
struct RawGuest {
|
||||
SOCKET socket = INVALID_SOCKET;
|
||||
std::string input;
|
||||
std::string output;
|
||||
bool closed = false;
|
||||
std::vector<lan_wire::Receipt> receipts;
|
||||
std::unique_ptr<World> snapshot;
|
||||
|
||||
RawGuest(std::uint16_t port, std::uint64_t key) {
|
||||
socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (socket == INVALID_SOCKET) throw std::runtime_error("Raw guest socket failed.");
|
||||
auto close_on_error = Void::Scope::on_exit([&] { closesocket(socket); });
|
||||
sockaddr_in remote{};
|
||||
remote.sin_family = AF_INET;
|
||||
remote.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
remote.sin_port = htons(port);
|
||||
if (connect(socket, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0) {
|
||||
throw std::runtime_error("Raw guest connect failed.");
|
||||
}
|
||||
u_long enabled = 1;
|
||||
require(ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) == 0);
|
||||
const auto hello = lan_wire::encode_hello({lan_wire::protocol_version, key});
|
||||
lan_wire::append_frame(output, lan_wire::Message::Hello, std::string_view(hello));
|
||||
close_on_error.release();
|
||||
}
|
||||
~RawGuest() { closesocket(socket); }
|
||||
RawGuest(const RawGuest&) = delete;
|
||||
RawGuest& operator=(const RawGuest&) = delete;
|
||||
|
||||
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
|
||||
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value});
|
||||
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
|
||||
}
|
||||
|
||||
void poll() {
|
||||
if (closed) return;
|
||||
if (!output.empty()) {
|
||||
const auto sent = send(socket, output.data(), static_cast<int>(output.size()), 0);
|
||||
if (sent > 0) output.erase(0, static_cast<std::size_t>(sent));
|
||||
else if (sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
||||
}
|
||||
std::array<char, 8192> bytes{};
|
||||
for (int attempt = 0; attempt < 16 && !closed; ++attempt) {
|
||||
const auto count = recv(socket, bytes.data(), static_cast<int>(bytes.size()), 0);
|
||||
if (count == SOCKET_ERROR) {
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK) closed = true;
|
||||
break;
|
||||
}
|
||||
if (count == 0) { closed = true; break; }
|
||||
input.append(bytes.data(), static_cast<std::size_t>(count));
|
||||
std::size_t consumed = 0;
|
||||
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
|
||||
if (frame->message == lan_wire::Message::Receipt) {
|
||||
auto receipt = lan_wire::decode_receipt(frame->payload);
|
||||
require(receipt.has_value());
|
||||
receipts.push_back(*receipt);
|
||||
} else if (frame->message == lan_wire::Message::Snapshot) {
|
||||
std::ispanstream stream(frame->payload);
|
||||
snapshot = World::read_save(stream);
|
||||
}
|
||||
consumed += frame->size;
|
||||
}
|
||||
input.erase(0, consumed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct LanTests : Void::Testing::Suite<LanTests> {
|
||||
[[= 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();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_receipts_and_corrected_legacy_sequence();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_wrong_sequence_busy_and_pipelining();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
|
||||
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
|
||||
};
|
||||
|
||||
Test LanTests::test_protocol_11_fixed_messages() {
|
||||
@@ -295,4 +424,197 @@ Test LanTests::test_shared_colony_over_loopback() {
|
||||
require(authoritative->production_orders().size() == previous_size + 10);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_receipts_and_corrected_legacy_sequence() {
|
||||
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
std::unique_ptr<World> view;
|
||||
const auto pump = [&] {
|
||||
host.poll_host(runtime);
|
||||
if (auto latest = guest.poll_guest()) view = std::move(latest);
|
||||
};
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Runtime guest did not join.");
|
||||
require(view && view->tick() == 0);
|
||||
const auto resident = view->agents().back().id;
|
||||
require(guest.submit(CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), {}, resident));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Profession receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::AssignProfession &&
|
||||
result->resident == resident && result->value == static_cast<std::uint8_t>(Profession::Miner));
|
||||
require(runtime.latest()->world->agents().back().profession == Profession::Miner);
|
||||
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, static_cast<std::uint8_t>(BedBase::Stone)));
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Bed receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->cell == GridPosition{16, 18});
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 0));
|
||||
require(guest.submit(CommandKind::SetForaging, {14, 12}, 1));
|
||||
pump_until(pump, [&] { return guest.take_rejection().has_value(); }, "Bed rejection missing.");
|
||||
// The failed result remains undrained. The queued correction cannot execute.
|
||||
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
||||
require(runtime.latest()->next_requests[1] == 4);
|
||||
result = guest.take_result();
|
||||
require(result && result->status == CommandStatus::InvalidTarget && result->kind == CommandKind::PlaceBed &&
|
||||
result->cell == GridPosition{16, 18} && result->destination == GridPosition{} && result->value == 0);
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "Corrected command receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
||||
require(runtime.latest()->next_requests[1] == 5 && runtime.latest()->world->next_command_sequence(2) == 4);
|
||||
require(runtime.latest()->world->production_orders().size() == 1);
|
||||
pump_until(pump, [&] { return view->next_command_sequence(2) == 4; }, "Same-tick snapshot missing.");
|
||||
require(view->tick() == 0);
|
||||
guest.leave();
|
||||
require(!guest.take_result());
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_wrong_sequence_busy_and_pipelining() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.capacity = 1, .ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
SimulationRuntime runtime(colony_checkpoint(), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host;
|
||||
host.host(0, true);
|
||||
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
|
||||
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
|
||||
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Raw runtime guest did not join.");
|
||||
guest.command(99, CommandKind::SetForaging, {14, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Wrong-sequence receipt missing.");
|
||||
require(guest.receipts[0].status == CommandStatus::WrongSequence && guest.receipts[0].next_sequence == 1);
|
||||
const auto snapshot = runtime.latest();
|
||||
gate.arm();
|
||||
const auto& id = snapshot->identity;
|
||||
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, 1,
|
||||
CommandPayload{CommandKind::SetForaging, {13, 14}, 1}});
|
||||
require(local.admission == RuntimeAdmission::Accepted);
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Owner did not reach blocked capture.");
|
||||
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Busy receipt missing.");
|
||||
require(guest.receipts[1].status == CommandStatus::Busy && guest.receipts[1].next_sequence == 1);
|
||||
require(runtime.latest()->next_requests[1] == 1);
|
||||
gate.release();
|
||||
require(local.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
|
||||
|
||||
// Two coalesced commands cannot turn one guest slot into multiple in-flight operations.
|
||||
guest.command(1, CommandKind::SetForaging, {14, 12}, 1);
|
||||
guest.command(2, CommandKind::SetForaging, {18, 12}, 1);
|
||||
pump_until(pump, [&] { return guest.closed; }, "Pipelined guest was not bounded.");
|
||||
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
|
||||
pump_until(pump, [&] {
|
||||
fence = runtime.synchronize();
|
||||
return fence.admission == RuntimeAdmission::Accepted;
|
||||
}, "Owner did not release its admission slot.");
|
||||
require(fence.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
|
||||
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->next_command_sequence(2) == 2);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_retains_slot_work_across_reconnect() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
SimulationRuntime runtime(colony_checkpoint(), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host, first, next;
|
||||
host.host(0, true);
|
||||
const auto code = host.join_code();
|
||||
const auto pump = [&] {
|
||||
host.poll_host(runtime);
|
||||
static_cast<void>(first.poll_guest());
|
||||
static_cast<void>(next.poll_guest());
|
||||
};
|
||||
first.join("127.0.0.1", code, host.port());
|
||||
pump_until(pump, [&] { return first.state() == LanState::GuestConnected; }, "First guest did not join.");
|
||||
gate.arm();
|
||||
require(first.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Guest command did not reach blocked owner.");
|
||||
require(runtime.latest()->world->production_orders().empty());
|
||||
first.leave();
|
||||
pump_until(pump, [&] { return host.state() == LanState::Hosting; }, "Old socket did not close.");
|
||||
next.join("127.0.0.1", code, host.port());
|
||||
for (int attempt = 0; attempt < 20; ++attempt) pump();
|
||||
require(next.state() == LanState::Connecting && !next.take_result());
|
||||
gate.release();
|
||||
pump_until(pump, [&] { return next.state() == LanState::GuestConnected; }, "Reconnected guest did not join.");
|
||||
require(!next.take_result());
|
||||
require(runtime.latest()->world->production_orders().size() == 1);
|
||||
require(runtime.latest()->next_requests[1] == 2);
|
||||
require(next.submit(CommandKind::SetForaging, {14, 12}, 1));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = next.take_result(); return result.has_value(); }, "New guest receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && result->kind == CommandKind::SetForaging);
|
||||
require(runtime.latest()->next_requests[1] == 3 && runtime.latest()->world->next_command_sequence(2) == 3);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_reauthenticates_after_pending_rollback() {
|
||||
CaptureGate gate;
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
|
||||
auto initial = colony_checkpoint();
|
||||
const auto world_id = initial.world_id;
|
||||
SimulationRuntime runtime(std::move(initial), options);
|
||||
auto release = Void::Scope::on_exit([&] { gate.release(); });
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
const auto pump = [&] { host.poll_host(runtime); static_cast<void>(guest.poll_guest()); };
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Rollback guest did not join.");
|
||||
const auto old_session = runtime.latest()->identity.session;
|
||||
gate.arm();
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return gate.waiting(); }, "Rollback guest command did not block.");
|
||||
auto ticket = runtime.begin_load();
|
||||
require(ticket.has_value());
|
||||
auto rollback = colony_checkpoint();
|
||||
rollback.world_id = world_id;
|
||||
auto installed = runtime.try_install(*ticket, rollback);
|
||||
require(installed.admission == RuntimeAdmission::Accepted);
|
||||
gate.release();
|
||||
require(installed.completion.wait_for(3s) == std::future_status::ready);
|
||||
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Old epoch peer stayed connected.");
|
||||
require(runtime.latest()->identity.session != old_session && runtime.latest()->identity.world == world_id);
|
||||
require(runtime.latest()->world->production_orders().empty() && !guest.take_result());
|
||||
guest.reconnect();
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Guest could not reauthenticate.");
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
std::optional<LanCommandResult> result;
|
||||
pump_until(pump, [&] { result = guest.take_result(); return result.has_value(); }, "New epoch receipt missing.");
|
||||
require(result->status == CommandStatus::Accepted && runtime.latest()->next_requests[1] == 2);
|
||||
}
|
||||
|
||||
Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
|
||||
auto initial = colony_checkpoint();
|
||||
auto packages = builtin_rule_packages();
|
||||
require(packages.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
auto rules = resolve_rules(*packages, selected);
|
||||
require(rules.has_value());
|
||||
initial.rules = std::move(*rules);
|
||||
SimulationRuntime incompatible(std::move(initial), {.ticking = false});
|
||||
LanSession host, guest;
|
||||
host.host(0, true);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
host.poll_host(incompatible);
|
||||
require(host.state() == LanState::Hosting && host.detail().find("default rules") != std::string::npos);
|
||||
for (int attempt = 0; attempt < 20; ++attempt) {
|
||||
host.poll_host(incompatible);
|
||||
require(!guest.poll_guest());
|
||||
}
|
||||
require(guest.state() != LanState::GuestConnected);
|
||||
guest.leave();
|
||||
RuntimeOptions options{.ticking = false};
|
||||
options.observer = [](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected capture failure.");
|
||||
};
|
||||
SimulationRuntime faulting(colony_checkpoint(), options);
|
||||
guest.join("127.0.0.1", host.join_code(), host.port());
|
||||
const auto pump = [&] { host.poll_host(faulting); static_cast<void>(guest.poll_guest()); };
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestConnected; }, "Fault guest did not join.");
|
||||
require(guest.submit(CommandKind::PlaceBed, {16, 18}, 1));
|
||||
pump_until(pump, [&] { return guest.state() == LanState::GuestDisconnected; }, "Faulted peer stayed connected.");
|
||||
require(faulting.view().state == RuntimeState::Faulted && faulting.latest()->world->production_orders().empty());
|
||||
require(!guest.take_result());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,352 @@
|
||||
#include "settlement/core/checkpoint.hpp"
|
||||
#include "settlement/core/simulation_runtime.hpp"
|
||||
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto terminal = std::numeric_limits<ProductionId>::max();
|
||||
constexpr std::size_t next_production_offset = 101;
|
||||
constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}};
|
||||
|
||||
void require(bool condition, const char* message = "production identity invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
std::string bytes(const World& world, WorldSaveFormat format = WorldSaveFormat::Current14) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, format);
|
||||
return stream.str();
|
||||
}
|
||||
std::unique_ptr<World> restore(const std::string& data, std::size_t workers = 1) {
|
||||
std::istringstream input(data, std::ios::binary);
|
||||
return World::read_save(input, workers, workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
|
||||
}
|
||||
template<class T>
|
||||
void put(std::string& data, std::size_t offset, T value) {
|
||||
Void::Binary::Writer writer(std::as_writable_bytes(std::span{data.data(), data.size()}).subspan(offset));
|
||||
require(writer.writeLittle(value).has_value(), "fixture write failed");
|
||||
}
|
||||
std::unique_ptr<World> with_next(const World& world, ProductionId next) {
|
||||
auto data = bytes(world);
|
||||
put(data, next_production_offset, next);
|
||||
return restore(data);
|
||||
}
|
||||
std::unique_ptr<World> checkpoint(const World& world, std::size_t workers = 1) {
|
||||
const auto rules = default_rules_manifest();
|
||||
const auto catalog = builtin_rule_packages();
|
||||
require(rules.has_value() && catalog.has_value());
|
||||
const auto encoded = encode_checkpoint(world, world_id, 7, *rules);
|
||||
require(encoded.has_value());
|
||||
auto decoded = decode_checkpoint(*encoded, *catalog, workers,
|
||||
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
|
||||
require(decoded.has_value() && decoded->world_id == world_id && bytes(*decoded->world) == bytes(world),
|
||||
"modern checkpoint changed stable identity or high-water state");
|
||||
return std::move(decoded->world);
|
||||
}
|
||||
CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
|
||||
GridPosition destination = {}) {
|
||||
return world.apply_command({1, world.next_command_sequence(1), kind, cell, value, destination}).status;
|
||||
}
|
||||
std::unique_ptr<World> scenario(bool legacy_beds = false) {
|
||||
auto world = std::make_unique<World>(43, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
world->start_scenario({2, 2});
|
||||
if (legacy_beds) {
|
||||
auto data = bytes(*world);
|
||||
data.back() = 0; // Historical scenario without staged beds.
|
||||
world = restore(data);
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
// Parse only field boundaries, using the public version-14 wire layout. This
|
||||
// avoids relying on C++ object layout when attacking references/counters.
|
||||
struct Locations { std::vector<std::size_t> orders; std::vector<std::size_t> links; };
|
||||
Locations locations(const std::string& data) {
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{data.data(), data.size()}));
|
||||
const auto skip = [&](std::size_t n) { require(reader.skip(n).has_value()); };
|
||||
const auto count = [&] { return reader.readLittle<std::uint32_t>().value(); };
|
||||
const auto route = [&] { const auto n = count(); skip(static_cast<std::size_t>(n) * 8); };
|
||||
skip(20);
|
||||
const auto width = count(), height = count();
|
||||
skip(81 + static_cast<std::size_t>(width) * height);
|
||||
Locations found;
|
||||
const auto agents = count();
|
||||
for (std::uint32_t i = 0; i < agents; ++i) {
|
||||
skip(25); route(); skip(28 + item_type_count * 4); route();
|
||||
found.links.push_back(reader.position()); skip(14);
|
||||
}
|
||||
const auto jobs = count(); skip(static_cast<std::size_t>(jobs) * 25);
|
||||
const auto nodes = count(); skip(static_cast<std::size_t>(nodes) * 39);
|
||||
const auto stores = count();
|
||||
for (std::uint32_t i = 0; i < stores; ++i) { skip(25); const auto stacks = count(); skip(stacks * 9U); }
|
||||
const auto orders = count();
|
||||
for (std::uint32_t i = 0; i < orders; ++i) {
|
||||
found.orders.push_back(reader.position()); skip(18);
|
||||
const auto materials = count(); skip(materials * 13U);
|
||||
const auto stops = count();
|
||||
for (std::uint32_t j = 0; j < stops; ++j) { skip(8); route(); }
|
||||
skip(18);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
void rejected(const std::string& data) {
|
||||
bool failed = false;
|
||||
try { static_cast<void>(restore(data)); } catch (const std::runtime_error&) { failed = true; }
|
||||
require(failed, "corrupt stable production state was accepted");
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("ProductionIdentityTests")]] ProductionIdentityTests
|
||||
: Void::Testing::Suite<ProductionIdentityTests> {
|
||||
[[= Void::Testing::tag("production-id")]] Test active_delivery_survives_lower_deletion_and_modern_replay();
|
||||
[[= Void::Testing::tag("production-id")]] Test highest_and_all_deletions_preserve_high_water();
|
||||
[[= Void::Testing::tag("production-id")]] Test last_single_id_and_complete_command_batches();
|
||||
[[= Void::Testing::tag("production-id")]] Test demolition_preflights_every_product_before_losing_stock();
|
||||
[[= Void::Testing::tag("production-id")]] Test demolition_counts_existing_supply_and_pending_crafts_exactly();
|
||||
[[= Void::Testing::tag("production-id")]] Test legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result();
|
||||
[[= Void::Testing::tag("production-id")]] Test malformed_ids_and_references_fail_before_dereference();
|
||||
[[= Void::Testing::tag("production-id")]] Test legacy_projection_imports_deterministic_dense_ids();
|
||||
};
|
||||
|
||||
Test ProductionIdentityTests::active_delivery_survives_lower_deletion_and_modern_replay() {
|
||||
World world(42, 32, 32, 1, ExecutionMode::SerialReference);
|
||||
const auto store = world.add_storage({3, 3}, 20);
|
||||
world.stock_storage(store, ItemType::Plank, 3);
|
||||
world.stock_storage(store, ItemType::StoneBlock, 2);
|
||||
static_cast<void>(world.spawn_agent({2, 3}));
|
||||
world.queue_production({20, 20}, RecipeId::BuildMedicineCabinet); // No wood: remains available.
|
||||
world.queue_production({14, 3}, RecipeId::BuildCabin);
|
||||
const auto lower = world.production_orders().front().id;
|
||||
const auto active = world.production_orders().back().id;
|
||||
for (int tick = 0; tick < 30 && world.agents().front().inventory.empty(); ++tick) world.step();
|
||||
require(world.agents().front().production_id == active && !world.agents().front().inventory.empty(),
|
||||
"fixture must exercise actual mid-delivery cargo");
|
||||
require(command(world, CommandKind::DemolishObject, {20, 20}) == CommandStatus::Accepted);
|
||||
require(world.find_production(lower) == nullptr && world.find_production(0) == nullptr &&
|
||||
world.find_production(terminal) == nullptr && world.agents().front().production_id == active);
|
||||
const auto legacy_bytes = bytes(world, WorldSaveFormat::Legacy13);
|
||||
const auto legacy = restore(legacy_bytes);
|
||||
require(legacy->agents().front().production_id == legacy->production_orders().front().id &&
|
||||
bytes(*legacy, WorldSaveFormat::Legacy13) == legacy_bytes,
|
||||
"legacy positional projection changed a live delivery after lower deletion");
|
||||
const auto held = world.capture();
|
||||
const auto frozen = bytes(*held);
|
||||
std::vector<std::unique_ptr<World>> copies;
|
||||
for (auto workers : {1U, 2U, 6U, 12U}) copies.push_back(checkpoint(world, workers));
|
||||
for (int tick = 0; tick < 70; ++tick) {
|
||||
world.step();
|
||||
for (auto& copy : copies) {
|
||||
copy->step();
|
||||
require(bytes(*copy) == bytes(world), "modern canonical tick replay diverged across worker counts");
|
||||
}
|
||||
require(bytes(*held) == frozen, "capture did not retain production state independently");
|
||||
}
|
||||
require(world.find_production(active)->state == JobState::Completed);
|
||||
require(command(world, CommandKind::DemolishObject, {14, 3}) == CommandStatus::Accepted);
|
||||
auto empty = checkpoint(world);
|
||||
empty->queue_production({15, 3}, RecipeId::BuildCabin);
|
||||
require(empty->production_orders().front().id > active, "deleting all orders reissued an identity");
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::highest_and_all_deletions_preserve_high_water() {
|
||||
auto world = scenario();
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto highest = world->production_orders().back().id;
|
||||
require(command(*world, CommandKind::DemolishObject, {7, 6}) == CommandStatus::Accepted);
|
||||
world = checkpoint(*world);
|
||||
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(world->production_orders().back().id == highest + 1);
|
||||
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
|
||||
require(command(*world, CommandKind::DemolishObject, {8, 6}) == CommandStatus::Accepted);
|
||||
world = checkpoint(*world);
|
||||
world->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(world->production_orders().front().id == highest + 2);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::last_single_id_and_complete_command_batches() {
|
||||
World basic(42, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
auto single = with_next(basic, terminal - 1);
|
||||
single->queue_production({6, 6}, RecipeId::BuildCabin);
|
||||
require(single->production_orders().back().id == terminal - 1);
|
||||
single = checkpoint(*single);
|
||||
const auto before = bytes(*single);
|
||||
bool exhausted = false;
|
||||
try { single->queue_production({7, 6}, RecipeId::BuildCabin); }
|
||||
catch (const ProductionCapacityError&) { exhausted = true; }
|
||||
require(exhausted && bytes(*single) == before);
|
||||
|
||||
struct Batch { CommandKind kind; std::uint8_t value; std::size_t count; bool legacy; GridPosition last; };
|
||||
const RoomPlan furnished{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Doctor};
|
||||
const RoomPlan empty{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Empty};
|
||||
const std::array batches{
|
||||
Batch{CommandKind::PlaceBed, 0, 1, false, {}},
|
||||
Batch{CommandKind::PlaceBed, 0, 2, true, {}},
|
||||
Batch{CommandKind::PlaceLoom, 0, 2, false, {}},
|
||||
Batch{CommandKind::CraftDoor, 0, 1, false, {}},
|
||||
Batch{CommandKind::CraftFurniture, static_cast<std::uint8_t>(ItemType::MiningRack), 1, false, {}},
|
||||
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 20, false, furnished.last},
|
||||
Batch{CommandKind::PlaceRoom, furnished.placement_value(), 21, true, furnished.last},
|
||||
Batch{CommandKind::PlaceRoom, empty.placement_value(), 17, false, empty.last}};
|
||||
for (const auto& batch : batches) {
|
||||
const auto initial = scenario(batch.legacy);
|
||||
auto refused = with_next(*initial, terminal - batch.count + 1);
|
||||
const auto original = bytes(*refused);
|
||||
require(command(*refused, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Busy,
|
||||
"insufficient complete command batch was not Busy");
|
||||
require(bytes(*refused) == original && refused->next_command_sequence(1) == 1,
|
||||
"batch refusal changed orders, counter, stock, terrain or command sequence");
|
||||
auto accepted = with_next(*initial, terminal - batch.count);
|
||||
require(command(*accepted, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Accepted);
|
||||
require(accepted->production_orders().size() == batch.count &&
|
||||
accepted->production_orders().back().id == terminal - 1, "batch allocation count or last ID differs");
|
||||
accepted = checkpoint(*accepted);
|
||||
const auto full = bytes(*accepted);
|
||||
require(command(*accepted, CommandKind::CraftDoor) == CommandStatus::Busy && bytes(*accepted) == full);
|
||||
}
|
||||
static_cast<void>(basic.spawn_agent({2, 2}));
|
||||
auto loom = with_next(basic, terminal - 1);
|
||||
require(command(*loom, CommandKind::PlaceLoom, {6, 6}) == CommandStatus::Accepted &&
|
||||
loom->production_orders().size() == 1 && loom->production_orders().front().id == terminal - 1);
|
||||
for (auto count : {5U, 6U}) {
|
||||
auto cabin = with_next(basic, terminal - count);
|
||||
const auto original = bytes(*cabin);
|
||||
bool failed = false;
|
||||
try { cabin->queue_cabin({10, 10}, {3, 3}, {4, 3}); }
|
||||
catch (const ProductionCapacityError&) { failed = true; }
|
||||
require(count == 5 ? failed && bytes(*cabin) == original :
|
||||
!failed && cabin->production_orders().size() == 6 && cabin->production_orders().back().id == terminal - 1);
|
||||
}
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::demolition_preflights_every_product_before_losing_stock() {
|
||||
auto initial = scenario();
|
||||
const auto store = initial->add_storage({3, 3}, 20);
|
||||
initial->stock_storage(store, ItemType::WoodenDoor, 1);
|
||||
initial->stock_storage(store, ItemType::Loom, 1);
|
||||
initial->stock_storage(store, ItemType::MedicineCabinet, 1);
|
||||
initial->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
|
||||
initial->queue_production({7, 6}, RecipeId::InstallLoom);
|
||||
initial->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
|
||||
for (auto available : {0U, 1U, 2U}) {
|
||||
auto world = with_next(*initial, terminal - available);
|
||||
const auto before = bytes(*world);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Busy && bytes(*world) == before,
|
||||
"multi-product demolition lost stock or allocated a partial replacement batch");
|
||||
require(world->find_storage(store) != nullptr && world->next_command_sequence(1) == 1);
|
||||
}
|
||||
auto world = with_next(*initial, terminal - 3);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted);
|
||||
require(world->find_storage(store) == nullptr && world->production_orders().size() == 6);
|
||||
for (auto recipe : {RecipeId::CraftWoodenDoor, RecipeId::CraftLoom, RecipeId::CraftMedicineCabinet}) {
|
||||
require(std::count_if(world->production_orders().begin(), world->production_orders().end(),
|
||||
[&](const auto& order) { return order.recipe == recipe; }) == 1);
|
||||
}
|
||||
static_cast<void>(checkpoint(*world));
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::demolition_counts_existing_supply_and_pending_crafts_exactly() {
|
||||
auto world = scenario();
|
||||
const auto lost = world->add_storage({3, 3}, 20);
|
||||
const auto retained = world->add_storage({4, 3}, 20);
|
||||
world->stock_storage(lost, ItemType::WoodenDoor, 1);
|
||||
world->stock_storage(lost, ItemType::Loom, 1);
|
||||
world->stock_storage(lost, ItemType::MedicineCabinet, 1);
|
||||
world->stock_storage(retained, ItemType::WoodenDoor, 1);
|
||||
world->queue_production({6, 6}, RecipeId::InstallDoorAlongX);
|
||||
world->queue_production({7, 6}, RecipeId::InstallLoom);
|
||||
world->queue_production({8, 6}, RecipeId::InstallMedicineCabinet);
|
||||
world->queue_production({2, 2}, RecipeId::CraftLoom);
|
||||
world = with_next(*world, terminal - 1);
|
||||
require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted,
|
||||
"demolition overcounted replacement orders already covered by stock or pending craft");
|
||||
require(world->production_orders().size() == 5 && world->production_orders().back().recipe == RecipeId::CraftMedicineCabinet &&
|
||||
world->production_orders().back().id == terminal - 1 && world->find_storage(retained)->item_count(ItemType::WoodenDoor) == 1);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result() {
|
||||
World initial(42, 24, 24, 1, ExecutionMode::SerialReference);
|
||||
static_cast<void>(initial.spawn_agent({2, 2}));
|
||||
auto world = with_next(initial, terminal - 5);
|
||||
const auto before = bytes(*world);
|
||||
auto rules = default_rules_manifest(); require(rules.has_value());
|
||||
SimulationRuntime runtime(WorldCheckpoint{std::move(world), world_id, 7, *rules}, {.ticking = false});
|
||||
const auto identity = runtime.latest()->identity;
|
||||
const CommandEnvelope cabin{command_envelope_version, identity.world, identity.session, identity.city, 1,
|
||||
LegacyCabinPayload{{10, 10}, {3, 3}, {4, 3}}};
|
||||
auto result = runtime.try_submit({1}, cabin);
|
||||
require(result.admission == RuntimeAdmission::Accepted);
|
||||
auto completed = result.completion.get();
|
||||
require(completed.outcome == RuntimeOutcome::Completed && completed.receipt ==
|
||||
DispatchReceipt{DispatchStatus::Completed, CommandStatus::Busy, 0, 0});
|
||||
auto repeat = runtime.try_submit({1}, cabin);
|
||||
require(repeat.admission == RuntimeAdmission::Accepted && repeat.completion.get().receipt == completed.receipt);
|
||||
require(runtime.lookup({1}, cabin) == completed.receipt && runtime.latest()->next_requests[0] == 2 &&
|
||||
runtime.view().state == RuntimeState::Running && bytes(*runtime.latest()->world) == before,
|
||||
"pre-mutation cabin refusal faulted the session, changed state or lost its retained receipt");
|
||||
const CommandEnvelope storage{command_envelope_version, identity.world, identity.session, identity.city, 2,
|
||||
CommandPayload{CommandKind::PlaceStorage, {6, 6}}};
|
||||
auto continued = runtime.try_submit({1}, storage);
|
||||
require(continued.admission == RuntimeAdmission::Accepted);
|
||||
const auto next = continued.completion.get();
|
||||
require(next.outcome == RuntimeOutcome::Completed && next.receipt->command_status == CommandStatus::Accepted &&
|
||||
runtime.view().state == RuntimeState::Running && runtime.latest()->world->storages().size() == 1);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::malformed_ids_and_references_fail_before_dereference() {
|
||||
auto world = scenario();
|
||||
static_cast<void>(world->spawn_agent({4, 4}));
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto valid = bytes(*world);
|
||||
const auto offsets = locations(valid);
|
||||
require(offsets.orders.size() == 2 && offsets.links.size() == 1);
|
||||
for (const auto value : {ProductionId{0}, ProductionId{2}, terminal}) {
|
||||
auto data = valid; put(data, offsets.orders.front(), value); rejected(data);
|
||||
}
|
||||
auto duplicate = valid; put(duplicate, offsets.orders.back(), ProductionId{1}); rejected(duplicate);
|
||||
auto unsorted = valid; put(unsorted, offsets.orders.front(), ProductionId{2});
|
||||
put(unsorted, offsets.orders.back(), ProductionId{1}); rejected(unsorted);
|
||||
for (const auto value : {ProductionId{0}, ProductionId{2}}) {
|
||||
auto data = valid; put(data, next_production_offset, value); rejected(data);
|
||||
}
|
||||
for (const auto value : {ProductionId{1}, ProductionId{3}, terminal}) {
|
||||
auto data = valid; put(data, offsets.links.front(), value); rejected(data);
|
||||
}
|
||||
const auto store = world->add_storage({3, 3}, 20);
|
||||
world->stock_storage(store, ItemType::Wood, 4);
|
||||
world->step();
|
||||
require(world->agents().front().production_id != 0);
|
||||
const auto active = bytes(*world);
|
||||
auto none = active; put(none, locations(active).links.front(), ProductionId{0}); rejected(none);
|
||||
auto wrong = active; put(wrong, locations(active).links.front(), world->production_orders().back().id); rejected(wrong);
|
||||
}
|
||||
|
||||
Test ProductionIdentityTests::legacy_projection_imports_deterministic_dense_ids() {
|
||||
auto world = scenario();
|
||||
world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet);
|
||||
world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted);
|
||||
world = with_next(*world, 123);
|
||||
world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet);
|
||||
const auto old_bytes = bytes(*world, WorldSaveFormat::Legacy13);
|
||||
auto legacy = restore(old_bytes);
|
||||
require(legacy->production_orders()[0].id == 1 && legacy->production_orders()[1].id == 2 &&
|
||||
bytes(*legacy, WorldSaveFormat::Legacy13) == old_bytes, "legacy positional projection or deterministic import changed");
|
||||
legacy->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(legacy->production_orders().back().id == 3);
|
||||
auto modern = checkpoint(*world);
|
||||
modern->queue_production({9, 6}, RecipeId::BuildMedicineCabinet);
|
||||
require(modern->production_orders().back().id == 124);
|
||||
}
|
||||
} // namespace
|
||||
@@ -38,7 +38,7 @@ void require(bool condition, std::string_view message) {
|
||||
|
||||
std::string saved_state(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ Test SnapshotTests::test_mid_delivery_and_paused_command_state_survives_owner()
|
||||
source->step();
|
||||
carrying = source->assignment_path_cache_hits() > 0 &&
|
||||
std::any_of(source->agents().begin(), source->agents().end(), [](const Agent& agent) {
|
||||
return !agent.inventory.empty() && agent.production_index != no_entity_index;
|
||||
return !agent.inventory.empty() && agent.production_id != 0;
|
||||
});
|
||||
}
|
||||
require(carrying);
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
#include "viewer_session.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using namespace settlement::viewer;
|
||||
using namespace std::chrono_literals;
|
||||
using Void::Testing::require;
|
||||
using Void::Testing::Test;
|
||||
|
||||
struct TempFiles {
|
||||
std::filesystem::path root;
|
||||
TempFiles() {
|
||||
const auto id = Void::Uuid::try_v4();
|
||||
require(id.has_value());
|
||||
root = std::filesystem::temp_directory_path() /
|
||||
("settlement-client-" + id->to_string());
|
||||
require(std::filesystem::create_directory(root));
|
||||
}
|
||||
~TempFiles() {
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(root, error);
|
||||
}
|
||||
};
|
||||
|
||||
struct Gate {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool entered = false;
|
||||
bool released = false;
|
||||
void hold() {
|
||||
std::unique_lock lock(mutex);
|
||||
entered = true;
|
||||
changed.notify_all();
|
||||
if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timeout");
|
||||
}
|
||||
void wait() {
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, 5s, [&] { return entered; }));
|
||||
}
|
||||
void release() {
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
std::string bytes(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void write(const std::filesystem::path& path, std::string_view contents) {
|
||||
std::ofstream file(path, std::ios::binary);
|
||||
file.write(contents.data(), static_cast<std::streamsize>(contents.size()));
|
||||
file.close();
|
||||
require(file.good());
|
||||
}
|
||||
|
||||
template<class Predicate>
|
||||
std::vector<ViewerEvent> pump_until(ViewerSession& session, Predicate done) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 5s;
|
||||
std::vector<ViewerEvent> events;
|
||||
while (!done(events)) {
|
||||
auto current = session.poll();
|
||||
for (auto& event : current) events.push_back(std::move(event));
|
||||
require(std::chrono::steady_clock::now() < deadline);
|
||||
std::this_thread::yield();
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
bool has(const std::vector<ViewerEvent>& events, ViewerEventKind kind) {
|
||||
return std::any_of(events.begin(), events.end(), [kind](const auto& event) { return event.kind == kind; });
|
||||
}
|
||||
|
||||
void flush_owner(ViewerSession& session, RuntimeOutcome expected = RuntimeOutcome::Completed) {
|
||||
const auto deadline = std::chrono::steady_clock::now() + 5s;
|
||||
for (;;) {
|
||||
auto sync = session.runtime().synchronize();
|
||||
if (sync.admission == RuntimeAdmission::Busy) {
|
||||
require(std::chrono::steady_clock::now() < deadline);
|
||||
std::this_thread::yield();
|
||||
continue;
|
||||
}
|
||||
require(sync.admission == RuntimeAdmission::Accepted);
|
||||
require(sync.completion.wait_until(deadline) == std::future_status::ready);
|
||||
require(sync.completion.get().outcome == expected);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void::Testing::Suite<ViewerSessionTests> {
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_commands_wait_for_commit_and_keep_rejected_drafts_retryable();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_long_tick_allows_reset_without_joining_and_fences_old_intents();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_title_load_and_later_failed_load_supersede_old_preparation();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_unsupported_profile_and_dimensions_keep_current_world();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_save_keeps_captured_session_across_reset();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_guest_view_is_read_only_and_leave_installs_received_world();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_runtime_busy_keeps_the_same_intent_until_commit();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_initial_candidate_requires_supported_rules_and_dimensions();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_fault_retains_view_and_explicit_load_recovers();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_failed_guest_transitions_retain_received_replica();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_profiles_new_save_load_and_legacy_host_admission();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins();
|
||||
[[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules();
|
||||
};
|
||||
|
||||
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
|
||||
ViewerSession session(2, {.command_capacity = 1});
|
||||
const auto before = session.world();
|
||||
const SessionPayload payload = CommandPayload{CommandKind::SetPriority, {}, 1};
|
||||
const auto first = session.submit(payload);
|
||||
require(first.has_value());
|
||||
require(session.submit(payload) == first);
|
||||
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
|
||||
require(session.world()->work_priority() == before->work_priority());
|
||||
const auto changed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(changed.front().command == *first);
|
||||
require(changed.front().status == CommandStatus::Accepted);
|
||||
require(!session.pending(*first));
|
||||
require(session.world()->work_priority() == WorkPriority::FoodFirst);
|
||||
require(session.world()->tick() == before->tick());
|
||||
require(before->work_priority() == WorkPriority::Balanced);
|
||||
|
||||
require(session.submit(CommandPayload{CommandKind::PlaceBed, {15, 16}, 0}).has_value());
|
||||
const auto rejected = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(rejected.front().status == CommandStatus::InvalidTarget);
|
||||
require(session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}).has_value());
|
||||
const auto paused = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(paused.front().status == CommandStatus::Accepted);
|
||||
require(session.world()->paused());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_long_tick_allows_reset_without_joining_and_fences_old_intents() {
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [gate, &block](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
gate->wait();
|
||||
const auto old = session.runtime().latest();
|
||||
require(session.submit(CommandPayload{CommandKind::SetPriority, {}, 1}).has_value());
|
||||
static_cast<void>(session.poll());
|
||||
session.new_colony();
|
||||
const auto pending = session.poll();
|
||||
require(pending.empty());
|
||||
require(session.changing_world());
|
||||
require(session.world() == old->world);
|
||||
gate->release();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
|
||||
require(!has(events, ViewerEventKind::Command));
|
||||
require(session.runtime().latest()->identity.session != old->identity.session);
|
||||
require(session.world()->work_priority() == WorkPriority::Balanced);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_title_load_and_later_failed_load_supersede_old_preparation() {
|
||||
TempFiles files;
|
||||
const auto original = make_first_colony(2);
|
||||
write(files.root / "old.settlement", bytes(*original));
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
|
||||
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
const auto before = session.runtime().latest();
|
||||
session.load(files.root / "old.settlement");
|
||||
gate->wait();
|
||||
session.load(files.root / "missing.settlement");
|
||||
require(session.poll().empty());
|
||||
gate->release();
|
||||
const auto failed = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(!has(failed, ViewerEventKind::Replaced));
|
||||
require(session.runtime().latest()->identity == before->identity);
|
||||
require(!session.changing_world());
|
||||
session.load(files.root / "old.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(session.runtime().latest()->identity.world != before->identity.world);
|
||||
require(session.world()->tick() == 0);
|
||||
require(bytes(*session.world()) == bytes(*original));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_unsupported_profile_and_dimensions_keep_current_world() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
const auto initial = session.runtime().latest();
|
||||
auto catalog = builtin_rule_packages();
|
||||
require(catalog.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
const auto rules = resolve_rules(*catalog, selected);
|
||||
require(rules.has_value());
|
||||
const auto custom = encode_checkpoint(*initial->world, initial->identity.world, 1, *rules);
|
||||
require(custom.has_value());
|
||||
write(files.root / "custom.settlement", *custom);
|
||||
session.load(files.root / "custom.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
|
||||
World small(1, 16, 16);
|
||||
write(files.root / "small.settlement", bytes(small));
|
||||
session.load(files.root / "small.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
|
||||
write(files.root / "broken.settlement", "STHCHKPTmalformed");
|
||||
session.load(files.root / "broken.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Error); });
|
||||
require(session.runtime().latest() == initial);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_save_keeps_captured_session_across_reset() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
const auto before = session.runtime().latest();
|
||||
session.save(files.root / "captured.settlement");
|
||||
session.new_colony();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Replaced); });
|
||||
require(!has(events, ViewerEventKind::Saved));
|
||||
require(session.runtime().latest()->identity.world != before->identity.world);
|
||||
CheckpointFiles reader;
|
||||
CheckpointLoadResult loaded = std::unexpected{CheckpointFileDiagnostic{CheckpointFileError::Io, "waiting"}};
|
||||
const auto limit = std::chrono::steady_clock::now() + 5s;
|
||||
while (!loaded) {
|
||||
auto operation = reader.try_load(files.root / "captured.settlement");
|
||||
require(operation.admission == CheckpointLoadAdmission::Accepted);
|
||||
require(operation.completion.wait_for(5s) == std::future_status::ready);
|
||||
loaded = operation.completion.get();
|
||||
require(std::chrono::steady_clock::now() < limit);
|
||||
}
|
||||
require(loaded->world_id == before->identity.world);
|
||||
require(bytes(*loaded->world) == bytes(*before->world));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_guest_view_is_read_only_and_leave_installs_received_world() {
|
||||
ViewerSession session(2);
|
||||
auto* owner = &session.runtime();
|
||||
const auto before = session.runtime().latest();
|
||||
session.enter_guest();
|
||||
require(!session.world());
|
||||
require(!session.submit(CommandPayload{CommandKind::SetPaused, {}, 1}));
|
||||
auto incoming = make_first_colony(2);
|
||||
const auto receipt = incoming->apply_command({1, 1, CommandKind::SetPriority, {}, 2});
|
||||
require(receipt.status == CommandStatus::Accepted);
|
||||
const auto expected = bytes(*incoming);
|
||||
session.receive_guest(std::move(incoming));
|
||||
const auto held = session.world();
|
||||
require(bytes(*held) == expected);
|
||||
session.leave_guest();
|
||||
require(session.world() == held);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(&session.runtime() == owner);
|
||||
require(session.runtime().latest()->identity.session != before->identity.session);
|
||||
require(bytes(*session.world()) == expected);
|
||||
require(bytes(*held) == expected);
|
||||
require(!session.guest());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_runtime_busy_keeps_the_same_intent_until_commit() {
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.capacity = 1;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [gate, &block](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
gate->wait();
|
||||
auto occupying = session.runtime().synchronize();
|
||||
require(occupying.admission == RuntimeAdmission::Accepted);
|
||||
require(session.runtime().synchronize().admission == RuntimeAdmission::Busy);
|
||||
const auto command = session.submit(CommandPayload{CommandKind::SetPriority, {}, 1});
|
||||
require(command.has_value());
|
||||
require(session.poll().empty());
|
||||
require(session.pending(*command));
|
||||
require(session.world()->work_priority() == WorkPriority::Balanced);
|
||||
gate->release();
|
||||
const auto result = pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Command); });
|
||||
require(result.front().command == *command && result.front().status == CommandStatus::Accepted);
|
||||
require(session.world()->next_command_sequence(colony_host) == 2);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_initial_candidate_requires_supported_rules_and_dimensions() {
|
||||
const auto id = Void::Uuid::try_v4();
|
||||
require(id.has_value());
|
||||
const auto catalog = builtin_rule_packages();
|
||||
require(catalog.has_value());
|
||||
const std::array selected{std::string{"settlement.core"}};
|
||||
const auto custom = resolve_rules(*catalog, selected);
|
||||
require(custom.has_value());
|
||||
bool rejected = false;
|
||||
try { ViewerSession session({make_first_colony(2), *id, 1, *custom}, 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
const auto defaults = default_rules_manifest();
|
||||
require(defaults.has_value());
|
||||
rejected = false;
|
||||
try { ViewerSession session({std::make_unique<World>(1, 16, 16), *id, 1, *defaults}, 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
|
||||
TempFiles files;
|
||||
const auto clock = std::make_shared<Void::Time::ManualClock>();
|
||||
std::atomic<bool> fail{true};
|
||||
ViewerSessionOptions options;
|
||||
options.runtime.clock = clock;
|
||||
options.runtime.observer = [&fail](RuntimePhase phase) {
|
||||
if (phase == RuntimePhase::BeforeTick && fail.exchange(false)) throw std::runtime_error("injected tick fault");
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
const auto before = session.world();
|
||||
write(files.root / "recover.settlement", bytes(*before));
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Fault); });
|
||||
require(session.world() == before);
|
||||
require(!session.can_submit());
|
||||
require(!has(session.poll(), ViewerEventKind::Fault));
|
||||
bool rejected_save = false;
|
||||
try { session.save(files.root / "fault.settlement"); }
|
||||
catch (const std::runtime_error&) { rejected_save = true; }
|
||||
require(rejected_save);
|
||||
session.set_ticking(false);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session, RuntimeOutcome::Faulted);
|
||||
static_cast<void>(session.poll());
|
||||
session.load(files.root / "recover.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(session.can_submit());
|
||||
require(bytes(*session.world()) == bytes(*before));
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
flush_owner(session);
|
||||
require(session.world()->tick() == before->tick());
|
||||
session.set_ticking(true);
|
||||
static_cast<void>(session.poll());
|
||||
flush_owner(session);
|
||||
require(clock->advance(50ms).has_value());
|
||||
session.runtime().notify_clock();
|
||||
pump_until(session, [&](const auto&) { return session.world()->tick() > before->tick(); });
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_failed_guest_transitions_retain_received_replica() {
|
||||
ViewerSession session(2);
|
||||
session.enter_guest();
|
||||
session.receive_guest(make_first_colony(2));
|
||||
const auto received = session.world();
|
||||
session.runtime().shutdown();
|
||||
bool rejected_join = false;
|
||||
try { session.enter_guest(); }
|
||||
catch (const std::runtime_error&) { rejected_join = true; }
|
||||
require(rejected_join && session.guest() && session.world() == received);
|
||||
bool rejected_leave = false;
|
||||
try { session.leave_guest(); }
|
||||
catch (const std::runtime_error&) { rejected_leave = true; }
|
||||
require(rejected_leave && session.guest() && session.world() == received);
|
||||
}
|
||||
|
||||
template<class T, class E>
|
||||
T checked(std::expected<T, E> result) {
|
||||
if (!result) throw std::runtime_error(result.error().message);
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
std::string checkpoint_bytes(const WorldCheckpoint& candidate) {
|
||||
return checked(encode_checkpoint(*candidate.world, candidate.world_id, candidate.city, candidate.rules));
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_profiles_new_save_load_and_legacy_host_admission() {
|
||||
TempFiles files;
|
||||
ViewerSession session(2);
|
||||
for (const auto profile : {ColonyProfile::PlankBeds, ColonyProfile::Default}) {
|
||||
const auto before = session.runtime().latest();
|
||||
session.new_colony(profile);
|
||||
require(session.changing_world() && !session.can_host_legacy());
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
const auto created = session.runtime().latest();
|
||||
const auto expected = checked(colony_rules(profile));
|
||||
require(created->identity.world != before->identity.world && created->identity.session != before->identity.session);
|
||||
require(*created->rules == expected.manifest());
|
||||
require(created->world->staged_beds() == (profile == ColonyProfile::Default));
|
||||
require(session.can_host_legacy() == (profile == ColonyProfile::Default));
|
||||
const auto path = files.root / "profile.settlement";
|
||||
session.save(path);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
|
||||
CheckpointFiles reader;
|
||||
auto read = reader.try_load(path, 2);
|
||||
require(read.admission == CheckpointLoadAdmission::Accepted);
|
||||
require(read.completion.wait_for(5s) == std::future_status::ready);
|
||||
const auto saved = checked(read.completion.get());
|
||||
require(saved.rules == expected.manifest() && saved.world_id == created->identity.world);
|
||||
require(bytes(*saved.world) == bytes(*created->world));
|
||||
session.new_colony(profile == ColonyProfile::Default ? ColonyProfile::PlankBeds : ColonyProfile::Default);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
session.load(path);
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(*session.runtime().latest()->rules == saved.rules);
|
||||
require(session.runtime().latest()->identity.world == saved.world_id);
|
||||
require(bytes(*session.world()) == bytes(*saved.world));
|
||||
}
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_profile_validation_rejects_initial_and_loaded_mismatches() {
|
||||
TempFiles files;
|
||||
auto catalog = checked(builtin_rule_packages());
|
||||
const auto optional_rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
|
||||
const auto core_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.core"}}));
|
||||
catalog.push_back(checked(load_rule_package("extra",
|
||||
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})")));
|
||||
const auto extra_rules = checked(resolve_rules(catalog,
|
||||
std::array{std::string{"settlement.colony"}, std::string{"game.extra"}}));
|
||||
auto altered = std::string(catalog[1].canonical_json());
|
||||
const auto recipe = altered.find("\"output_count\":1");
|
||||
require(recipe != std::string::npos);
|
||||
altered.replace(recipe, std::string_view{"\"output_count\":1"}.size(), "\"output_count\":2");
|
||||
catalog[1] = checked(load_rule_package("forged", altered));
|
||||
const auto forged_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.colony"}}));
|
||||
ViewerSession session(2);
|
||||
const auto before = session.runtime().latest();
|
||||
for (const auto& rules : {core_rules, extra_rules, forged_rules, optional_rules}) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
candidate.rules = rules;
|
||||
write(files.root / "invalid.settlement", checkpoint_bytes(candidate));
|
||||
bool rejected = false;
|
||||
try { ViewerSession invalid(std::move(candidate), 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
session.load(files.root / "invalid.settlement");
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
|
||||
require(!has(events, ViewerEventKind::Replaced));
|
||||
require(session.runtime().latest() == before && !session.changing_world());
|
||||
}
|
||||
for (int problem = 0; problem < 3; ++problem) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
if (problem == 0) candidate.world.reset();
|
||||
if (problem == 1) candidate.world_id = {};
|
||||
if (problem == 2) candidate.city = 0;
|
||||
bool rejected = false;
|
||||
try { ViewerSession invalid(std::move(candidate), 2); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected);
|
||||
}
|
||||
bool rejected = false;
|
||||
try { session.new_colony(static_cast<ColonyProfile>(255)); }
|
||||
catch (const std::runtime_error&) { rejected = true; }
|
||||
require(rejected && session.runtime().latest() == before && session.can_host_legacy());
|
||||
auto supported = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
|
||||
ViewerSession optional(std::move(supported), 2);
|
||||
require(!optional.world()->staged_beds() && !optional.can_host_legacy());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_pending_optional_load_blocks_host_and_newest_invalid_load_wins() {
|
||||
TempFiles files;
|
||||
auto valid = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
|
||||
write(files.root / "optional.settlement", checkpoint_bytes(valid));
|
||||
valid.world = make_first_colony(2);
|
||||
write(files.root / "invalid.settlement", checkpoint_bytes(valid));
|
||||
auto gate = std::make_shared<Gate>();
|
||||
std::atomic<bool> block{true};
|
||||
ViewerSessionOptions options;
|
||||
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
|
||||
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
|
||||
};
|
||||
ViewerSession session(2, std::move(options));
|
||||
auto release = Void::Scope::on_exit([&] { gate->release(); });
|
||||
const auto before = session.runtime().latest();
|
||||
require(session.can_host_legacy());
|
||||
session.load(files.root / "optional.settlement");
|
||||
gate->wait();
|
||||
require(session.changing_world() && !session.can_host_legacy() && session.runtime().latest() == before);
|
||||
// Invalid direct New preparation must retain the pending load and its ticket.
|
||||
const auto generation = session.generation();
|
||||
try { session.new_colony(static_cast<ColonyProfile>(255)); }
|
||||
catch (const std::runtime_error&) {}
|
||||
require(session.changing_world() && session.generation() == generation);
|
||||
session.load(files.root / "invalid.settlement");
|
||||
gate->release();
|
||||
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
|
||||
require(!has(events, ViewerEventKind::Replaced) && session.runtime().latest() == before);
|
||||
flush_owner(session);
|
||||
require(session.poll().empty() && session.runtime().latest() == before && session.can_host_legacy());
|
||||
}
|
||||
|
||||
Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_default_rules() {
|
||||
TempFiles files;
|
||||
const auto defaults = checked(default_rules_manifest());
|
||||
for (int mode = 0; mode < 3; ++mode) {
|
||||
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
|
||||
if (mode == 1) candidate.world = make_first_colony(2, BedConstructionMode::Plank);
|
||||
if (mode == 2) candidate.world = std::make_unique<World>(17, 32, 32, 2);
|
||||
const auto expected = bytes(*candidate.world);
|
||||
ViewerSession session(std::move(candidate), 2);
|
||||
require(bytes(*session.world()) == expected && session.can_host_legacy());
|
||||
write(files.root / "legacy.settlement", expected);
|
||||
session.load(files.root / "legacy.settlement");
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(bytes(*session.world()) == expected && *session.runtime().latest()->rules == defaults);
|
||||
}
|
||||
ViewerSession session(checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2)), 2);
|
||||
session.enter_guest();
|
||||
session.receive_guest(make_first_colony(2, BedConstructionMode::Plank));
|
||||
session.leave_guest();
|
||||
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
|
||||
require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
Reference in new issue
Block a user