Add a live interface scale slider and room blueprints

This commit is contained in:
Codex committed 2026-11-29 20:21:04 +03:00
1 parent 2a71ed6242
commit 85547b00b9
12 files changed
+553 -96

No files matched your search

+2 -1
View File
@@ -55,7 +55,8 @@
- [ ] Расширение набора 3D-моделей и освещения. - [ ] Расширение набора 3D-моделей и освещения.
- [x] Постановка чертежа домика мышью в Windows-клиенте. - [x] Постановка чертежа домика мышью в Windows-клиенте.
- [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением. - [x] Редактируемая раскладка кроватей и станков с предпросмотром, списком материалов и подтверждением.
- [ ] Чертежи комнат с полом, стенами и проёмами. - [x] Прямоугольные чертежи комнат с полом, стенами, выбором стороны входа и поэтапной стройкой.
- [ ] Маршруты через дверные проёмы и настройка формы комнаты.
- [ ] Интерфейс для остальных типов работ и зданий. - [ ] Интерфейс для остальных типов работ и зданий.
### P5 — Игровые системы и совместная игра ### P5 — Игровые системы и совместная игра
+47 -1
View File
@@ -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<float>(cell.x), y = static_cast<float>(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<float>(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) { void construction(Mesh& mesh, const World& world) {
for (const auto& storage : world.storages()) { for (const auto& storage : world.storages()) {
const float x = static_cast<float>(storage.position.x), y = static_cast<float>(storage.position.y); const float x = static_cast<float>(storage.position.x), y = static_cast<float>(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); 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); 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)) { (order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) {
mesh.box(x, y, .045f, .77f, .43f, .18f, mesh.box(x, y, .045f, .77f, .43f, .18f,
order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66)); 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<std
terrain(graphics.mesh, world, view); terrain(graphics.mesh, world, view);
resources(graphics.mesh, world); resources(graphics.mesh, world);
construction(graphics.mesh, world); construction(graphics.mesh, world);
for (const auto& plan : view.room_blueprints) draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false); for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true); if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view); residents(graphics.mesh, world, view);
+2
View File
@@ -32,6 +32,8 @@ struct SceneView {
std::optional<AgentId> selected; std::optional<AgentId> selected;
std::span<const BlueprintPart> blueprint; std::span<const BlueprintPart> blueprint;
std::optional<BlueprintPart> preview; std::optional<BlueprintPart> preview;
std::span<const RoomPlan> room_blueprints;
std::optional<RoomPlan> room_preview;
}; };
class D3DScene { class D3DScene {
+1
View File
@@ -17,6 +17,7 @@ struct LanRejection {
CommandKind kind; CommandKind kind;
GridPosition cell; GridPosition cell;
std::uint8_t value; std::uint8_t value;
GridPosition destination;
}; };
class LanSession { class LanSession {
+2 -2
View File
@@ -24,7 +24,7 @@ namespace {
using Clock = std::chrono::steady_clock; using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals; 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 std::size_t frame_limit = 4 * 1024 * 1024;
constexpr auto poll_budget = 16; constexpr auto poll_budget = 16;
constexpr std::size_t command_queue_limit = 32; 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::Busy) throw std::runtime_error("Invalid command result.");
if (status != CommandStatus::Accepted) { if (status != CommandStatus::Accepted) {
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, 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)); guest_sequence = number(payload.substr(1));
awaiting_receipt.reset(); awaiting_receipt.reset();
+291 -81
View File
@@ -64,6 +64,7 @@ constexpr int flax_field_id = 1038;
constexpr int loom_id = 1039; constexpr int loom_id = 1039;
constexpr int farmer_menu_id = 1040; constexpr int farmer_menu_id = 1040;
constexpr int builder_menu_id = 1043; constexpr int builder_menu_id = 1043;
constexpr int room_tool_id = 1044;
constexpr int first_work_choice_id = 1050; constexpr int first_work_choice_id = 1050;
constexpr int resident_list_id = 1060; constexpr int resident_list_id = 1060;
constexpr int first_role_id = 1070; constexpr int first_role_id = 1070;
@@ -73,8 +74,10 @@ constexpr int build_blueprint_id = 1084;
constexpr int clear_blueprint_id = 1085; constexpr int clear_blueprint_id = 1085;
constexpr int exit_menu_id = 1121; constexpr int exit_menu_id = 1121;
constexpr int interface_scale_id = 1122; constexpr int interface_scale_id = 1122;
constexpr int first_scale_id = 1130; constexpr int scale_slider_id = 1130;
constexpr std::array interface_scales{100, 125, 150}; 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 default_interface_scale = 125;
constexpr int timer_id = 1; constexpr int timer_id = 1;
constexpr int map_size = settlement::first_colony_map_size; constexpr int map_size = settlement::first_colony_map_size;
@@ -100,6 +103,7 @@ struct DockLayout {
int height = 0; int height = 0;
int hint_top = 0; int hint_top = 0;
int line_height = 0; int line_height = 0;
int scale = default_interface_scale;
}; };
DockLayout dock_layout; DockLayout dock_layout;
std::array<HWND, 3> dock_section_buttons{}; std::array<HWND, 3> dock_section_buttons{};
@@ -118,7 +122,7 @@ settlement::viewer::LanSession lan;
LanState displayed_lan_state = LanState::Offline; LanState displayed_lan_state = LanState::Offline;
const auto local_worker_count = std::clamp<std::size_t>( const auto local_worker_count = std::clamp<std::size_t>(
std::thread::hardware_concurrency(), settlement::min_worker_count, 8); 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; PlacementMode placement_mode = PlacementMode::None;
enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None };
WorkPanel work_panel = WorkPanel::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{pantry_id, L"Кладовая", WorkIcon::Pantry, 103, PlacementMode::Pantry},
WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move}, WorkChoice{move_id, L"Перенести", WorkIcon::Move, 108, PlacementMode::Move},
WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish}, WorkChoice{demolish_id, L"Снести", WorkIcon::Demolish, 90, PlacementMode::Demolish},
WorkChoice{room_tool_id, L"Комната", WorkIcon::Hammer, 116, PlacementMode::Room},
}; };
std::array<HWND, builder_choices.size()> work_choice_buttons{}; std::array<HWND, builder_choices.size()> work_choice_buttons{};
constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; 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], constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0],
builder_choices[2], builder_choices[3]}; builder_choices[2], builder_choices[3]};
constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], 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 { struct DockSection {
WorkPanel panel; WorkPanel panel;
const wchar_t* title; const wchar_t* title;
@@ -196,6 +201,8 @@ struct ResidentRoster {
ResidentRoster roster; ResidentRoster roster;
std::optional<settlement::BedBase> selected_bed_base; std::optional<settlement::BedBase> selected_bed_base;
std::vector<settlement::viewer::BlueprintPart> blueprint; std::vector<settlement::viewer::BlueprintPart> blueprint;
std::vector<settlement::RoomPlan> room_blueprints;
std::optional<settlement::GridPosition> room_anchor;
std::optional<settlement::GridPosition> move_source; std::optional<settlement::GridPosition> move_source;
settlement::viewer::MapCamera camera; settlement::viewer::MapCamera camera;
struct CameraDrag { struct CameraDrag {
@@ -210,7 +217,7 @@ std::optional<settlement::AgentId> selected_resident;
std::wstring placement_message; std::wstring placement_message;
int dock_pixels(int pixels) { 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) { COLORREF color(int red, int green, int blue) {
@@ -351,11 +358,16 @@ bool shows_bed_choices() {
} }
bool is_blueprint_tool() { 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() { 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) { bool is_map_point(const RECT& client, POINT point) {
@@ -468,16 +480,11 @@ std::span<const WorkChoice> work_choices() {
return {}; return {};
} }
void layout_command_dock(HWND window) { DockLayout measure_command_dock(int width, int height, int scale, bool position_controls) {
RECT client{}; const auto pixels = [scale](int amount) { return MulDiv(amount, scale, 100); };
GetClientRect(window, &client); const bool compact = height < 760;
const auto width = static_cast<int>(client.right); const int margin = pixels(compact ? 8 : 12);
const auto height = static_cast<int>(client.bottom); const int gap = pixels(compact ? 5 : 7);
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);
const int available = std::max(1, width - margin * 2); const int available = std::max(1, width - margin * 2);
int bottom = height - margin; int bottom = height - margin;
struct DockItem { struct DockItem {
@@ -485,8 +492,8 @@ void layout_command_dock(HWND window) {
int width; int width;
bool materials = false; bool materials = false;
}; };
const auto place = [](HWND button, int x, int y, int w, int h) { const auto place = [&](HWND button, int x, int y, int w, int h) {
SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); if (position_controls) SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE);
}; };
const auto layout_rows = [&](std::span<const DockItem> items, int button_height) { const auto layout_rows = [&](std::span<const DockItem> items, int button_height) {
// Pack from the end so rows near the bottom stay fixed as the window grows. // 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(); auto start = items.size();
do { do {
const auto& item = items[start - 1]; 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; if (row_width + required > available) break;
row_width += required; row_width += required;
materials |= item.materials; materials |= item.materials;
--start; --start;
} while (start != 0); } 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); int x = std::max(margin, (width - row_width) / 2);
const int y = bottom - material_height - button_height; const int y = bottom - material_height - button_height;
for (const auto& item : items.subspan(start)) { 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); place(item.control, x, y, w, button_height);
if (item.materials) { if (item.materials) {
const int half = (w - gap) / 2; 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}, {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}, {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(); const auto choices = work_choices();
std::array<DockItem, builder_choices.size()> tools{}; std::array<DockItem, builder_choices.size()> tools{};
for (std::size_t index = 0; index < choices.size(); ++index) { 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; const bool bed = choice.command == cabin_button_id;
tools[index] = {work_choice_buttons[index], choice.width + (bed ? 32 : 14), bed && shows_bed_choices()}; 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; if (choices.empty()) bottom -= tool_height + gap;
else layout_rows(std::span(tools).first(choices.size()), tool_height); else layout_rows(std::span(tools).first(choices.size()), tool_height);
if (shows_blueprint_actions()) { if (shows_blueprint_actions()) {
const DockItem actions[] = {{build_blueprint_button, 182}, {clear_blueprint_button, 188}}; 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 hint_top = bottom - 2 * line_height;
const int new_height = height - hint_top + dock_pixels(8); return {height - hint_top + pixels(8), hint_top, line_height, scale};
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);
} }
std::filesystem::path interface_settings_file() { void update_dock_font() {
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;
const auto font = CreateFontW(-dock_pixels(15), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, 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"); OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
const auto face = reinterpret_cast<WPARAM>(font ? font : GetStockObject(DEFAULT_GUI_FONT)); const auto face = reinterpret_cast<WPARAM>(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); for (const auto button : work_choice_buttons) set_font(button);
if (dock_font) DeleteObject(dock_font); if (dock_font) DeleteObject(dock_font);
dock_font = 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); layout_command_dock(window);
InvalidateRect(window, nullptr, FALSE); InvalidateRect(window, nullptr, FALSE);
} }
@@ -586,8 +615,7 @@ int read_interface_scale() {
const auto file = interface_settings_file(); const auto file = interface_settings_file();
if (file.empty()) return default_interface_scale; if (file.empty()) return default_interface_scale;
const auto scale = static_cast<int>(GetPrivateProfileIntW(L"Interface", L"Scale", default_interface_scale, file.c_str())); const auto scale = static_cast<int>(GetPrivateProfileIntW(L"Interface", L"Scale", default_interface_scale, file.c_str()));
return std::find(interface_scales.begin(), interface_scales.end(), scale) != interface_scales.end() return scale >= min_interface_scale && scale <= max_interface_scale ? scale : default_interface_scale;
? scale : default_interface_scale;
} }
void invalidate_work_choices() { 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 residents_button_id: return draw(WorkIcon::Resident, roster.window != nullptr);
case work_list_button_id: return draw(WorkIcon::Hammer); case work_list_button_id: return draw(WorkIcon::Hammer);
case priority_button_id: return draw(WorkIcon::Priority); 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); case clear_blueprint_id: return draw(WorkIcon::Demolish);
} }
if (id >= first_dock_section_id && static_cast<std::size_t>(id - first_dock_section_id) < dock_sections.size()) { if (id >= first_dock_section_id && static_cast<std::size_t>(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); for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play); EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, 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"Равный приоритет"; const wchar_t* priority = L"Равный приоритет";
if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда";
else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) 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; const int visibility = shows_blueprint_actions() ? SW_SHOWNA : SW_HIDE;
ShowWindow(build_blueprint_button, visibility); ShowWindow(build_blueprint_button, visibility);
ShowWindow(clear_blueprint_button, visibility); ShowWindow(clear_blueprint_button, visibility);
EnableWindow(build_blueprint_button, !blueprint.empty() && can_give_orders()); EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders());
EnableWindow(clear_blueprint_button, !blueprint.empty()); EnableWindow(clear_blueprint_button, has_blueprint());
layout_command_dock(window); layout_command_dock(window);
} }
@@ -852,6 +880,7 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message
placement_mode = mode; placement_mode = mode;
selected_bed_base.reset(); selected_bed_base.reset();
move_source.reset(); move_source.reset();
room_anchor.reset();
hover_cell.reset(); hover_cell.reset();
placement_message = message; placement_message = message;
update_bed_choices(); update_bed_choices();
@@ -860,6 +889,12 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message
invalidate_scene(window); invalidate_scene(window);
} }
void clear_blueprints() {
blueprint.clear();
room_blueprints.clear();
room_anchor.reset();
}
void toggle_work_panel(HWND window, WorkPanel panel) { void toggle_work_panel(HWND window, WorkPanel panel) {
if (!can_give_orders()) return; if (!can_give_orders()) return;
set_placement_mode(window, PlacementMode::None); set_placement_mode(window, PlacementMode::None);
@@ -906,7 +941,7 @@ void show_title_screen(HWND window, bool visible) {
void reset_world(HWND window) { void reset_world(HWND window) {
world = settlement::make_first_colony(local_worker_count); world = settlement::make_first_colony(local_worker_count);
blueprint.clear(); clear_blueprints();
camera = {}; camera = {};
selected_resident.reset(); selected_resident.reset();
sync_resident_roster(true); sync_resident_roster(true);
@@ -987,7 +1022,7 @@ void handle_save_menu(HWND window, bool saving, std::optional<std::filesystem::p
throw std::runtime_error("This viewer opens saves with a 32 by 32 map."); throw std::runtime_error("This viewer opens saves with a 32 by 32 map.");
} }
world = std::move(loaded); world = std::move(loaded);
blueprint.clear(); clear_blueprints();
camera = {}; camera = {};
selected_resident.reset(); selected_resident.reset();
sync_resident_roster(true); sync_resident_roster(true);
@@ -1144,7 +1179,7 @@ void handle_lan_menu(HWND window, int command) {
lan.host(); lan.host();
if (colony) { if (colony) {
world = std::move(colony); world = std::move(colony);
blueprint.clear(); clear_blueprints();
camera = {}; camera = {};
selected_resident.reset(); selected_resident.reset();
} }
@@ -1159,7 +1194,7 @@ void handle_lan_menu(HWND window, int command) {
if (!request) return; if (!request) return;
if (!world) world = settlement::make_first_colony(local_worker_count); if (!world) world = settlement::make_first_colony(local_worker_count);
lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data()));
blueprint.clear(); clear_blueprints();
enter_game_on_snapshot = true; enter_game_on_snapshot = true;
selected_resident.reset(); selected_resident.reset();
sync_resident_roster(true); 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::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted;
case PlacementMode::Building: case PlacementMode::Building:
return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell); return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell);
case PlacementMode::Room:
case PlacementMode::None: return false; case PlacementMode::None: return false;
} }
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<settlement::viewer::BlueprintPart> preview_blueprint(settlement::GridPosition cell) { std::optional<settlement::viewer::BlueprintPart> preview_blueprint(settlement::GridPosition cell) {
using settlement::RecipeId; using settlement::RecipeId;
if (placement_mode == PlacementMode::Loom) { if (placement_mode == PlacementMode::Loom) {
@@ -1286,7 +1387,8 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) {
if (!can_give_orders()) return; if (!can_give_orders()) return;
if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) { if (std::erase_if(blueprint, [cell](const auto& part) { return part.cell == cell; }) != 0) {
placement_message = L"Объект убран из чертежа."; 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); blueprint.push_back(*part);
placement_message.clear(); placement_message.clear();
} else { } else {
@@ -1299,10 +1401,14 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) {
} }
void submit_blueprint(HWND window) { 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::CommandKind;
using settlement::RecipeId; 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<std::uint8_t>(room.entrance), room.last) == settlement::CommandStatus::Accepted;
});
const auto objects_sent = std::erase_if(blueprint, [](const auto& part) {
switch (part.recipe) { switch (part.recipe) {
case RecipeId::BuildBed: case RecipeId::BuildBed:
return world->can_place_bed(part.cell) && return world->can_place_bed(part.cell) &&
@@ -1320,10 +1426,10 @@ void submit_blueprint(HWND window) {
return false; return false;
} }
}); });
const std::wstring count = std::to_wstring(sent); const std::wstring count = std::to_wstring(rooms_sent + objects_sent);
if (!blueprint.empty()) { if (has_blueprint()) {
placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " +
std::to_wstring(blueprint.size()) + std::to_wstring(blueprint.size() + room_blueprints.size()) +
(lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." :
L". Проверьте, свободны ли клетки и есть ли к ним проход."); L". Проверьте, свободны ли клетки и есть ли к ним проход.");
} else { } else {
@@ -1660,7 +1766,15 @@ std::wstring blueprint_details() {
totals[static_cast<std::size_t>(material.type)] += material.count; totals[static_cast<std::size_t>(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<std::size_t>(item.type)] += item.count;
}
}
}
std::wstring text = L"Чертёж · объектов " + std::to_wstring(blueprint.size() + room_blueprints.size());
for (const auto& material : materials) { for (const auto& material : materials) {
const auto count = totals[static_cast<std::size_t>(material.type)]; const auto count = totals[static_cast<std::size_t>(material.type)];
if (count != 0) text += std::wstring(L" ") + material.name + L" " + std::to_wstring(count); 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"Выберите кровать, склад, станок или посаженный участок."; L"Выберите кровать, склад, станок или посаженный участок.";
} else if (placement_mode == PlacementMode::Demolish) { } else if (placement_mode == PlacementMode::Demolish) {
hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена.";
} else if (placement_mode == PlacementMode::Room) {
hint = room_anchor ? L"Укажите противоположный угол комнаты." :
L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату.";
} else if (is_blueprint_tool()) { } else if (is_blueprint_tool()) {
hint = shows_bed_choices() && !selected_bed_base hint = shows_bed_choices() && !selected_bed_base
? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."
@@ -1723,7 +1840,7 @@ void draw_world(HDC dc, int width, int height) {
const int margin = dock_pixels(12); const int margin = dock_pixels(12);
RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height}; 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); 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)); SetTextColor(dc, color(190, 201, 178));
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height}; 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); 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 pan = camera.offset();
const auto scale = camera.scale(); const auto scale = camera.scale();
const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt;
const bool valid_cursor = cursor && valid_edit_cell(*cursor); std::optional<settlement::RoomPlan> 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() && 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; }) std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == *cursor; })
? preview_blueprint(*cursor) : std::nullopt; ? preview_blueprint(*cursor) : std::nullopt;
return {width, height, static_cast<float>(width / 2 * scale + pan.x), return {width, height, static_cast<float>(width / 2 * scale + pan.x),
static_cast<float>(map_origin_y * scale + pan.y - map_top), static_cast<float>(map_origin_y * scale + pan.y - map_top),
static_cast<float>(scale), tile_width / 2.f, tile_height / 2.f, static_cast<float>(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) { 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<const MenuAc
return static_cast<int>(action); return static_cast<int>(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<HMENU>(static_cast<INT_PTR>(id)), GetModuleHandleW(nullptr), nullptr);
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(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<LPARAM>(slider));
SetFocus(slider);
return FALSE;
}
case WM_HSCROLL:
if (reinterpret_cast<HWND>(lparam) == GetDlgItem(dialog, scale_slider_id)) {
const auto scale = static_cast<int>(SendMessageW(reinterpret_cast<HWND>(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) { void choose_interface_scale(HWND window) {
std::array<std::wstring, interface_scales.size()> captions; struct alignas(DWORD) EmptyDialog {
std::array<MenuAction, interface_scales.size()> actions{}; DLGTEMPLATE header{};
for (std::size_t index = 0; index < interface_scales.size(); ++index) { WORD menu = 0, window_class = 0, title = 0;
const auto scale = interface_scales[index]; } layout;
captions[index] = std::to_wstring(scale) + L"%"; layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER;
if (scale == interface_scale) captions[index] += L" · текущий"; layout.header.cx = 243;
actions[index] = {first_scale_id + static_cast<int>(index), captions[index].c_str()}; 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<int>(interface_scales.size())) return;
const int scale = interface_scales[static_cast<std::size_t>(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) { void open_pause_menu(HWND window) {
@@ -2035,8 +2208,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
SetFocus(window); SetFocus(window);
return 0; return 0;
} }
if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && !blueprint.empty()) { if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && has_blueprint()) {
blueprint.clear(); clear_blueprints();
placement_message = L"Чертёж очищен."; placement_message = L"Чертёж очищен.";
update_blueprint_controls(window); update_blueprint_controls(window);
SetFocus(window); SetFocus(window);
@@ -2091,6 +2264,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
SetFocus(window); SetFocus(window);
return 0; 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() && if (HIWORD(wparam) == BN_CLICKED && shows_bed_choices() &&
(LOWORD(wparam) == wood_bed_button_id || LOWORD(wparam) == stone_bed_button_id)) { (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; 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; return 0;
} }
if (world && is_blueprint_tool()) { 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; return 0;
} }
if (world && placement_mode >= PlacementMode::BerryField) { if (world && placement_mode >= PlacementMode::BerryField) {
@@ -2216,6 +2397,26 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
break; break;
} }
case WM_RBUTTONDOWN: 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) { if (placement_mode != PlacementMode::None || work_panel != WorkPanel::None) {
set_placement_mode(window, PlacementMode::None); set_placement_mode(window, PlacementMode::None);
set_work_panel(window, WorkPanel::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::CommandKind;
using settlement::RecipeId; using settlement::RecipeId;
const bool bed = rejection->kind == CommandKind::PlaceBed; 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<settlement::RoomSide>(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(), if (std::none_of(blueprint.begin(), blueprint.end(),
[&](const auto& part) { return part.cell == rejection->cell; })) { [&](const auto& part) { return part.cell == rejection->cell; })) {
blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth, 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 } // namespace
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { 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); InitCommonControlsEx(&controls);
WNDCLASSEXW window_class_info{}; WNDCLASSEXW window_class_info{};
window_class_info.cbSize = sizeof(window_class_info); window_class_info.cbSize = sizeof(window_class_info);
+3 -1
View File
@@ -20,6 +20,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж.
В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены.
Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту.
Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна. Уставшие жители работают медленнее и после поручения идут к закреплённой кровати. На земле они отдыхают только при сильной усталости и восстанавливают меньше сил. Щелчок по жителю показывает усталость и состояние сна.
@@ -40,7 +42,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой. Esc открывает меню игры из любого режима строительства и выбора. В одиночной партии симуляция останавливается, пока меню открыто. «Продолжить» или Esc закрывает меню. Выбранный на карте инструмент можно использовать дальше. В этом меню доступны сохранение, загрузка, главное меню и выход. Файл `.settlement` хранит карту, текущий такт, голод, запасы, заказы и маршруты. При ошибке загрузки текущая колония остаётся открытой.
«Esc → Масштаб панели» меняет размер кнопок, значков и текста внизу. Доступны 100%, 125% и 150%. По умолчанию используется 125%, выбранный масштаб запоминается между запусками. «Esc → Масштаб панели» открывает ползунок от 50% до 250% с предпросмотром. «Применить» сохраняет выбор между запусками, «Отмена» возвращает предыдущий масштаб. В маленьком окне панель подстраивается под доступное место, чтобы оставить видимой карту. По умолчанию используется 125%.
В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки. В одиночной игре «Esc → Главное меню» возвращает на стартовый экран и останавливает симуляцию. «Продолжить» возвращает к текущей колонии. «Новая колония» запускает отдельную партию с поэтапной сборкой и стартовым запасом ткани. Старые сохранения продолжаются со своими правилами стройки.
+20 -3
View File
@@ -74,21 +74,37 @@ enum class RecipeId : std::uint8_t {
CutStoneBlock, CutStoneBlock,
BuildCabin, BuildCabin,
BuildBed, BuildBed,
WeaveCloth WeaveCloth,
BuildFloor,
BuildWall,
BuildDoorAlongX,
BuildDoorAlongY
}; };
enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedBase : std::uint8_t { Wood, Stone };
enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow };
constexpr bool is_construction(RecipeId recipe) noexcept { 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 WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst };
enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder };
enum class CommandKind : std::uint8_t { enum class CommandKind : std::uint8_t {
PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3,
PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, 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 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy };
@@ -273,6 +289,7 @@ public:
void enable_hunger() noexcept; void enable_hunger() noexcept;
void queue_production(GridPosition position, RecipeId recipe); void queue_production(GridPosition position, RecipeId recipe);
[[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept;
[[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const; [[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const;
void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter);
void start_scenario(GridPosition sawmill); void start_scenario(GridPosition sawmill);
+105 -5
View File
@@ -35,6 +35,10 @@ bool is_production_object(RecipeId recipe) noexcept {
return is_construction(recipe) || recipe == RecipeId::WeaveCloth; 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 { bool can_take_work(const Agent& agent, Profession profession) noexcept {
return agent.profession == Profession::Generalist || agent.profession == profession; return agent.profession == Profession::Generalist || agent.profession == profession;
} }
@@ -62,12 +66,19 @@ const Recipe& recipe_for(RecipeId id) {
ItemType::None, 28}; ItemType::None, 28};
static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; 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 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) { switch (id) {
case RecipeId::SawPlank: return saw; case RecipeId::SawPlank: return saw;
case RecipeId::CutStoneBlock: return cut; case RecipeId::CutStoneBlock: return cut;
case RecipeId::BuildCabin: return cabin; case RecipeId::BuildCabin: return cabin;
case RecipeId::BuildBed: return bed; case RecipeId::BuildBed: return bed;
case RecipeId::WeaveCloth: return weave; 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"); throw std::invalid_argument("unknown production recipe");
} }
@@ -124,6 +135,38 @@ struct OpenNodeLater {
} // namespace } // 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<std::int64_t>(last.x) - first.x + 1;
const auto height = static_cast<std::int64_t>(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 { std::uint32_t Inventory::item_count(ItemType type) const noexcept {
const auto index = static_cast<std::size_t>(type); const auto index = static_cast<std::size_t>(type);
return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; 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"); throw std::invalid_argument("the production site is occupied");
} }
for (const ProductionOrder& order : production_orders_) { 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"); 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) && return std::none_of(storages_.begin(), storages_.end(), occupies_cell) &&
std::none_of(resource_nodes_.begin(), resource_nodes_.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(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<std::size_t>(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<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase base) const { std::array<ItemStack, 2> 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; constexpr auto ready = CommandStatus::Accepted;
for (const auto& order : production_orders_) { for (const auto& order : production_orders_) {
if (order.position != position || !is_production_object(order.recipe)) continue; 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; return order.state == JobState::InProgress || resting_at(position) ? busy : ready;
} }
for (std::size_t i = 0; i < storages_.size(); ++i) { 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; 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; return CommandStatus::InvalidTarget;
} }
@@ -450,7 +522,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
if (index != no_entity_index && index > removed) --index; if (index != no_entity_index && index > removed) --index;
}; };
const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) { 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 (order != production_orders_.end()) {
if (destination) order->position = *destination; if (destination) order->position = *destination;
@@ -476,7 +548,15 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
return CommandStatus::Accepted; return CommandStatus::Accepted;
} }
const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position); 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<std::size_t>(floor - production_orders_.begin());
production_orders_.erase(floor);
for (auto& agent : agents_) shift_index(agent.production_index, removed);
return CommandStatus::Accepted;
}
if (destination) source->position = *destination; if (destination) source->position = *destination;
else { else {
const auto removed = static_cast<std::size_t>(source - resource_nodes_.begin()); const auto removed = static_cast<std::size_t>(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) { CommandReceipt World::apply_command(const PlayerCommand& command) {
const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; }; const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; };
const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) || 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 && if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession &&
command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable); command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable);
if (command.player < colony_host || command.player > colony_player_slots) { 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); queue_production(command.cell, RecipeId::WeaveCloth);
break; break;
case CommandKind::PlaceRoom: {
const RoomPlan plan{command.cell, command.destination, static_cast<RoomSide>(command.value)};
if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) {
return receipt(CommandStatus::InvalidTarget);
}
const auto width = static_cast<std::size_t>(plan.last.x - plan.first.x + 1);
const auto height = static_cast<std::size_t>(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: case CommandKind::PlaceStorage:
if (command.value > static_cast<std::uint8_t>(StorageKind::Pantry) || if (command.value > static_cast<std::uint8_t>(StorageKind::Pantry) ||
!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { !can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) {
+11 -2
View File
@@ -13,7 +13,7 @@ namespace settlement {
namespace { namespace {
constexpr std::string_view signature = "SETTLERS"; 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::uint32_t last_legacy_footer_version = 8;
constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_records = 1'000'000;
constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024;
@@ -255,6 +255,7 @@ struct WorldSaveCodec {
archive.field(order.recipe); archive.field(order.recipe);
require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); 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 >= 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); archive.field(order.state);
sequence(archive, order.materials, item_types, [&](auto& material) { sequence(archive, order.materials, item_types, [&](auto& material) {
index(archive, material.storage_index); index(archive, material.storage_index);
@@ -361,7 +362,7 @@ void WorldSaveCodec::validate(const World& world) {
std::vector<AgentId> bed_owners; std::vector<AgentId> bed_owners;
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
const auto& order = world.production_orders_[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) && world.is_walkable(order.position) &&
(order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed));
invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow &&
@@ -424,6 +425,14 @@ void WorldSaveCodec::validate(const World& world) {
break; break;
case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break;
case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 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); invalid(ingredients == required);
} }
+43
View File
@@ -721,6 +721,48 @@ void test_object_tools_work_in_an_older_demo_world() {
static_cast<void>(save_roundtrip(*world)); static_cast<void>(save_roundtrip(*world));
} }
void test_room_builds_and_saves_as_separate_parts() {
using namespace settlement;
World world(61, 16, 16);
static_cast<void>(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<std::uint8_t>(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<void>(save_roundtrip(*resumed));
}
} // namespace } // namespace
int main() { int main() {
@@ -746,6 +788,7 @@ int main() {
test_field_growth_requires_a_worker(); test_field_growth_requires_a_worker();
test_opening_a_mine_invalidates_unreachable_routes(); test_opening_a_mine_invalidates_unreachable_routes();
test_object_tools_work_in_an_older_demo_world(); test_object_tools_work_in_an_older_demo_world();
test_room_builds_and_saves_as_separate_parts();
} catch (const std::exception& error) { } catch (const std::exception& error) {
std::cerr << "Test failed: " << error.what() << '\n'; std::cerr << "Test failed: " << error.what() << '\n';
return 1; return 1;
+26
View File
@@ -134,6 +134,32 @@ void test_shared_colony_over_loopback() {
client_view->resource_nodes().back().needs_tending() && client_view->resource_nodes().back().needs_tending() &&
client_view->resource_nodes().back().reserved_workers == 1; client_view->resource_nodes().back().reserved_workers == 1;
}, "a snapshot lost the resident's sowing assignment"); }, "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<std::uint8_t>(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"; std::cout << "Loopback LAN checks passed.\n";
} }