From 85547b00b9a03fdc7831d9c0b2669564e8441d77 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 20:21:04 +0300 Subject: [PATCH] Add a live interface scale slider and room blueprints --- PLAN.md | 3 +- app/d3d_scene_win32.cpp | 48 ++- app/d3d_scene_win32.hpp | 2 + app/lan_session.hpp | 1 + app/lan_session_win32.cpp | 4 +- app/viewer_win32.cpp | 372 ++++++++++++++++++----- docs/viewer.md | 4 +- engine/include/settlement/core/world.hpp | 23 +- engine/src/world.cpp | 110 ++++++- engine/src/world_save.cpp | 13 +- tests/core_tests.cpp | 43 +++ tests/lan_tests.cpp | 26 ++ 12 files changed, 553 insertions(+), 96 deletions(-) diff --git a/PLAN.md b/PLAN.md index a3599a4..861d0cd 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,8 @@ - [ ] Расширение набора 3D-моделей и освещения. - [x] Постановка чертежа домика мышью в Windows-клиенте. - [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением. -- [ ] Чертежи комнат с полом, стенами и проёмами. +- [x] Прямоугольные чертежи комнат с полом, стенами, выбором стороны входа и поэтапной стройкой. +- [ ] Маршруты через дверные проёмы и настройка формы комнаты. - [ ] Интерфейс для остальных типов работ и зданий. ### P5 — Игровые системы и совместная игра diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index 7b72f5e..fadeacc 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -116,6 +116,43 @@ void resources(Mesh& mesh, const World& world) { } } +void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool draft) { + const float x = static_cast(cell.x), y = static_cast(cell.y); + if (recipe == RecipeId::BuildFloor) { + mesh.flat(x - .495f, y - .495f, x + .495f, y + .495f, .013f, shade(color, .76f)); + for (int i = 0; i < 4; ++i) { + const auto strip = static_cast(i) * .24f; + mesh.flat(x - .49f, y - .48f + strip, x + .49f, y - .25f + strip, .015f, + shade(color, i % 2 ? 1.f : .93f)); + } + } else if (recipe == RecipeId::BuildWall) { + if (draft) { + mesh.box(x, y, .03f, .92f, .92f, .09f, shade(color, .69f)); + mesh.box(x, y, .12f, .91f, .91f, .16f, color); + } else { + mesh.box(x, y, .02f, 1.f, 1.f, .73f, color); + mesh.box(x, y, .75f, 1.f, 1.f, .10f, shade(color, 1.13f)); + } + } else { + const bool along_x = recipe == RecipeId::BuildDoorAlongX; + for (const float side : {-1.f, 1.f}) { + mesh.box(x + (along_x ? side * .40f : 0.f), y + (along_x ? 0.f : side * .40f), + .02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color); + } + mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f)); + } +} + +void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + room_part(mesh, cell, plan.recipe_at(cell), !valid ? rgb(203, 113, 101) : + (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)), true); + } + } +} + void construction(Mesh& mesh, const World& world) { for (const auto& storage : world.storages()) { const float x = static_cast(storage.position.x), y = static_cast(storage.position.y); @@ -139,7 +176,14 @@ void construction(Mesh& mesh, const World& world) { const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked); } - if (order.recipe == RecipeId::BuildBed && + if (order.recipe >= RecipeId::BuildFloor) { + if (order.state == JobState::Completed) { + room_part(mesh, order.position, order.recipe, rgb(175, 123, 78), false); + } else if (order.recipe != RecipeId::BuildFloor) { + room_part(mesh, order.position, order.recipe, + order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true); + } + } else if (order.recipe == RecipeId::BuildBed && (order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) { mesh.box(x, y, .045f, .77f, .43f, .18f, order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66)); @@ -403,6 +447,8 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector selected; std::span blueprint; std::optional preview; + std::span room_blueprints; + std::optional room_preview; }; class D3DScene { diff --git a/app/lan_session.hpp b/app/lan_session.hpp index 2beb091..74def74 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -17,6 +17,7 @@ struct LanRejection { CommandKind kind; GridPosition cell; std::uint8_t value; + GridPosition destination; }; class LanSession { diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 3eabfdf..49b1b3d 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -24,7 +24,7 @@ namespace { using Clock = std::chrono::steady_clock; using namespace std::chrono_literals; -constexpr std::uint32_t protocol_version = 7; +constexpr std::uint32_t protocol_version = 8; constexpr std::size_t frame_limit = 4 * 1024 * 1024; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; @@ -306,7 +306,7 @@ struct LanSession::Impl { if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); if (status != CommandStatus::Accepted) { rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, - awaiting_receipt->value}; + awaiting_receipt->value, awaiting_receipt->destination}; } guest_sequence = number(payload.substr(1)); awaiting_receipt.reset(); diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index eb451a6..340a63b 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -64,6 +64,7 @@ constexpr int flax_field_id = 1038; constexpr int loom_id = 1039; constexpr int farmer_menu_id = 1040; constexpr int builder_menu_id = 1043; +constexpr int room_tool_id = 1044; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; @@ -73,8 +74,10 @@ constexpr int build_blueprint_id = 1084; constexpr int clear_blueprint_id = 1085; constexpr int exit_menu_id = 1121; constexpr int interface_scale_id = 1122; -constexpr int first_scale_id = 1130; -constexpr std::array interface_scales{100, 125, 150}; +constexpr int scale_slider_id = 1130; +constexpr int scale_value_id = 1131; +constexpr int min_interface_scale = 50; +constexpr int max_interface_scale = 250; constexpr int default_interface_scale = 125; constexpr int timer_id = 1; constexpr int map_size = settlement::first_colony_map_size; @@ -100,6 +103,7 @@ struct DockLayout { int height = 0; int hint_top = 0; int line_height = 0; + int scale = default_interface_scale; }; DockLayout dock_layout; std::array dock_section_buttons{}; @@ -118,7 +122,7 @@ settlement::viewer::LanSession lan; LanState displayed_lan_state = LanState::Offline; const auto local_worker_count = std::clamp( std::thread::hardware_concurrency(), settlement::min_worker_count, 8); -enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish }; +enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; WorkPanel work_panel = WorkPanel::None; @@ -148,13 +152,14 @@ constexpr std::array builder_choices = { WorkChoice{pantry_id, L"Кладовая", WorkIcon::Pantry, 103, PlacementMode::Pantry}, WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, + WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room}, }; std::array work_choice_buttons{}; constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0], builder_choices[2], builder_choices[3]}; constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], - builder_choices[4], builder_choices[5]}; + builder_choices[6], builder_choices[4], builder_choices[5]}; struct DockSection { WorkPanel panel; const wchar_t* title; @@ -196,6 +201,8 @@ struct ResidentRoster { ResidentRoster roster; std::optional selected_bed_base; std::vector blueprint; +std::vector room_blueprints; +std::optional room_anchor; std::optional move_source; settlement::viewer::MapCamera camera; struct CameraDrag { @@ -210,7 +217,7 @@ std::optional selected_resident; std::wstring placement_message; int dock_pixels(int pixels) { - return MulDiv(pixels, interface_scale, 100); + return MulDiv(pixels, dock_layout.scale, 100); } COLORREF color(int red, int green, int blue) { @@ -351,11 +358,16 @@ bool shows_bed_choices() { } bool is_blueprint_tool() { - return placement_mode == PlacementMode::Building || placement_mode == PlacementMode::Loom; + return placement_mode == PlacementMode::Building || placement_mode == PlacementMode::Loom || + placement_mode == PlacementMode::Room; +} + +bool has_blueprint() { + return !blueprint.empty() || !room_blueprints.empty(); } bool shows_blueprint_actions() { - return !showing_title && (is_blueprint_tool() || !blueprint.empty()); + return !showing_title && (is_blueprint_tool() || has_blueprint()); } bool is_map_point(const RECT& client, POINT point) { @@ -468,16 +480,11 @@ std::span work_choices() { return {}; } -void layout_command_dock(HWND window) { - RECT client{}; - GetClientRect(window, &client); - const auto width = static_cast(client.right); - const auto height = static_cast(client.bottom); - SetWindowPos(status_label, nullptr, 16, 14, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); - SetWindowPos(production_label, nullptr, 16, 44, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); - const bool compact = height < map_top + dock_pixels(390); - const int margin = dock_pixels(compact ? 8 : 12); - const int gap = dock_pixels(compact ? 5 : 7); +DockLayout measure_command_dock(int width, int height, int scale, bool position_controls) { + const auto pixels = [scale](int amount) { return MulDiv(amount, scale, 100); }; + const bool compact = height < 760; + const int margin = pixels(compact ? 8 : 12); + const int gap = pixels(compact ? 5 : 7); const int available = std::max(1, width - margin * 2); int bottom = height - margin; struct DockItem { @@ -485,8 +492,8 @@ void layout_command_dock(HWND window) { int width; bool materials = false; }; - const auto place = [](HWND button, int x, int y, int w, int h) { - SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); + const auto place = [&](HWND button, int x, int y, int w, int h) { + if (position_controls) SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); }; const auto layout_rows = [&](std::span items, int button_height) { // Pack from the end so rows near the bottom stay fixed as the window grows. @@ -496,17 +503,17 @@ void layout_command_dock(HWND window) { auto start = items.size(); do { const auto& item = items[start - 1]; - const int required = std::min(available, dock_pixels(item.width)) + (row_width ? gap : 0); + const int required = std::min(available, pixels(item.width)) + (row_width ? gap : 0); if (row_width + required > available) break; row_width += required; materials |= item.materials; --start; } while (start != 0); - const int material_height = materials ? dock_pixels(compact ? 28 : 34) + gap : 0; + const int material_height = materials ? pixels(compact ? 28 : 34) + gap : 0; int x = std::max(margin, (width - row_width) / 2); const int y = bottom - material_height - button_height; for (const auto& item : items.subspan(start)) { - const int w = std::min(available, dock_pixels(item.width)); + const int w = std::min(available, pixels(item.width)); place(item.control, x, y, w, button_height); if (item.materials) { const int half = (w - gap) / 2; @@ -524,7 +531,7 @@ void layout_command_dock(HWND window) { {residents_button, 101}, {dock_section_buttons[0], 104}, {dock_section_buttons[1], 104}, {dock_section_buttons[2], 163}, {work_list_button, 101}, {priority_button, 172}, }; - layout_rows(sections, dock_pixels(compact ? 34 : 40)); + layout_rows(sections, pixels(compact ? 34 : 40)); const auto choices = work_choices(); std::array tools{}; for (std::size_t index = 0; index < choices.size(); ++index) { @@ -532,32 +539,20 @@ void layout_command_dock(HWND window) { const bool bed = choice.command == cabin_button_id; tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; } - const int tool_height = dock_pixels(compact ? 30 : 36); + const int tool_height = pixels(compact ? 30 : 36); if (choices.empty()) bottom -= tool_height + gap; else layout_rows(std::span(tools).first(choices.size()), tool_height); if (shows_blueprint_actions()) { const DockItem actions[] = {{build_blueprint_button, 182}, {clear_blueprint_button, 188}}; - layout_rows(actions, dock_pixels(compact ? 31 : 37)); + layout_rows(actions, pixels(compact ? 31 : 37)); } - const int line_height = dock_pixels(compact ? 20 : 23); + const int line_height = pixels(compact ? 20 : 23); const int hint_top = bottom - 2 * line_height; - const int new_height = height - hint_top + dock_pixels(8); - if (new_height != dock_layout.height && !showing_title) { - RECT dirty{0, height - std::max(new_height, dock_layout.height), width, height}; - InvalidateRect(window, &dirty, FALSE); - } - dock_layout = {new_height, hint_top, line_height}; - layout_scene(window); + return {height - hint_top + pixels(8), hint_top, line_height, scale}; } -std::filesystem::path interface_settings_file() { - const auto saves = title::saves_directory(); - return saves.empty() ? std::filesystem::path{} : saves.parent_path() / L"settings.ini"; -} - -void apply_interface_scale(HWND window, int scale) { - interface_scale = scale; +void update_dock_font() { const auto font = CreateFontW(-dock_pixels(15), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI"); const auto face = reinterpret_cast(font ? font : GetStockObject(DEFAULT_GUI_FONT)); @@ -568,6 +563,40 @@ void apply_interface_scale(HWND window, int scale) { for (const auto button : work_choice_buttons) set_font(button); if (dock_font) DeleteObject(dock_font); dock_font = font; +} + +void layout_command_dock(HWND window) { + RECT client{}; + GetClientRect(window, &client); + const int width = client.right, height = client.bottom; + SetWindowPos(status_label, nullptr, 16, 14, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + SetWindowPos(production_label, nullptr, 16, 44, std::max(0, width - 32), 24, SWP_NOZORDER | SWP_NOACTIVATE); + const int budget = std::max(0, height - map_top - 170); + int low = min_interface_scale, high = interface_scale; + while (low < high) { + const int scale = (low + high + 1) / 2; + if (measure_command_dock(width, height, scale, false).height <= budget) low = scale; + else high = scale - 1; + } + const auto next = measure_command_dock(width, height, low, true); + const auto new_height = next.height; + if (new_height != dock_layout.height && !showing_title) { + RECT dirty{0, height - std::max(new_height, dock_layout.height), width, height}; + InvalidateRect(window, &dirty, FALSE); + } + const bool font_changed = !dock_font || next.scale != dock_layout.scale; + dock_layout = next; + if (font_changed) update_dock_font(); + layout_scene(window); +} + +std::filesystem::path interface_settings_file() { + const auto saves = title::saves_directory(); + return saves.empty() ? std::filesystem::path{} : saves.parent_path() / L"settings.ini"; +} + +void apply_interface_scale(HWND window, int scale) { + interface_scale = std::clamp(scale, min_interface_scale, max_interface_scale); layout_command_dock(window); InvalidateRect(window, nullptr, FALSE); } @@ -586,8 +615,7 @@ int read_interface_scale() { const auto file = interface_settings_file(); if (file.empty()) return default_interface_scale; const auto scale = static_cast(GetPrivateProfileIntW(L"Interface", L"Scale", default_interface_scale, file.c_str())); - return std::find(interface_scales.begin(), interface_scales.end(), scale) != interface_scales.end() - ? scale : default_interface_scale; + return scale >= min_interface_scale && scale <= max_interface_scale ? scale : default_interface_scale; } void invalidate_work_choices() { @@ -678,7 +706,7 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { case residents_button_id: return draw(WorkIcon::Resident, roster.window != nullptr); case work_list_button_id: return draw(WorkIcon::Hammer); case priority_button_id: return draw(WorkIcon::Priority); - case build_blueprint_id: return draw(WorkIcon::Hammer, !blueprint.empty()); + case build_blueprint_id: return draw(WorkIcon::Hammer, has_blueprint()); case clear_blueprint_id: return draw(WorkIcon::Demolish); } if (id >= first_dock_section_id && static_cast(id - first_dock_section_id) < dock_sections.size()) { @@ -790,7 +818,7 @@ void update_status() { for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(work_list_button, can_play); - EnableWindow(build_blueprint_button, !blueprint.empty() && can_play); + EnableWindow(build_blueprint_button, has_blueprint() && can_play); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; @@ -843,8 +871,8 @@ void update_blueprint_controls(HWND window) { const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE; ShowWindow(build_blueprint_button, visibility); ShowWindow(clear_blueprint_button, visibility); - EnableWindow(build_blueprint_button, !blueprint.empty() && can_give_orders()); - EnableWindow(clear_blueprint_button, !blueprint.empty()); + EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders()); + EnableWindow(clear_blueprint_button, has_blueprint()); layout_command_dock(window); } @@ -852,6 +880,7 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message placement_mode = mode; selected_bed_base.reset(); move_source.reset(); + room_anchor.reset(); hover_cell.reset(); placement_message = message; update_bed_choices(); @@ -860,6 +889,12 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message invalidate_scene(window); } +void clear_blueprints() { + blueprint.clear(); + room_blueprints.clear(); + room_anchor.reset(); +} + void toggle_work_panel(HWND window, WorkPanel panel) { if (!can_give_orders()) return; set_placement_mode(window, PlacementMode::None); @@ -906,7 +941,7 @@ void show_title_screen(HWND window, bool visible) { void reset_world(HWND window) { world = settlement::make_first_colony(local_worker_count); - blueprint.clear(); + clear_blueprints(); camera = {}; selected_resident.reset(); sync_resident_roster(true); @@ -987,7 +1022,7 @@ void handle_save_menu(HWND window, bool saving, std::optionaladdress.data()), narrow_lan_input(request->code.data())); - blueprint.clear(); + clear_blueprints(); enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); @@ -1264,11 +1299,77 @@ bool valid_edit_cell(settlement::GridPosition cell) { case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted; case PlacementMode::Building: return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell); + case PlacementMode::Room: case PlacementMode::None: return false; } return false; } +auto room_at(settlement::GridPosition cell) { + return std::find_if(room_blueprints.begin(), room_blueprints.end(), + [cell](const auto& room) { return room.contains(cell); }); +} + +bool room_fits_blueprint(const settlement::RoomPlan& room) { + return std::none_of(blueprint.begin(), blueprint.end(), + [&](const auto& part) { return room.contains(part.cell); }) && + std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { + return room.first.x <= other.last.x && room.last.x >= other.first.x && + room.first.y <= other.last.y && room.last.y >= other.first.y; + }); +} + +settlement::RoomPlan preview_room(settlement::GridPosition cell) { + auto room = settlement::make_room_plan(*room_anchor, cell); + if (room.valid_size() && !world->can_place_room(room)) { + for (const auto side : {settlement::RoomSide::North, settlement::RoomSide::East, settlement::RoomSide::West}) { + room.entrance = side; + if (world->can_place_room(room)) return room; + } + room.entrance = settlement::RoomSide::South; + } + return room; +} + +void edit_room_blueprint(HWND window, settlement::GridPosition cell) { + if (!can_give_orders()) return; + using settlement::RoomSide; + if (room_anchor) { + const auto room = preview_room(cell); + if (!room.valid_size()) { + placement_message = L"Ширина и длина комнаты должны быть от 3 до 12 клеток."; + } else if (!world->can_place_room(room) || !room_fits_blueprint(room)) { + placement_message = L"Нужна свободная площадка и проход снаружи."; + } else { + room_blueprints.push_back(room); + room_anchor.reset(); + placement_message.clear(); + } + } else if (const auto room = room_at(cell); room != room_blueprints.end()) { + auto candidate = *room; + if (cell.y == room->first.y) candidate.entrance = RoomSide::North; + else if (cell.y == room->last.y) candidate.entrance = RoomSide::South; + else if (cell.x == room->first.x) candidate.entrance = RoomSide::West; + else if (cell.x == room->last.x) candidate.entrance = RoomSide::East; + else { + placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход."; + invalidate_scene(window); + return; + } + if (world->can_place_room(candidate)) { + *room = candidate; + placement_message.clear(); + } else { + placement_message = L"С этой стороны нет свободного прохода."; + } + } else { + room_anchor = cell; + placement_message.clear(); + } + update_blueprint_controls(window); + invalidate_scene(window); +} + std::optional preview_blueprint(settlement::GridPosition cell) { using settlement::RecipeId; if (placement_mode == PlacementMode::Loom) { @@ -1286,7 +1387,8 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { if (!can_give_orders()) 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); part && valid_edit_cell(cell)) { + } else if (const auto part = preview_blueprint(cell); + part && valid_edit_cell(cell) && room_at(cell) == room_blueprints.end()) { blueprint.push_back(*part); placement_message.clear(); } else { @@ -1299,10 +1401,14 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { } void submit_blueprint(HWND window) { - if (!world || blueprint.empty() || !can_give_orders()) return; + if (!world || !has_blueprint() || !can_give_orders()) return; using settlement::CommandKind; using settlement::RecipeId; - const auto sent = std::erase_if(blueprint, [](const auto& part) { + const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) { + return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first, + static_cast(room.entrance), room.last) == settlement::CommandStatus::Accepted; + }); + const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { switch (part.recipe) { case RecipeId::BuildBed: return world->can_place_bed(part.cell) && @@ -1320,10 +1426,10 @@ void submit_blueprint(HWND window) { return false; } }); - const std::wstring count = std::to_wstring(sent); - if (!blueprint.empty()) { + const std::wstring count = std::to_wstring(rooms_sent + objects_sent); + if (has_blueprint()) { placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + - std::to_wstring(blueprint.size()) + + std::to_wstring(blueprint.size() + room_blueprints.size()) + (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : L". Проверьте, свободны ли клетки и есть ли к ним проход."); } else { @@ -1660,7 +1766,15 @@ std::wstring blueprint_details() { totals[static_cast(material.type)] += material.count; } } - std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size()); + for (const auto& room : room_blueprints) { + for (int y = room.first.y; y <= room.last.y; ++y) { + for (int x = room.first.x; x <= room.last.x; ++x) { + const auto ingredients = world->construction_materials(room.recipe_at({x, y}), settlement::BedBase::Wood); + for (const auto& item : ingredients) totals[static_cast(item.type)] += item.count; + } + } + } + std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size()); for (const auto& material : materials) { const auto count = totals[static_cast(material.type)]; if (count != 0) text += std::wstring(L" ") + material.name + L" " + std::to_wstring(count); @@ -1714,6 +1828,9 @@ void draw_world(HDC dc, int width, int height) { L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; + } else if (placement_mode == PlacementMode::Room) { + hint = room_anchor ? L"Укажите противоположный угол комнаты." : + L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату."; } else if (is_blueprint_tool()) { hint = shows_bed_choices() && !selected_bed_base ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." @@ -1723,7 +1840,7 @@ void draw_world(HDC dc, int width, int height) { const int margin = dock_pixels(12); RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto details = blueprint.empty() ? resident_details() : blueprint_details(); + const auto details = has_blueprint() ? blueprint_details() : resident_details(); SetTextColor(dc, color(190, 201, 178)); RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); @@ -1734,14 +1851,21 @@ settlement::viewer::SceneView scene_view(int width, int height) { const auto pan = camera.offset(); const auto scale = camera.scale(); const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; - const bool valid_cursor = cursor && valid_edit_cell(*cursor); + std::optional room_preview; + if (cursor && room_anchor && placement_mode == PlacementMode::Room) { + const auto room = preview_room(*cursor); + if (room.valid_size()) room_preview = room; + } + const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview) + : cursor && (placement_mode == PlacementMode::Room ? !room_anchor : valid_edit_cell(*cursor)); const auto preview = valid_cursor && is_blueprint_tool() && + cursor && room_at(*cursor) == room_blueprints.end() && std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == *cursor; }) ? preview_blueprint(*cursor) : std::nullopt; return {width, height, static_cast(width / 2 * scale + pan.x), static_cast(map_origin_y * scale + pan.y - map_top), static_cast(scale), tile_width / 2.f, tile_height / 2.f, - cursor, valid_cursor, move_source, selected_resident, blueprint, preview}; + cursor, valid_cursor, move_source, selected_resident, blueprint, preview, room_blueprints, room_preview}; } LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { @@ -1842,24 +1966,73 @@ int choose_menu_action(HWND window, const wchar_t* title, std::span(action); } +INT_PTR CALLBACK scale_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_INITDIALOG: { + SetWindowTextW(dialog, L"Масштаб нижней панели"); + const auto add = [&](const wchar_t* kind, const wchar_t* text, int id, DWORD style, RECT rect) { + MapDialogRect(dialog, &rect); + const auto child = CreateWindowExW(0, kind, text, WS_VISIBLE | WS_CHILD | style, + rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, dialog, + reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); + SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), FALSE); + return child; + }; + add(L"STATIC", L"", scale_value_id, SS_CENTER, {8, 6, 235, 21}); + const auto slider = add(TRACKBAR_CLASSW, L"Масштаб панели", scale_slider_id, + TBS_AUTOTICKS | WS_TABSTOP, {10, 24, 233, 46}); + SendMessageW(slider, TBM_SETRANGE, TRUE, MAKELONG(min_interface_scale, max_interface_scale)); + SendMessageW(slider, TBM_SETTICFREQ, 25, 0); + SendMessageW(slider, TBM_SETPAGESIZE, 0, 10); + SendMessageW(slider, TBM_SETPOS, TRUE, interface_scale); + add(L"STATIC", L"50%", -1, 0, {12, 46, 45, 59}); + add(L"STATIC", L"250%", -1, SS_RIGHT, {195, 46, 232, 59}); + add(L"BUTTON", L"Применить", IDOK, BS_DEFPUSHBUTTON | WS_TABSTOP, {91, 63, 157, 83}); + add(L"BUTTON", L"Отмена", IDCANCEL, BS_PUSHBUTTON | WS_TABSTOP, {164, 63, 230, 83}); + SendMessageW(dialog, WM_HSCROLL, 0, reinterpret_cast(slider)); + SetFocus(slider); + return FALSE; + } + case WM_HSCROLL: + if (reinterpret_cast(lparam) == GetDlgItem(dialog, scale_slider_id)) { + const auto scale = static_cast(SendMessageW(reinterpret_cast(lparam), TBM_GETPOS, 0, 0)); + if (scale != interface_scale) apply_interface_scale(GetWindow(dialog, GW_OWNER), scale); + auto value = std::to_wstring(interface_scale) + L"%"; + if (dock_layout.scale != interface_scale) { + value += L" · в этом окне " + std::to_wstring(dock_layout.scale) + L"%"; + } + SetDlgItemTextW(dialog, scale_value_id, value.c_str()); + return TRUE; + } + break; + case WM_COMMAND: + if (LOWORD(wparam) == IDOK || LOWORD(wparam) == IDCANCEL) { + EndDialog(dialog, LOWORD(wparam)); + return TRUE; + } + break; + case WM_CLOSE: + EndDialog(dialog, IDCANCEL); + return TRUE; + } + return FALSE; +} + void choose_interface_scale(HWND window) { - std::array captions; - std::array actions{}; - for (std::size_t index = 0; index < interface_scales.size(); ++index) { - const auto scale = interface_scales[index]; - captions[index] = std::to_wstring(scale) + L"%"; - if (scale == interface_scale) captions[index] += L" · текущий"; - actions[index] = {first_scale_id + static_cast(index), captions[index].c_str()}; + struct alignas(DWORD) EmptyDialog { + DLGTEMPLATE header{}; + WORD menu = 0, window_class = 0, title = 0; + } layout; + layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; + layout.header.cx = 243; + layout.header.cy = 91; + const int previous = interface_scale; + if (DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, scale_dialog_proc, 0) != IDOK) { + if (interface_scale != previous) apply_interface_scale(window, previous); + } else if (interface_scale != previous && !save_interface_scale(interface_scale)) { + placement_message = L"Не удалось сохранить масштаб панели на диск."; + invalidate_scene(window); } - const int action = choose_menu_action(window, L"Масштаб нижней панели", actions); - if (action < first_scale_id || action >= first_scale_id + static_cast(interface_scales.size())) return; - const int scale = interface_scales[static_cast(action - first_scale_id)]; - if (scale == interface_scale) return; - const bool saved = save_interface_scale(scale); - const auto caption = std::to_wstring(scale) + L"%"; - placement_message = L"Масштаб нижней панели · " + caption + - (saved ? L"" : L". Настройку не удалось сохранить на диск."); - apply_interface_scale(window, scale); } void open_pause_menu(HWND window) { @@ -2035,8 +2208,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp SetFocus(window); return 0; } - if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && !blueprint.empty()) { - blueprint.clear(); + if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && has_blueprint()) { + clear_blueprints(); placement_message = L"Чертёж очищен."; update_blueprint_controls(window); SetFocus(window); @@ -2091,6 +2264,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp SetFocus(window); return 0; } + if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { + set_placement_mode(window, placement_mode == PlacementMode::Room ? PlacementMode::None : PlacementMode::Room); + SetFocus(window); + return 0; + } if (HIWORD(wparam) == BN_CLICKED && shows_bed_choices() && (LOWORD(wparam) == wood_bed_button_id || LOWORD(wparam) == stone_bed_button_id)) { selected_bed_base = LOWORD(wparam) == wood_bed_button_id ? settlement::BedBase::Wood : settlement::BedBase::Stone; @@ -2199,7 +2377,10 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp return 0; } if (world && is_blueprint_tool()) { - if (const auto cell = map_cell(client, point)) edit_blueprint(window, *cell); + if (const auto cell = map_cell(client, point)) { + if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell); + else edit_blueprint(window, *cell); + } return 0; } if (world && placement_mode >= PlacementMode::BerryField) { @@ -2216,6 +2397,26 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp break; } case WM_RBUTTONDOWN: + if (placement_mode == PlacementMode::Room) { + if (room_anchor) { + room_anchor.reset(); + placement_message.clear(); + invalidate_scene(window); + return 0; + } + RECT client{}; + GetClientRect(window, &client); + if (const auto cell = map_cell(client, client_point(lparam))) { + const auto room = room_at(*cell); + if (room != room_blueprints.end()) { + room_blueprints.erase(room); + placement_message = L"Комната убрана из чертежа."; + update_blueprint_controls(window); + invalidate_scene(window); + return 0; + } + } + } if (placement_mode != PlacementMode::None || work_panel != WorkPanel::None) { set_placement_mode(window, PlacementMode::None); set_work_panel(window, WorkPanel::None); @@ -2263,7 +2464,16 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp using settlement::CommandKind; using settlement::RecipeId; const bool bed = rejection->kind == CommandKind::PlaceBed; - if (bed || rejection->kind == CommandKind::PlaceLoom) { + if (rejection->kind == CommandKind::PlaceRoom) { + const settlement::RoomPlan room{rejection->cell, rejection->destination, + static_cast(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, @@ -2330,7 +2540,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } // namespace int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { - INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES}; + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls); WNDCLASSEXW window_class_info{}; window_class_info.cbSize = sizeof(window_class_info); diff --git a/docs/viewer.md b/docs/viewer.md index 158a142..fcbc993 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -20,6 +20,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. +В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. + Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. @@ -40,7 +42,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. -«Esc → Масштаб панели» меняет размер кнопок, значков и текста внизу. Доступны 100%, 125% и 150%. По умолчанию используется 125%, выбранный масштаб запоминается между запусками. +«Esc → Масштаб панели» открывает ползунок от 50% до 250% с предпросмотром. «Применить» сохраняет выбор между запусками, «Отмена» возвращает предыдущий масштаб. В маленьком окне панель подстраивается под доступное место, чтобы оставить видимой карту. По умолчанию используется 125%. В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index cc78cc1..6748972 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -74,21 +74,37 @@ enum class RecipeId : std::uint8_t { CutStoneBlock, BuildCabin, BuildBed, - WeaveCloth + WeaveCloth, + BuildFloor, + BuildWall, + BuildDoorAlongX, + BuildDoorAlongY }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; constexpr bool is_construction(RecipeId recipe) noexcept { - return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed; + return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || + (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY); } +enum class RoomSide : std::uint8_t { North, East, South, West }; +struct RoomPlan { + GridPosition first; + GridPosition last; + RoomSide entrance = RoomSide::South; + [[nodiscard]] bool valid_size() const noexcept; + [[nodiscard]] bool contains(GridPosition cell) const noexcept; + [[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept; +}; +[[nodiscard]] RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept; + enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; enum class CommandKind : std::uint8_t { PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, - PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12 + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -273,6 +289,7 @@ public: void enable_hunger() noexcept; void queue_production(GridPosition position, RecipeId recipe); [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; + [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); diff --git a/engine/src/world.cpp b/engine/src/world.cpp index beb1b8c..6458412 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -35,6 +35,10 @@ bool is_production_object(RecipeId recipe) noexcept { return is_construction(recipe) || recipe == RecipeId::WeaveCloth; } +bool is_finished_floor(const ProductionOrder& order) noexcept { + return order.recipe == RecipeId::BuildFloor && order.state == JobState::Completed; +} + bool can_take_work(const Agent& agent, Profession profession) noexcept { return agent.profession == Profession::Generalist || agent.profession == profession; } @@ -62,12 +66,19 @@ const Recipe& recipe_for(RecipeId id) { ItemType::None, 28}; static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; + static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; + static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; + static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; case RecipeId::BuildCabin: return cabin; case RecipeId::BuildBed: return bed; case RecipeId::WeaveCloth: return weave; + case RecipeId::BuildFloor: return floor; + case RecipeId::BuildWall: return wall; + case RecipeId::BuildDoorAlongX: + case RecipeId::BuildDoorAlongY: return door; } throw std::invalid_argument("unknown production recipe"); } @@ -124,6 +135,38 @@ struct OpenNodeLater { } // namespace +RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept { + return {{std::min(first.x, last.x), std::min(first.y, last.y)}, + {std::max(first.x, last.x), std::max(first.y, last.y)}}; +} + +bool RoomPlan::valid_size() const noexcept { + const auto width = static_cast(last.x) - first.x + 1; + const auto height = static_cast(last.y) - first.y + 1; + return width >= 3 && width <= 12 && height >= 3 && height <= 12 && entrance <= RoomSide::West; +} + +bool RoomPlan::contains(GridPosition cell) const noexcept { + return cell.x >= first.x && cell.x <= last.x && cell.y >= first.y && cell.y <= last.y; +} + +RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept { + const auto middle_x = std::midpoint(first.x, last.x), middle_y = std::midpoint(first.y, last.y); + if (cell.y == first.y || cell.y == last.y) { + if (cell.x == middle_x && (cell.y == first.y ? entrance == RoomSide::North : entrance == RoomSide::South)) { + return RecipeId::BuildDoorAlongX; + } + return RecipeId::BuildWall; + } + if (cell.x == first.x || cell.x == last.x) { + if (cell.y == middle_y && (cell.x == first.x ? entrance == RoomSide::West : entrance == RoomSide::East)) { + return RecipeId::BuildDoorAlongY; + } + return RecipeId::BuildWall; + } + return RecipeId::BuildFloor; +} + std::uint32_t Inventory::item_count(ItemType type) const noexcept { const auto index = static_cast(type); return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; @@ -318,7 +361,7 @@ void World::queue_production(GridPosition position, RecipeId recipe) { throw std::invalid_argument("the production site is occupied"); } for (const ProductionOrder& order : production_orders_) { - if (is_production_object(order.recipe) && order.position == position) { + if (is_production_object(order.recipe) && order.position == position && !is_finished_floor(order)) { throw std::invalid_argument("a building occupies the production site"); } } @@ -334,7 +377,32 @@ bool World::can_place_cabin(GridPosition position) const noexcept { return std::none_of(storages_.begin(), storages_.end(), occupies_cell) && std::none_of(resource_nodes_.begin(), resource_nodes_.end(), occupies_cell) && std::none_of(jobs_.begin(), jobs_.end(), occupies_cell) && - std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell); + std::none_of(production_orders_.begin(), production_orders_.end(), + [&](const auto& order) { return occupies_cell(order) && !is_finished_floor(order); }); +} + +bool World::can_place_room(const RoomPlan& plan) const noexcept { + if (!plan.valid_size() || !is_walkable(plan.first) || !is_walkable(plan.last)) return false; + const int middle_x = std::midpoint(plan.first.x, plan.last.x); + const int middle_y = std::midpoint(plan.first.y, plan.last.y); + const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y}, + {middle_x, plan.last.y + 1}, {plan.first.x - 1, middle_y}}; + if (!is_walkable(exits[static_cast(plan.entrance)]) || + (scenario_active_ && plan.contains(scenario_sawmill_))) return false; + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + if (!is_walkable({x, y})) return false; + } + } + const auto inside = [&](const auto& entity) { return plan.contains(entity.position); }; + return std::none_of(production_orders_.begin(), production_orders_.end(), inside) && + std::none_of(resource_nodes_.begin(), resource_nodes_.end(), inside) && + std::none_of(storages_.begin(), storages_.end(), inside) && + std::none_of(jobs_.begin(), jobs_.end(), inside) && + std::none_of(agents_.begin(), agents_.end(), [&](const Agent& agent) { + return (agent.state == AgentState::Sleeping && inside(agent)) || + (agent.state == AgentState::GoingToSleep && !agent.route.empty() && plan.contains(agent.route.back())); + }); } std::array World::construction_materials(RecipeId recipe, BedBase base) const { @@ -416,6 +484,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe constexpr auto ready = CommandStatus::Accepted; for (const auto& order : production_orders_) { if (order.position != position || !is_production_object(order.recipe)) continue; + if (is_finished_floor(order)) continue; + if (moving && order.recipe >= RecipeId::BuildFloor) return CommandStatus::InvalidTarget; return order.state == JobState::InProgress || resting_at(position) ? busy : ready; } for (std::size_t i = 0; i < storages_.size(); ++i) { @@ -436,6 +506,8 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe } return node.reserved_workers != 0 ? busy : ready; } + if (!moving && !resting_at(position) && std::any_of(production_orders_.begin(), production_orders_.end(), + [position](const auto& order) { return order.position == position && is_finished_floor(order); })) return ready; return CommandStatus::InvalidTarget; } @@ -450,7 +522,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest if (index != no_entity_index && index > removed) --index; }; const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) { - return is_production_object(entry.recipe) && at_position(entry); + return is_production_object(entry.recipe) && !is_finished_floor(entry) && at_position(entry); }); if (order != production_orders_.end()) { if (destination) order->position = *destination; @@ -476,7 +548,15 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest return CommandStatus::Accepted; } const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position); - if (source == resource_nodes_.end()) return CommandStatus::InvalidTarget; + if (source == resource_nodes_.end()) { + const auto floor = std::find_if(production_orders_.begin(), production_orders_.end(), + [&](const auto& entry) { return is_finished_floor(entry) && at_position(entry); }); + if (floor == production_orders_.end() || destination) return CommandStatus::InvalidTarget; + const auto removed = static_cast(floor - production_orders_.begin()); + production_orders_.erase(floor); + for (auto& agent : agents_) shift_index(agent.production_index, removed); + return CommandStatus::Accepted; + } if (destination) source->position = *destination; else { const auto removed = static_cast(source - resource_nodes_.begin()); @@ -495,7 +575,8 @@ std::uint64_t World::next_command_sequence(std::uint8_t player) const noexcept { CommandReceipt World::apply_command(const PlayerCommand& command) { const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; }; const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) || - command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom; + command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom || + command.kind == CommandKind::PlaceRoom; if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession && command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable); if (command.player < colony_host || command.player > colony_player_slots) { @@ -580,6 +661,25 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { } queue_production(command.cell, RecipeId::WeaveCloth); break; + case CommandKind::PlaceRoom: { + const RoomPlan plan{command.cell, command.destination, static_cast(command.value)}; + if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { + return receipt(CommandStatus::InvalidTarget); + } + const auto width = static_cast(plan.last.x - plan.first.x + 1); + const auto height = static_cast(plan.last.y - plan.first.y + 1); + production_orders_.reserve(production_orders_.size() + width * height); + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + ProductionOrder order{}; + order.position = cell; + order.recipe = plan.recipe_at(cell); + production_orders_.push_back(std::move(order)); + } + } + break; + } case CommandKind::PlaceStorage: if (command.value > static_cast(StorageKind::Pantry) || !can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 8a73b39..26e9cdc 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -13,7 +13,7 @@ namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; -constexpr std::uint32_t save_version = 9; +constexpr std::uint32_t save_version = 10; constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; @@ -255,6 +255,7 @@ struct WorldSaveCodec { archive.field(order.recipe); require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); + require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version."); archive.field(order.state); sequence(archive, order.materials, item_types, [&](auto& material) { index(archive, material.storage_index); @@ -361,7 +362,7 @@ void WorldSaveCodec::validate(const World& world) { std::vector bed_owners; for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { const auto& order = world.production_orders_[i]; - invalid(order.recipe <= RecipeId::WeaveCloth && order.state <= JobState::Completed && + invalid(order.recipe <= RecipeId::BuildDoorAlongY && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && @@ -424,6 +425,14 @@ void WorldSaveCodec::validate(const World& world) { break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; + case RecipeId::BuildFloor: + case RecipeId::BuildWall: + case RecipeId::BuildDoorAlongX: + case RecipeId::BuildDoorAlongY: + for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { + if (item.count) required[item_index(item.type)] = item.count; + } + break; } invalid(ingredients == required); } diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index e5e13ba..bffadee 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -721,6 +721,48 @@ void test_object_tools_work_in_an_older_demo_world() { static_cast(save_roundtrip(*world)); } +void test_room_builds_and_saves_as_separate_parts() { + using namespace settlement; + World world(61, 16, 16); + static_cast(world.spawn_agent({3, 3})); + const auto storage = world.add_storage({2, 2}, 32); + world.stock_storage(storage, ItemType::Wood, 32); + auto room = make_room_plan({9, 8}, {6, 5}); + room.entrance = RoomSide::East; + const auto place = [&](const RoomPlan& plan) { + return world.apply_command({1, world.next_command_sequence(1), CommandKind::PlaceRoom, plan.first, + static_cast(plan.entrance), plan.last}).status; + }; + require(room.recipe_at({9, 6}) == RecipeId::BuildDoorAlongY, "room lost its entrance"); + world.set_blocked({10, 6}, true); + require(place(room) == CommandStatus::InvalidTarget && world.production_orders().empty(), + "a room with a blocked entrance was partially scheduled"); + world.set_blocked({10, 6}, false); + require(place(room) == CommandStatus::Accepted && world.production_orders().size() == 16, + "room did not queue floor, walls and entrance together"); + require(place(room) == CommandStatus::InvalidTarget && world.production_orders().size() == 16, + "duplicate room placement altered its construction orders"); + world.step(); + require(world.production_orders().front().state == JobState::InProgress, "builders did not start the room"); + auto resumed = save_roundtrip(world); + for (int i = 0; i < 850; ++i) resumed->step(); + for (const auto& order : resumed->production_orders()) { + require(order.state == JobState::Completed && order.recipe == room.recipe_at(order.position), + "room component did not survive delivery and construction after load"); + } + require(resumed->storages().front().item_count(ItemType::Wood) == 15, "room used incorrect materials"); + const auto apply = [&](CommandKind command, GridPosition cell) { + return resumed->apply_command({1, resumed->next_command_sequence(1), command, cell}).status; + }; + const GridPosition floor{7, 6}; + require(apply(CommandKind::PlaceLoom, floor) == CommandStatus::Accepted, + "finished floor could not hold furniture"); + require(apply(CommandKind::DemolishObject, floor) == CommandStatus::Accepted && + resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), + "demolition removed the floor instead of the furniture"); + static_cast(save_roundtrip(*resumed)); +} + } // namespace int main() { @@ -746,6 +788,7 @@ int main() { test_field_growth_requires_a_worker(); test_opening_a_mine_invalidates_unreachable_routes(); test_object_tools_work_in_an_older_demo_world(); + test_room_builds_and_saves_as_separate_parts(); } catch (const std::exception& error) { std::cerr << "Test failed: " << error.what() << '\n'; return 1; diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index 6ea872a..da8b32d 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -134,6 +134,32 @@ void test_shared_colony_over_loopback() { client_view->resource_nodes().back().needs_tending() && client_view->resource_nodes().back().reserved_workers == 1; }, "a snapshot lost the resident's sowing assignment"); + RoomPlan room{}; + bool found_room = false; + for (int y = 2; y < 29 && !found_room; ++y) { + for (int x = 2; x < 29 && !found_room; ++x) { + const auto candidate = make_room_plan({x, y}, {x + 2, y + 2}); + if (!authoritative->can_place_room(candidate)) continue; + room = candidate; + found_room = true; + } + } + require(found_room, "could not find a test plot for a room"); + const auto entrance = static_cast(room.entrance); + const auto previous_size = authoritative->production_orders().size(); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), + "guest could not send the room"); + pump_until([&] { return client_view->production_orders().size() == previous_size + 9; }, + "snapshot did not carry all room components"); + require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), + "guest could not send the conflicting room"); + pump_until([&] { + const auto rejected = guest.take_rejection(); + return rejected && rejected->kind == CommandKind::PlaceRoom && rejected->cell == room.first && + rejected->destination == room.last && rejected->value == entrance && + rejected->status == CommandStatus::InvalidTarget; + }, "room rejection lost the geometry needed to restore the draft"); + require(authoritative->production_orders().size() == previous_size + 9, "room conflict scheduled extra work"); std::cout << "Loopback LAN checks passed.\n"; }