Drive the Win32 client from committed simulation snapshots and receipts

This commit is contained in:
faumaray committed 2026-12-02 22:36:08 +03:00
1 parent eef69caa0e
commit b7f18c094b
7 files changed
+1244 -188

No files matched your search

+10 -1
View File
@@ -88,16 +88,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
@@ -130,4 +135,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()
+324
View File
@@ -0,0 +1,324 @@
#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 RulesManifest& rules) {
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.");
}
if (candidate.rules != rules) {
throw std::runtime_error("This viewer requires the installed default colony rules.");
}
}
WorldCheckpoint validated_initial(WorldCheckpoint candidate, const RulesManifest& rules) {
validate_supported(candidate, rules);
return candidate;
}
WorldCheckpoint initial_colony(std::size_t workers) {
auto identity = Void::Uuid::try_v4();
if (!identity) throw std::runtime_error("Could not create a world identity.");
return {make_first_colony(workers), *identity, 1, supported_rules()};
}
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), supported_rules_), 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;
}
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, supported_rules_);
}
void ViewerSession::replace(WorldCheckpoint candidate) {
validate_candidate(candidate);
const auto ticket = begin_change();
installing_.emplace(Installing{ticket, std::move(candidate)});
}
void ViewerSession::new_colony() {
replace(initial_colony(workers_));
}
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
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include "settlement/core/checkpoint_files.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]] 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();
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
+348 -185
View File
@@ -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 };
@@ -244,6 +248,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 +289,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 +824,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 +1000,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 +1016,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 +1054,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();
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 +1087,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 +1211,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 +1253,65 @@ 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);
if (command == lan_host_id && lan->state() == LanState::Offline) {
if (!has_session || !world || !world->scenario_active()) {
session->new_colony();
host_after_replacement = true;
clear_blueprints();
camera = {};
selected_resident.reset();
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 +1328,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 +1364,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 +1484,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 +1569,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 +1593,184 @@ 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)) {
lan->host();
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 +1803,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 +1820,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 +1843,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 +1964,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) {
@@ -2079,6 +2254,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) {
@@ -2099,6 +2276,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 {
@@ -2249,17 +2434,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:
@@ -2283,12 +2469,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"Создать сетевую колонию…"});
@@ -2316,10 +2503,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);
@@ -2327,6 +2513,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);
@@ -2448,11 +2636,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);
@@ -2470,12 +2658,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};
@@ -2550,7 +2738,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);
@@ -2729,49 +2917,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;
@@ -2810,7 +2957,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;
@@ -2818,11 +2965,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{};
@@ -2853,5 +3015,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
session.reset();
return static_cast<int>(message.wParam);
}
+48
View File
@@ -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.
+10 -2
View File
@@ -1,6 +1,6 @@
# S18. Интерфейс, управление и обратная связь
Статус — план реализации. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — первый срез S18-W01 реализован: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
@@ -16,6 +16,14 @@
## Последовательность реализации
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное и загружаемое состояние проверяются на карту 32×32 и точное совпадение поддержанного стандартного состава правил. Настоящие альтернативные правила относятся к [S19](S19.md).
Локальная очередь ограничена 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, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
@@ -42,7 +50,7 @@
## VoidLibrary
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
## Приёмка
+395
View File
@@ -0,0 +1,395 @@
#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) {
for (;;) {
auto sync = session.runtime().synchronize();
if (sync.admission == RuntimeAdmission::Busy) {
std::this_thread::yield();
continue;
}
require(sync.admission == RuntimeAdmission::Accepted);
require(sync.completion.wait_for(5s) == std::future_status::ready);
require(sync.completion.get().outcome == RuntimeOutcome::Completed);
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();
};
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());
auto suspended = session.runtime().synchronize();
require(suspended.admission == RuntimeAdmission::Accepted);
require(suspended.completion.wait_for(5s) == std::future_status::ready);
require(suspended.completion.get().outcome == 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);
}
} // namespace