Integrate the snapshot-driven Win32 client into M01

This commit is contained in:
faumaray committed 2026-12-02 22:36:12 +03:00
commit db0a8720a6
7 files changed
+1244 -188

No files matched your search

+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) {
@@ -2078,6 +2253,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 +2275,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 +2433,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 +2468,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 +2502,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 +2512,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 +2635,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 +2657,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 +2737,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 +2916,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 +2956,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 +2964,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 +3014,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
session.reset();
return static_cast<int>(message.wParam);
}