#define NOMINMAX #define UNICODE #define _UNICODE #include #include #include #include #include "d3d_scene_win32.hpp" #include "house_icons.h" #include "map_camera.hpp" #include "lan_session.hpp" #include "title_screen_win32.hpp" #include "settlement/core/world.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr wchar_t window_class[] = L"SettlementViewer"; constexpr wchar_t resident_window_class[] = L"SettlementResidentRoster"; constexpr wchar_t scene_window_class[] = L"SettlementD3DViewport"; constexpr int title_menu_id = 1002; constexpr int status_label_id = 1003; constexpr int cabin_button_id = 1004; constexpr int save_menu_id = 1005; constexpr int load_menu_id = 1006; constexpr int forage_action_id = 1007; constexpr int priority_button_id = 1008; constexpr int pause_button_id = 1009; constexpr int reset_camera_id = 1010; constexpr int wood_bed_button_id = 1011; constexpr int stone_bed_button_id = 1012; constexpr int lan_host_id = 1020; constexpr int lan_join_id = 1021; constexpr int lan_info_id = 1022; constexpr int lan_reconnect_id = 1023; constexpr int lan_leave_id = 1024; constexpr int berry_field_id = 1030; constexpr int tree_plot_id = 1031; constexpr int mine_id = 1032; constexpr int storage_id = 1033; constexpr int pantry_id = 1034; constexpr int move_id = 1035; constexpr int demolish_id = 1036; constexpr int residents_button_id = 1037; 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 furnished_room_tool_id = 1045; constexpr int house_list_back_id = 1046; constexpr int carpenter_menu_id = 1047; constexpr int craft_door_id = 1048; constexpr int first_furniture_craft_id = 1143; constexpr int first_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; constexpr int first_dock_section_id = 1080; constexpr int work_list_button_id = 1083; constexpr int build_blueprint_id = 1084; constexpr int clear_blueprint_id = 1085; constexpr int building_view_id = 1086; constexpr int exit_menu_id = 1121; constexpr int interface_scale_id = 1122; constexpr int scale_slider_id = 1130; constexpr int scale_value_id = 1131; constexpr int first_house_tool_id = 1140; 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; constexpr int tile_width = 24; constexpr int tile_height = 14; constexpr int map_origin_y = 86; constexpr int map_top = 76; constexpr settlement::GridPosition sawmill{15, 14}; constexpr settlement::GridPosition stonecutter{17, 14}; HWND status_label = nullptr; HWND production_label = nullptr; HWND wood_bed_button = nullptr; HWND stone_bed_button = nullptr; HWND priority_button = nullptr; HWND work_list_button = nullptr; HWND residents_button = nullptr; HWND build_blueprint_button = nullptr; HWND clear_blueprint_button = nullptr; HWND building_view_button = nullptr; HFONT dock_font = nullptr; int interface_scale = default_interface_scale; 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{}; std::unique_ptr world; namespace title = settlement::viewer; title::TitleScreen title_screen; bool showing_title = true; bool has_session = false; bool enter_game_on_snapshot = false; bool coop_menu_open = false; bool pause_menu_open = false; HWND scene_window = nullptr; settlement::viewer::D3DScene graphics; using settlement::viewer::BuildingView; BuildingView building_view = BuildingView::Full; constexpr const wchar_t* building_view_labels[] = { L"Вид: полный", L"Вид: без крыш", L"Вид: без стен и крыш", }; using settlement::viewer::LanState; 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, Room }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None }; WorkPanel work_panel = WorkPanel::None; WorkPanel house_list_parent = WorkPanel::Construction; enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority, House, Back }; struct WorkChoice { int command; const wchar_t* title; WorkIcon icon; int width; PlacementMode mode = PlacementMode::None; settlement::RoomTemplate layout = settlement::RoomTemplate::Empty; }; constexpr std::array farmer_choices = { WorkChoice{forage_action_id, L"Сбор ягод", WorkIcon::Berries, 113, PlacementMode::Foraging}, WorkChoice{berry_field_id, L"Поле ягод", WorkIcon::Field, 113, PlacementMode::BerryField}, WorkChoice{flax_field_id, L"Поле льна", WorkIcon::Flax, 112, PlacementMode::FlaxField}, }; constexpr std::array woodcutter_choices = { WorkChoice{tree_plot_id, L"Посадить деревья", WorkIcon::Tree, 168, PlacementMode::TreePlot}, }; constexpr std::array miner_choices = { WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, }; constexpr std::array furniture_products = { settlement::ItemType::MedicineCabinet, settlement::ItemType::MiningRack, settlement::ItemType::Loom, }; constexpr std::array carpenter_choices = { WorkChoice{craft_door_id, L"Изготовить дверь", WorkIcon::Wood, 190}, WorkChoice{first_furniture_craft_id, L"Аптечный шкаф", WorkIcon::Crate, 163}, WorkChoice{first_furniture_craft_id + 1, L"Стойка шахтёра", WorkIcon::Pickaxe, 168}, WorkChoice{first_furniture_craft_id + 2, L"Ткацкий станок", WorkIcon::Loom, 163}, }; constexpr std::array builder_choices = { WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, WorkChoice{storage_id, L"Склад", WorkIcon::Crate, 84, PlacementMode::Storage}, 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}, WorkChoice{furnished_room_tool_id, L"Готовые дома", WorkIcon::House, 158}, }; 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[6], builder_choices[7], builder_choices[4], builder_choices[5]}; constexpr std::array house_choices = { WorkChoice{house_list_back_id, L"Назад", WorkIcon::Back, 93}, WorkChoice{first_house_tool_id, L"Дом врача", WorkIcon::House, 155, PlacementMode::Room, settlement::RoomTemplate::Doctor}, WorkChoice{first_house_tool_id + 1, L"Дом шахтёра", WorkIcon::House, 175, PlacementMode::Room, settlement::RoomTemplate::Miner}, WorkChoice{first_house_tool_id + 2, L"Дом ткача", WorkIcon::House, 155, PlacementMode::Room, settlement::RoomTemplate::Weaver}, }; constexpr const wchar_t* house_contents[] = { L"Деревянная кровать и аптечный шкаф", L"Каменная кровать и стойка с инструментами", L"Деревянная кровать и ткацкий станок", }; std::array house_artwork{}; struct DockSection { WorkPanel panel; const wchar_t* title; WorkIcon icon; }; constexpr std::array dock_sections = { DockSection{WorkPanel::Gathering, L"Добыча", WorkIcon::Pickaxe}, DockSection{WorkPanel::Zones, L"Участки", WorkIcon::Field}, DockSection{WorkPanel::Construction, L"Строительство", WorkIcon::Hammer}, }; using settlement::Profession; struct RoleChoice { Profession role; const wchar_t* title; WorkIcon icon; }; constexpr std::array role_choices = { RoleChoice{Profession::Generalist, L"Разнорабочий", WorkIcon::Resident}, RoleChoice{Profession::Farmer, L"Фермер", WorkIcon::Berries}, RoleChoice{Profession::Woodcutter, L"Лесоруб", WorkIcon::Tree}, RoleChoice{Profession::Miner, L"Шахтёр", WorkIcon::Pickaxe}, RoleChoice{Profession::Builder, L"Строитель", WorkIcon::Hammer}, RoleChoice{Profession::Carpenter, L"Плотник", WorkIcon::Wood}, }; struct ResidentRow { settlement::AgentId id; Profession role; }; struct ResidentRoster { HWND window = nullptr; HWND list = nullptr; HWND current_role = nullptr; HWND notice = nullptr; HWND apply = nullptr; std::array roles{}; std::vector rows; std::optional pending_role; bool updating_selection = false; }; ResidentRoster roster; std::optional selected_bed_base; std::vector blueprint; std::vector room_blueprints; std::optional room_anchor; settlement::RoomTemplate selected_room_template = settlement::RoomTemplate::Empty; std::optional preferred_room_entrance; struct RoomDraftMove { std::size_t index; settlement::GridPosition grabbed_cell; settlement::RoomSide entrance; }; std::optional room_draft_move; std::optional move_source; settlement::viewer::MapCamera camera; struct CameraDrag { POINT previous; bool left_button; bool moved; }; std::optional camera_drag; bool file_dialog_active = false; std::optional hover_cell; std::optional selected_resident; std::wstring placement_message; int dock_pixels(int pixels) { return MulDiv(pixels, dock_layout.scale, 100); } COLORREF color(int red, int green, int blue) { return RGB(red, green, blue); } void fill_polygon(HDC dc, const POINT* points, int count, COLORREF fill, COLORREF outline) { HBRUSH brush = CreateSolidBrush(fill); HPEN pen = CreatePen(PS_SOLID, 1, outline); HGDIOBJ old_brush = SelectObject(dc, brush); HGDIOBJ old_pen = SelectObject(dc, pen); Polygon(dc, points, count); SelectObject(dc, old_brush); SelectObject(dc, old_pen); DeleteObject(brush); DeleteObject(pen); } void fill_ellipse(HDC dc, int left, int top, int right, int bottom, COLORREF fill, COLORREF outline) { HBRUSH brush = CreateSolidBrush(fill); HPEN pen = CreatePen(PS_SOLID, 1, outline); HGDIOBJ old_brush = SelectObject(dc, brush); HGDIOBJ old_pen = SelectObject(dc, pen); Ellipse(dc, left, top, right, bottom); SelectObject(dc, old_brush); SelectObject(dc, old_pen); DeleteObject(brush); DeleteObject(pen); } void draw_work_icon(HDC dc, WorkIcon icon, int x, int y, int extent = 17) { const auto ink = color(54, 61, 58); const auto wood = color(158, 101, 52); const auto leaf = color(76, 137, 74); const auto metal = color(143, 168, 180); const auto berry = color(180, 62, 103); const auto blue = color(91, 136, 184); const int state = SaveDC(dc); if (state == 0) return; const float scale = static_cast(extent) / 17.f; const XFORM transform{scale, 0.f, 0.f, scale, static_cast(x), static_cast(y)}; if (extent == 17 || !SetGraphicsMode(dc, GM_ADVANCED) || !SetWorldTransform(dc, &transform)) { OffsetViewportOrgEx(dc, x, y, nullptr); } const auto shape = [&](std::initializer_list points, COLORREF fill) { fill_polygon(dc, points.begin(), static_cast(points.size()), fill, ink); }; const auto box = [&](int left, int top, int right, int bottom, COLORREF fill) { shape({{left, top}, {right, top}, {right, bottom}, {left, bottom}}, fill); }; const auto circle = [&](int left, int top, int right, int bottom, COLORREF fill) { fill_ellipse(dc, left, top, right, bottom, fill, ink); }; switch (icon) { case WorkIcon::Berries: shape({{8, 7}, {8, 3}, {14, 1}, {13, 5}}, leaf); circle(2, 5, 9, 12, berry); circle(9, 5, 16, 12, berry); circle(5, 9, 13, 17, berry); break; case WorkIcon::Field: shape({{1, 10}, {8, 6}, {16, 10}, {16, 12}, {8, 16}, {1, 12}}, wood); shape({{8, 11}, {3, 7}, {3, 4}, {7, 5}, {9, 8}, {12, 3}, {15, 3}, {14, 8}}, leaf); break; case WorkIcon::Flax: shape({{5, 15}, {6, 6}, {9, 8}, {10, 4}, {12, 14}, {9, 16}}, leaf); circle(3, 3, 9, 9, blue); circle(8, 1, 14, 7, blue); break; case WorkIcon::Tree: box(7, 11, 10, 16, wood); shape({{8, 1}, {13, 8}, {11, 8}, {15, 13}, {2, 13}, {6, 8}, {4, 8}}, leaf); break; case WorkIcon::Pickaxe: shape({{2, 14}, {10, 4}, {13, 6}, {5, 16}}, wood); shape({{3, 3}, {8, 1}, {14, 4}, {17, 9}, {12, 6}, {8, 4}}, metal); break; case WorkIcon::Hammer: shape({{2, 14}, {10, 5}, {13, 7}, {5, 16}}, wood); shape({{9, 1}, {16, 7}, {13, 11}, {6, 5}}, metal); break; case WorkIcon::Loom: box(2, 2, 5, 16, wood); box(12, 2, 15, 16, wood); box(2, 2, 15, 5, wood); box(5, 5, 12, 12, color(240, 230, 201)); box(2, 12, 15, 14, wood); break; case WorkIcon::Resident: circle(2, 8, 15, 17, blue); circle(5, 1, 12, 9, color(232, 194, 143)); break; case WorkIcon::Bed: box(1, 4, 3, 15, wood); box(13, 10, 16, 15, wood); box(3, 6, 7, 11, color(249, 240, 213)); box(7, 7, 16, 12, blue); break; case WorkIcon::Wood: box(2, 4, 16, 13, wood); circle(1, 4, 8, 14, color(214, 166, 98)); break; case WorkIcon::Stone: shape({{1, 12}, {4, 5}, {10, 2}, {15, 7}, {16, 13}, {6, 16}}, metal); break; case WorkIcon::Crate: case WorkIcon::Pantry: box(2, 4, 15, 15, icon == WorkIcon::Crate ? wood : leaf); box(1, 3, 16, 7, icon == WorkIcon::Crate ? color(214, 166, 98) : color(152, 183, 108)); box(7, 8, 10, 11, color(241, 205, 119)); break; case WorkIcon::Move: shape({{1, 8}, {6, 3}, {6, 6}, {11, 6}, {11, 3}, {16, 8}, {11, 13}, {11, 10}, {6, 10}, {6, 13}}, blue); break; case WorkIcon::Demolish: shape({{3, 5}, {14, 5}, {13, 16}, {4, 16}}, color(181, 102, 87)); box(6, 2, 11, 5, metal); box(2, 5, 15, 7, metal); break; case WorkIcon::Priority: box(2, 3, 16, 6, metal); box(2, 8, 12, 11, metal); box(2, 13, 8, 16, metal); break; case WorkIcon::House: box(4, 8, 14, 16, wood); shape({{1, 9}, {9, 2}, {17, 9}}, berry); box(7, 10, 11, 16, metal); break; case WorkIcon::Back: shape({{1, 9}, {7, 3}, {7, 7}, {16, 7}, {16, 11}, {7, 11}, {7, 15}}, metal); break; } RestoreDC(dc, state); } POINT map_projection(int x, int y, int origin_x, int origin_y) { return POINT{origin_x + (x - y) * tile_width / 2, origin_y + (x + y) * tile_height / 2}; } bool shows_bed_choices() { return world && world->staged_beds() && placement_mode == PlacementMode::Building; } bool is_blueprint_tool() { 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() || has_blueprint()); } bool is_map_point(const RECT& client, POINT point) { return !showing_title && graphics.ready() && point.x >= 0 && point.x < client.right && point.y >= map_top && point.y < client.bottom - dock_layout.height; } POINT client_point(LPARAM coordinates) { return {GET_X_LPARAM(coordinates), GET_Y_LPARAM(coordinates)}; } void invalidate_scene(HWND window) { RECT scene{}; GetClientRect(window, &scene); scene.top = map_top; if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE); if (!showing_title && graphics.ready() && scene_window) { InvalidateRect(scene_window, nullptr, FALSE); } } void layout_scene(HWND window) { if (!scene_window) return; if (showing_title || !graphics.ready()) { ShowWindow(scene_window, SW_HIDE); ShowWindow(building_view_button, SW_HIDE); return; } RECT client{}; GetClientRect(window, &client); SetWindowPos(scene_window, HWND_BOTTOM, 0, map_top, client.right, std::max(0, static_cast(client.bottom) - map_top - dock_layout.height), SWP_NOACTIVATE | SWP_SHOWWINDOW); const int margin = dock_pixels(10); const int width = dock_pixels(184); SetWindowPos(building_view_button, HWND_TOP, client.right - width - margin, map_top + margin, width, dock_pixels(32), SWP_NOACTIVATE | SWP_SHOWWINDOW); } void update_camera_drag(POINT point) { if (!camera_drag) return; const auto dx = point.x - camera_drag->previous.x; const auto dy = point.y - camera_drag->previous.y; if (camera_drag->left_button && !camera_drag->moved && std::abs(dx) < 4 && std::abs(dy) < 4) return; camera.pan(dx, dy); camera_drag->previous = point; camera_drag->moved = true; } std::optional map_cell(const RECT& client, POINT point) { if (!is_map_point(client, point)) return std::nullopt; const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); const double horizontal = (scene.x - client.right / 2) / (tile_width / 2.0); const double vertical = (scene.y - map_origin_y) / (tile_height / 2.0); const double x = std::floor((vertical + horizontal) / 2.0 + 0.5); const double y = std::floor((vertical - horizontal) / 2.0 + 0.5); if (x < 0 || y < 0 || x >= map_size || y >= map_size) return std::nullopt; return settlement::GridPosition{static_cast(x), static_cast(y)}; } void update_map_hover(HWND window, POINT point) { if (placement_mode == PlacementMode::None) return; TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0}; TrackMouseEvent(&tracking); RECT client{}; GetClientRect(window, &client); const auto cell = map_cell(client, point); if (cell == hover_cell) return; hover_cell = cell; placement_message.clear(); invalidate_scene(window); } POINT resident_position(POINT center, settlement::AgentId id) { const int offset = static_cast(id % 5) - 2; return {center.x + offset * 2, center.y - 4}; } POINT resident_anchor(POINT center, const settlement::Agent& agent) { if (agent.state != settlement::AgentState::Sleeping && world->is_bed_cell(agent.position) && std::any_of(world->agents().begin(), world->agents().end(), [&](const auto& other) { return other.state == settlement::AgentState::Sleeping && !other.resting_on_ground && other.position == agent.position; })) { center.x += tile_width / 2; center.y += tile_height / 2; } return resident_position(center, agent.id); } const wchar_t* profession_name(settlement::Profession profession) { const auto choice = std::find_if(role_choices.begin(), role_choices.end(), [profession](const auto& entry) { return entry.role == profession; }); return choice == role_choices.end() ? L"" : choice->title; } const settlement::Agent* selected_agent() { if (!world || !selected_resident) return nullptr; const auto& agents = world->agents(); const auto agent = std::find_if(agents.begin(), agents.end(), [](const auto& entry) { return entry.id == *selected_resident; }); return agent == agents.end() ? nullptr : &*agent; } std::span work_choices() { switch (work_panel) { case WorkPanel::Farmer: return farmer_choices; case WorkPanel::Woodcutter: return woodcutter_choices; case WorkPanel::Miner: return miner_choices; case WorkPanel::Builder: return builder_choices; case WorkPanel::Gathering: return gathering_choices; case WorkPanel::Zones: return zones_choices; case WorkPanel::Construction: return construction_choices; case WorkPanel::Houses: return house_choices; case WorkPanel::Carpenter: return carpenter_choices; case WorkPanel::None: return {}; } return {}; } 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 { HWND control; int width; bool materials = false; }; 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. while (!items.empty()) { int row_width = 0; bool materials = false; auto start = items.size(); do { const auto& item = items[start - 1]; 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 ? 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, pixels(item.width)); place(item.control, x, y, w, button_height); if (item.materials) { const int half = (w - gap) / 2; const int material_y = y + button_height + gap; place(wood_bed_button, x, material_y, half, material_height - gap); place(stone_bed_button, x + half + gap, material_y, w - half - gap, material_height - gap); } x += w + gap; } bottom = y - gap; items = items.first(start); } }; const DockItem sections[] = { {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, pixels(compact ? 34 : 40)); const auto choices = work_choices(); std::array tools{}; for (std::size_t index = 0; index < choices.size(); ++index) { const auto& choice = choices[index]; 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 = pixels(work_panel == WorkPanel::Houses ? 44 : (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, pixels(compact ? 31 : 37)); } const int line_height = pixels(compact ? 20 : 23); const int hint_top = bottom - 2 * line_height; return {height - hint_top + pixels(8), hint_top, line_height, 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)); const auto set_font = [&](HWND button) { SendMessageW(button, WM_SETFONT, face, TRUE); }; for (const auto button : {priority_button, work_list_button, residents_button, wood_bed_button, stone_bed_button, build_blueprint_button, clear_blueprint_button, building_view_button}) set_font(button); for (const auto button : dock_section_buttons) set_font(button); 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); } bool save_interface_scale(int scale) { const auto file = interface_settings_file(); if (file.empty()) return false; std::error_code error; std::filesystem::create_directories(file.parent_path(), error); if (error) return false; const auto value = std::to_wstring(scale); return WritePrivateProfileStringW(L"Interface", L"Scale", value.c_str(), file.c_str()) != FALSE; } 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 scale >= min_interface_scale && scale <= max_interface_scale ? scale : default_interface_scale; } void invalidate_work_choices() { const auto choices = work_choices(); for (std::size_t index = 0; index < choices.size(); ++index) { InvalidateRect(work_choice_buttons[index], nullptr, FALSE); } } void set_work_panel(HWND window, WorkPanel panel) { if (work_panel == panel) return; work_panel = panel; const auto choices = work_choices(); layout_command_dock(window); for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { const auto button = work_choice_buttons[index]; if (index >= choices.size()) { ShowWindow(button, SW_HIDE); continue; } const auto& choice = choices[index]; SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? L"Чертёж домика" : choice.title); EnableWindow(button, work_panel != WorkPanel::Carpenter || (world && world->scenario_active())); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); invalidate_work_choices(); RECT row{}; GetClientRect(window, &row); row.top = row.bottom - dock_layout.height; InvalidateRect(window, &row, FALSE); } void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, int icon_width = 17, HICON artwork = nullptr) { const bool disabled = (item.itemState & ODS_DISABLED) != 0; const bool pressed = (item.itemState & ODS_SELECTED) != 0; const auto dc = item.hDC; RECT box = item.rcItem; if (dock) { const bool highlighted = !disabled && (active || pressed); const auto brush = CreateSolidBrush(highlighted ? color(85, 105, 72) : color(48, 62, 55)); const auto border = CreateSolidBrush(highlighted ? color(206, 177, 114) : color(92, 106, 86)); FillRect(dc, &box, brush); FrameRect(dc, &box, border); DeleteObject(border); DeleteObject(brush); } else { DrawFrameControl(dc, &box, DFC_BUTTON, DFCS_BUTTONPUSH | (pressed || active ? DFCS_PUSHED : 0U)); } InflateRect(&box, -3, -3); if (!dock && active && !disabled) { const auto brush = CreateSolidBrush(color(211, 229, 194)); FillRect(dc, &box, brush); DeleteObject(brush); } wchar_t title[64]{}; const int length = GetWindowTextW(item.hwndItem, title, static_cast(std::size(title))); const auto font = reinterpret_cast(SendMessageW(item.hwndItem, WM_GETFONT, 0, 0)); const auto previous_font = SelectObject(dc, font ? font : GetStockObject(DEFAULT_GUI_FONT)); SIZE caption{}; GetTextExtentPoint32W(dc, title, length, &caption); constexpr int gap = 5; const int left = std::max(box.left + 2, (box.left + box.right - icon_width - gap - caption.cx) / 2); const int offset = pressed ? 1 : 0; const int icon_x = left + offset, icon_y = (box.top + box.bottom - icon_width) / 2 + offset; if (artwork) DrawIconEx(dc, icon_x, icon_y, artwork, icon_width, icon_width, 0, nullptr, DI_NORMAL); else draw_work_icon(dc, icon, icon_x, icon_y, icon_width); RECT caption_box{left + icon_width + gap + offset, box.top + offset, box.right - 1, box.bottom + offset}; const auto previous_mode = SetBkMode(dc, TRANSPARENT); const auto previous_color = SetTextColor(dc, dock ? (disabled ? color(165, 174, 162) : color(246, 240, 220)) : GetSysColor(disabled ? COLOR_GRAYTEXT : COLOR_BTNTEXT)); DrawTextW(dc, title, length, &caption_box, DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX); SetTextColor(dc, previous_color); SetBkMode(dc, previous_mode); if (previous_font) SelectObject(dc, previous_font); if ((item.itemState & (ODS_FOCUS | ODS_NOFOCUSRECT)) == ODS_FOCUS) DrawFocusRect(dc, &box); } bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { const auto id = static_cast(item.CtlID); const auto draw = [&](WorkIcon icon, bool active = false) { draw_icon_button(item, icon, active, true, dock_pixels(17)); return true; }; switch (id) { case wood_bed_button_id: return draw(WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood); case stone_bed_button_id: return draw(WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone); 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, has_blueprint()); case clear_blueprint_id: return draw(WorkIcon::Demolish); case building_view_id: return draw(WorkIcon::House, building_view != BuildingView::Full); } if (id >= first_dock_section_id && static_cast(id - first_dock_section_id) < dock_sections.size()) { const auto& section = dock_sections[static_cast(id - first_dock_section_id)]; return draw(section.icon, work_panel == section.panel || (work_panel == WorkPanel::Houses && section.panel == WorkPanel::Construction)); } const auto choices = work_choices(); if (id < first_work_choice_id || static_cast(id - first_work_choice_id) >= choices.size()) return false; const auto& choice = choices[static_cast(id - first_work_choice_id)]; const bool active = choice.mode != PlacementMode::None && placement_mode == choice.mode && (choice.mode != PlacementMode::Room || selected_room_template == choice.layout); if (choice.layout != settlement::RoomTemplate::Empty) { const auto artwork = house_artwork[static_cast(choice.layout) - 1]; draw_icon_button(item, choice.icon, active, true, dock_pixels(34), artwork); return true; } return draw(choice.icon, active); } bool can_give_orders() { return !lan.is_guest() || lan.state() == LanState::GuestConnected; } void update_roster_details() { const auto* resident = selected_agent(); const auto role = resident ? profession_name(resident->profession) : L""; const std::wstring title = resident ? L"Текущая роль: " + std::wstring(role) : L"Выберите жителя в списке."; SetWindowTextW(roster.current_role, title.c_str()); const bool can_assign = resident && can_give_orders(); EnableWindow(roster.apply, can_assign && roster.pending_role && *roster.pending_role != resident->profession); for (const auto button : roster.roles) { EnableWindow(button, can_assign); InvalidateRect(button, nullptr, FALSE); } } void sync_resident_roster(bool update_selection = false) { if (!roster.window) return; const auto& agents = world->agents(); const bool rows_changed = !std::equal(agents.begin(), agents.end(), roster.rows.begin(), roster.rows.end(), [](const auto& agent, const auto& row) { return agent.id == row.id && agent.profession == row.role; }); if (!rows_changed && !update_selection) return; if (rows_changed) { const auto old_count = roster.rows.size(); roster.rows.clear(); roster.rows.reserve(agents.size()); for (const auto& agent : agents) roster.rows.push_back({agent.id, agent.profession}); roster.updating_selection = true; if (old_count != roster.rows.size()) { ListView_SetItemCountEx(roster.list, static_cast(roster.rows.size()), LVSICF_NOSCROLL); } roster.updating_selection = false; InvalidateRect(roster.list, nullptr, FALSE); std::array counts{}; for (const auto& row : roster.rows) { for (std::size_t index = 0; index < role_choices.size(); ++index) { if (row.role == role_choices[index].role) ++counts[index]; } } for (std::size_t index = 0; index < role_choices.size(); ++index) { const auto title = std::wstring(role_choices[index].title) + L" (" + std::to_wstring(counts[index]) + L")"; SetWindowTextW(roster.roles[index], title.c_str()); } } if (update_selection) { roster.pending_role.reset(); SetWindowTextW(roster.notice, L""); } const auto row = std::find_if(roster.rows.begin(), roster.rows.end(), [](const auto& entry) { return selected_resident == entry.id; }); const int index = row == roster.rows.end() ? -1 : static_cast(row - roster.rows.begin()); if (ListView_GetNextItem(roster.list, -1, LVNI_SELECTED) != index) { roster.updating_selection = true; ListView_SetItemState(roster.list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); if (index >= 0) { ListView_SetItemState(roster.list, index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); if (update_selection) ListView_EnsureVisible(roster.list, index, FALSE); } roster.updating_selection = false; } update_roster_details(); } void update_status() { if (status_label == nullptr || !world) return; const auto busy = std::count_if(world->agents().begin(), world->agents().end(), [](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; }); std::uint64_t wood = 0; std::uint64_t stone = 0; std::uint64_t planks = 0; std::uint64_t blocks = 0; std::uint64_t berries = 0; std::uint64_t cloth = 0; std::uint64_t flax = 0; std::uint64_t doors = 0; for (const settlement::Storage& storage : world->storages()) { wood += storage.item_count(settlement::ItemType::Wood); stone += storage.item_count(settlement::ItemType::Stone); planks += storage.item_count(settlement::ItemType::Plank); blocks += storage.item_count(settlement::ItemType::StoneBlock); berries += storage.item_count(settlement::ItemType::Berries); cloth += storage.item_count(settlement::ItemType::Cloth); flax += storage.item_count(settlement::ItemType::Flax); doors += storage.available_item_count(settlement::ItemType::WoodenDoor); } const std::wstring text = L"Жители: " + std::to_wstring(world->agents().size()) + L" Заняты: " + std::to_wstring(busy) + L" Выполнено работ: " + std::to_wstring(world->jobs_completed()) + L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) + L" Двери: " + std::to_wstring(doors) + L" Ход: " + std::to_wstring(world->tick()); SetWindowTextW(status_label, text.c_str()); const bool scenario = world->scenario_active(); const bool can_play = can_give_orders(); if (work_panel != WorkPanel::None && !can_play) { set_work_panel(GetParent(residents_button), WorkPanel::None); } 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, has_blueprint() && can_play && !room_draft_move); const wchar_t* priority = L"Равный приоритет"; if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда"; else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка"; SetWindowTextW(priority_button, priority); if (scenario && production_label != nullptr) { const auto progress = world->scenario_progress(); const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(), [](const auto& agent) { return agent.state == settlement::AgentState::Sleeping; }); const std::wstring goal = (progress.completed ? std::wstring(L"Цель выполнена ") : std::wstring{}) + L"Спальные места " + std::to_wstring(progress.assigned_beds) + L"/" + std::to_wstring(progress.residents) + L" Еда " + std::to_wstring(progress.available_food) + L"/" + std::to_wstring(progress.food_goal) + L" Ткань " + std::to_wstring(cloth) + L" Лён " + std::to_wstring(flax) + L" Спят " + std::to_wstring(sleeping); SetWindowTextW(production_label, goal.c_str()); return; } if (production_label != nullptr) { unsigned waiting = 0; unsigned carrying = 0; unsigned building = 0; unsigned built = 0; for (const auto& order : world->production_orders()) { if (order.recipe != settlement::RecipeId::BuildCabin) continue; if (order.state == settlement::JobState::Available) ++waiting; else if (order.state == settlement::JobState::Completed) ++built; else if (order.delivery_stops.empty()) ++building; else ++carrying; } const auto hungry = std::count_if(world->agents().begin(), world->agents().end(), [](const settlement::Agent& agent) { return agent.hungry(); }); const std::wstring production = L"Ягоды: " + std::to_wstring(berries) + L" Голодны: " + std::to_wstring(hungry) + L" Доски: " + std::to_wstring(planks) + L" Блоки: " + std::to_wstring(blocks) + L" Лён: " + std::to_wstring(flax) + L" Ткань: " + std::to_wstring(cloth) + L" Домики В очереди: " + std::to_wstring(waiting) + L" Доставка: " + std::to_wstring(carrying) + L" Строятся: " + std::to_wstring(building) + L" Готовы: " + std::to_wstring(built); SetWindowTextW(production_label, production.c_str()); } } void update_bed_choices() { const int visibility = !showing_title && shows_bed_choices() ? SW_SHOWNA : SW_HIDE; ShowWindow(wood_bed_button, visibility); ShowWindow(stone_bed_button, visibility); InvalidateRect(wood_bed_button, nullptr, FALSE); InvalidateRect(stone_bed_button, nullptr, FALSE); } 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, has_blueprint() && can_give_orders() && !room_draft_move); EnableWindow(clear_blueprint_button, has_blueprint()); layout_command_dock(window); } void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { placement_mode = mode; selected_bed_base.reset(); move_source.reset(); room_anchor.reset(); room_draft_move.reset(); preferred_room_entrance.reset(); selected_room_template = settlement::RoomTemplate::Empty; hover_cell.reset(); placement_message = message; update_bed_choices(); update_blueprint_controls(window); invalidate_work_choices(); invalidate_scene(window); } void clear_blueprints() { blueprint.clear(); room_blueprints.clear(); room_anchor.reset(); room_draft_move.reset(); } void toggle_work_panel(HWND window, WorkPanel panel) { if (!can_give_orders()) return; set_placement_mode(window, PlacementMode::None); set_work_panel(window, work_panel == panel ? WorkPanel::None : panel); SetFocus(window); } bool can_resume_session() { return has_session && lan.state() != LanState::Connecting && lan.state() != LanState::GuestDisconnected; } void update_title_controls() { title_screen.update(can_resume_session(), lan.state() == LanState::Offline); } void show_title_screen(HWND window, bool visible) { showing_title = visible; if (visible) { if (roster.window) DestroyWindow(roster.window); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None); title_screen.reload_saves(); update_title_controls(); } else { has_session = true; enter_game_on_snapshot = false; if (!graphics.ready() && scene_window && !graphics.initialize(scene_window)) { graphics.initialize(scene_window, true); } } const int flags = visible ? SW_HIDE : SW_SHOWNA; for (const auto control : {status_label, production_label, priority_button, work_list_button, residents_button}) { ShowWindow(control, flags); } for (const auto control : dock_section_buttons) ShowWindow(control, flags); title_screen.show(visible); RECT client{}; GetClientRect(window, &client); title_screen.layout(client.right, client.bottom); update_blueprint_controls(window); SetFocus(window); InvalidateRect(window, nullptr, FALSE); } void reset_world(HWND window) { world = settlement::make_first_colony(local_worker_count); clear_blueprints(); camera = {}; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None); show_title_screen(window, false); update_status(); invalidate_scene(window); } std::optional choose_save_file(HWND window, bool saving) { wchar_t filename[32768]{}; constexpr std::wstring_view default_name = L"Поселение.settlement"; if (saving) std::copy(default_name.begin(), default_name.end(), filename); OPENFILENAMEW dialog{}; dialog.lStructSize = sizeof(dialog); dialog.hwndOwner = window; dialog.lpstrFilter = L"Сохранение поселения (*.settlement)\0*.settlement\0Все файлы\0*.*\0"; dialog.lpstrFile = filename; dialog.nMaxFile = static_cast(std::size(filename)); dialog.lpstrDefExt = L"settlement"; const auto folder = title::saves_directory(); if (!folder.empty()) { std::error_code error; if (saving) std::filesystem::create_directories(folder, error); if (std::filesystem::is_directory(folder, error)) dialog.lpstrInitialDir = folder.c_str(); } dialog.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | (saving ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST); const BOOL accepted = saving ? GetSaveFileNameW(&dialog) : GetOpenFileNameW(&dialog); if (accepted) return std::filesystem::path(filename); if (CommDlgExtendedError() != 0) throw std::runtime_error("Could not open the file picker."); return std::nullopt; } void save_world_file(const std::filesystem::path& path) { // Stage the complete file beside its destination before replacing an existing save. wchar_t temporary[MAX_PATH]{}; if (GetTempFileNameW(path.parent_path().c_str(), L"stl", 0, temporary) == 0) { throw std::runtime_error("Could not create a temporary save in this folder."); } try { std::ofstream stream(std::filesystem::path(temporary), std::ios::binary | std::ios::trunc); if (!stream) throw std::runtime_error("Could not open the temporary save for writing."); world->write_save(stream); stream.close(); if (!stream) throw std::runtime_error("Could not finish writing the temporary save."); if (!MoveFileExW(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { throw std::runtime_error("Could not move the completed save into place."); } } catch (...) { DeleteFileW(temporary); throw; } } void handle_save_menu(HWND window, bool saving, std::optional selected = std::nullopt) { if (file_dialog_active || (saving && !world)) return; if (lan.is_guest() || (!saving && lan.state() != LanState::Offline)) return; file_dialog_active = true; struct RestoreTimer { ~RestoreTimer() { file_dialog_active = false; } } restore_timer; try { const auto path = selected ? std::move(selected) : choose_save_file(window, saving); if (!path) return; if (saving) { save_world_file(*path); placement_message = L"Поселение сохранено."; invalidate_scene(window); return; } std::ifstream stream(*path, std::ios::binary); if (!stream) throw std::runtime_error("Could not open the requested save."); auto loaded = settlement::World::read_save(stream, local_worker_count); if (loaded->width() != map_size || loaded->height() != map_size) { throw std::runtime_error("This viewer opens saves with a 32 by 32 map."); } world = std::move(loaded); clear_blueprints(); camera = {}; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Поселение загружено."); show_title_screen(window, false); update_status(); } catch (const std::exception& error) { const std::string_view details(error.what()); const std::wstring message = std::wstring(saving ? L"Не удалось сохранить поселение.\n" : L"Не удалось загрузить поселение.\n") + std::wstring(details.begin(), details.end()); MessageBoxW(window, message.c_str(), L"Поселение", MB_OK | MB_ICONERROR); } } std::wstring widen_ascii(std::string_view text) { return {text.begin(), text.end()}; } struct JoinForm { std::array address{}; std::array code{}; }; INT_PTR CALLBACK join_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { constexpr int address_id = 10; constexpr int code_id = 11; switch (message) { case WM_INITDIALOG: { SetWindowLongPtrW(dialog, DWLP_USER, static_cast(lparam)); SetWindowTextW(dialog, L"Подключиться к поселению"); const auto control = [&](const wchar_t* type, const wchar_t* title, DWORD style, DWORD ex_style, int id, RECT units) { MapDialogRect(dialog, &units); const HWND child = CreateWindowExW(ex_style, type, title, WS_CHILD | WS_VISIBLE | style, units.left, units.top, units.right - units.left, units.bottom - units.top, dialog, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); return child; }; control(L"STATIC", L"IPv4 хозяина", 0, 0, 0, {10, 13, 77, 26}); const HWND address = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, address_id, {82, 10, 216, 25}); control(L"STATIC", L"Код партии", 0, 0, 0, {10, 38, 77, 51}); const HWND code = control(L"EDIT", L"", WS_TABSTOP | ES_AUTOHSCROLL, WS_EX_CLIENTEDGE, code_id, {82, 35, 216, 50}); SendMessageW(address, EM_SETLIMITTEXT, 63, 0); SendMessageW(code, EM_SETLIMITTEXT, 31, 0); control(L"BUTTON", L"Подключиться", WS_TABSTOP | BS_DEFPUSHBUTTON, 0, IDOK, {68, 62, 151, 79}); control(L"BUTTON", L"Отмена", WS_TABSTOP | BS_PUSHBUTTON, 0, IDCANCEL, {158, 62, 216, 79}); SendMessageW(dialog, DM_SETDEFID, IDOK, 0); SetFocus(address); return FALSE; } case WM_COMMAND: if (LOWORD(wparam) == IDOK) { auto* form = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER)); GetDlgItemTextW(dialog, address_id, form->address.data(), static_cast(form->address.size())); GetDlgItemTextW(dialog, code_id, form->code.data(), static_cast(form->code.size())); EndDialog(dialog, IDOK); return TRUE; } if (LOWORD(wparam) == IDCANCEL) { EndDialog(dialog, IDCANCEL); return TRUE; } break; case WM_CLOSE: EndDialog(dialog, IDCANCEL); return TRUE; } return FALSE; } std::optional ask_join_address(HWND window) { struct alignas(DWORD) EmptyDialog { DLGTEMPLATE header{}; WORD menu = 0; WORD window_class = 0; WORD title = 0; } layout; layout.header.style = WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_CENTER; layout.header.cx = 226; layout.header.cy = 91; JoinForm values; const auto result = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, join_dialog_proc, reinterpret_cast(&values)); if (result == -1) throw std::runtime_error("Could not display the connection window."); if (result != IDOK) return std::nullopt; return values; } std::string narrow_lan_input(std::wstring_view value) { const auto begin = value.find_first_not_of(L" \t"); if (begin == std::wstring_view::npos) return {}; value = value.substr(begin, value.find_last_not_of(L" \t") - begin + 1); std::string ascii; for (const auto letter : value) { if (letter > 127) throw std::invalid_argument("Use ASCII digits and letters for the address and code."); ascii.push_back(static_cast(letter)); } return ascii; } void show_lan_info(HWND window) { const auto addresses = settlement::viewer::local_lan_addresses(); const auto text = L"Передайте другу IPv4 вашего компьютера и код партии.\n\nIPv4: " + (addresses.empty() ? std::wstring(L"см. ipconfig") : widen_ascii(addresses)) + L"\nКод партии: " + widen_ascii(lan.join_code()) + L"\nПорт TCP: " + std::to_wstring(lan.port()) + L"\n\nДруг в той же сети выбирает «Кооператив → Подключиться к другу…» в главном меню."; MessageBoxW(window, text.c_str(), L"Кооператив по локальной сети", MB_OK | MB_ICONINFORMATION); } void refresh_lan_controls(HWND window) { const auto state = lan.state(); displayed_lan_state = state; const bool disconnected = state == LanState::GuestDisconnected; const wchar_t* suffix = L""; switch (state) { case LanState::Offline: break; case LanState::Hosting: suffix = L" · ждём гостя"; break; case LanState::HostConnected: suffix = L" · хозяин, гость подключён"; break; case LanState::Connecting: suffix = L" · подключение"; break; case LanState::GuestConnected: suffix = L" · гость"; break; case LanState::GuestDisconnected: suffix = L" · связь потеряна"; break; } const auto caption = std::wstring(showing_title ? L"Settlement" : L"Settlement — Первое поселение") + suffix; SetWindowTextW(window, caption.c_str()); if (disconnected) { set_placement_mode(window, PlacementMode::None); enter_game_on_snapshot = false; placement_message = showing_title ? L"Связь потеряна. Откройте «Кооператив», чтобы подключиться снова." : L"Связь прервана. Переподключение — в разделе «Кооператив» главного меню."; } else if (state == LanState::GuestConnected) { placement_message = L"Подключено к колонии хозяина."; } if (roster.window) update_roster_details(); update_status(); if (showing_title) { update_title_controls(); InvalidateRect(window, nullptr, FALSE); } invalidate_scene(window); } void handle_lan_menu(HWND window, int command) { if (!showing_title) return; try { if (command == lan_host_id && lan.state() == LanState::Offline) { auto colony = !has_session || !world || !world->scenario_active() ? settlement::make_first_colony(local_worker_count) : nullptr; lan.host(); if (colony) { world = std::move(colony); clear_blueprints(); camera = {}; selected_resident.reset(); } has_session = true; placement_message = L"Сетевая колония открыта. Нажмите «Продолжить», чтобы войти."; refresh_lan_controls(window); show_lan_info(window); return; } else if (command == lan_join_id && (lan.state() == LanState::Offline || lan.state() == LanState::GuestDisconnected)) { const auto request = ask_join_address(window); if (!request) return; if (!world) world = settlement::make_first_colony(local_worker_count); lan.join(narrow_lan_input(request->address.data()), narrow_lan_input(request->code.data())); clear_blueprints(); enter_game_on_snapshot = true; selected_resident.reset(); sync_resident_roster(true); set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Подключаемся к хозяину…"); } else if (command == lan_info_id && !lan.is_guest() && lan.state() != LanState::Offline) { show_lan_info(window); return; } else if (command == lan_reconnect_id && lan.state() == LanState::GuestDisconnected) { lan.reconnect(); enter_game_on_snapshot = true; placement_message = L"Подключаемся к хозяину…"; } else if (command == lan_leave_id) { lan.leave(); enter_game_on_snapshot = false; set_work_panel(window, WorkPanel::None); set_placement_mode(window, PlacementMode::None, L"Сетевая игра завершена."); } refresh_lan_controls(window); } catch (const std::exception& error) { const auto text = L"Не удалось выполнить действие.\n" + widen_ascii(error.what()); MessageBoxW(window, text.c_str(), L"Кооператив", MB_OK | MB_ICONERROR); } } void open_coop_menu(HWND window); void handle_title_command(HWND window, int command, int notification) { if (command == title::title_exit_id && notification == BN_CLICKED) { DestroyWindow(window); return; } if (command == title::title_coop_id && notification == BN_CLICKED) { open_coop_menu(window); return; } const bool offline = lan.state() == LanState::Offline; if (command == title::title_continue_id && notification == BN_CLICKED && can_resume_session()) { show_title_screen(window, false); refresh_lan_controls(window); return; } if (!offline) return; if (command == title::title_saves_id && notification == LBN_SELCHANGE) { update_title_controls(); return; } const bool open_selected = (command == title::title_open_id && notification == BN_CLICKED) || (command == title::title_saves_id && notification == LBN_DBLCLK); if (!open_selected && (notification != BN_CLICKED || (command != title::title_new_id && command != title::title_continue_id && command != title::title_browse_id))) { return; } if (open_selected) { if (const auto path = title_screen.selected_save()) handle_save_menu(window, false, path); } else if (command == title::title_new_id) { reset_world(window); } else if (command == title::title_browse_id) { handle_save_menu(window, false); } else if (const auto path = title_screen.latest_save()) { handle_save_menu(window, false, path); } refresh_lan_controls(window); } const settlement::ResourceNode* berry_source(settlement::GridPosition cell) { for (const auto& node : world->resource_nodes()) { if (node.position == cell && node.type == settlement::ItemType::Berries) return &node; } return nullptr; } settlement::CommandStatus submit_command(settlement::CommandKind kind, settlement::GridPosition cell, std::uint8_t value, settlement::GridPosition destination = {}, settlement::AgentId resident = 0) { if (lan.is_guest()) { return lan.submit(kind, cell, value, destination, resident) ? settlement::CommandStatus::Accepted : settlement::CommandStatus::Unavailable; } constexpr auto host = settlement::colony_host; return world->apply_command({host, world->next_command_sequence(host), kind, cell, value, destination, resident}).status; } bool send_command(settlement::CommandKind kind, settlement::GridPosition cell = {}, std::uint8_t value = 0) { return submit_command(kind, cell, value) == settlement::CommandStatus::Accepted; } bool valid_edit_cell(settlement::GridPosition cell) { using settlement::CommandStatus; using settlement::ResourceSite; switch (placement_mode) { case PlacementMode::Foraging: return berry_source(cell) != nullptr; case PlacementMode::BerryField: return world->can_place_site(cell, ResourceSite::BerryField); case PlacementMode::FlaxField: return world->can_place_site(cell, ResourceSite::FlaxField); case PlacementMode::TreePlot: return world->can_place_site(cell, ResourceSite::TreePlot); case PlacementMode::Mine: return world->can_place_site(cell, ResourceSite::Mine); case PlacementMode::Storage: case PlacementMode::Loom: case PlacementMode::Pantry: return world->can_place_storage(cell); case PlacementMode::Move: return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted; 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; } bool has_carpenter() { return std::any_of(world->agents().begin(), world->agents().end(), [](const auto& agent) { return agent.profession == Profession::Carpenter; }); } 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, const settlement::RoomPlan* ignored = nullptr) { 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 &other != ignored && 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) { if (room_draft_move) { auto room = room_blueprints[room_draft_move->index]; const int x = cell.x - room_draft_move->grabbed_cell.x; const int y = cell.y - room_draft_move->grabbed_cell.y; room.first = {room.first.x + x, room.first.y + y}; room.last = {room.last.x + x, room.last.y + y}; room.entrance = room_draft_move->entrance; return room; } constexpr int edge = settlement::furnished_room_size - 1; auto room = room_anchor ? settlement::make_room_plan(*room_anchor, cell) : settlement::RoomPlan{cell, {cell.x + edge, cell.y + edge}}; room.layout = selected_room_template; if (preferred_room_entrance) { room.entrance = *preferred_room_entrance; return room; } 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 rotate_room_preview(HWND window, int direction) { using settlement::RoomSide; const auto next = [direction](RoomSide side) { return static_cast((static_cast(side) + direction + 4) % 4); }; if (room_draft_move) { room_draft_move->entrance = next(room_draft_move->entrance); } else { const auto side = hover_cell ? preview_room(*hover_cell).entrance : preferred_room_entrance.value_or(RoomSide::South); preferred_room_entrance = next(side); } placement_message.clear(); invalidate_scene(window); } void edit_room_blueprint(HWND window, settlement::GridPosition cell, bool shift) { if (!can_give_orders()) return; using settlement::RoomSide; if (room_draft_move) { auto& original = room_blueprints[room_draft_move->index]; const auto room = preview_room(cell); if (world->can_place_room(room) && room_fits_blueprint(room, &original)) { original = room; room_draft_move.reset(); placement_message.clear(); } else { placement_message = L"Здесь дом не помещается. Выберите другую площадку или отмените перенос."; } } else 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 draft = room_at(cell); draft != room_blueprints.end()) { if (shift) { room_draft_move = RoomDraftMove{static_cast(draft - room_blueprints.begin()), cell, draft->entrance}; hover_cell = cell; placement_message.clear(); update_blueprint_controls(window); invalidate_scene(window); return; } auto candidate = *draft; if (cell.y == draft->first.y) candidate.entrance = RoomSide::North; else if (cell.y == draft->last.y) candidate.entrance = RoomSide::South; else if (cell.x == draft->first.x) candidate.entrance = RoomSide::West; else if (cell.x == draft->last.x) candidate.entrance = RoomSide::East; else { placement_message = L"Щёлкните по краю комнаты, чтобы перенести вход."; invalidate_scene(window); return; } if (world->can_place_room(candidate)) { *draft = candidate; placement_message.clear(); } else { placement_message = L"С этой стороны нет свободного прохода."; } } else if (selected_room_template != settlement::RoomTemplate::Empty) { const auto room = preview_room(cell); if (world->can_place_room(room) && room_fits_blueprint(room)) { room_blueprints.push_back(room); placement_message.clear(); } else { placement_message = L"Для дома нужна свободная площадка 4×4 и проход снаружи."; } } 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) { return settlement::viewer::BlueprintPart{cell, RecipeId::WeaveCloth}; } if (placement_mode != PlacementMode::Building || (shows_bed_choices() && !selected_bed_base)) { return std::nullopt; } return settlement::viewer::BlueprintPart{cell, world->scenario_active() ? RecipeId::BuildBed : RecipeId::BuildCabin, selected_bed_base.value_or(settlement::BedBase::Wood)}; } 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) && room_at(cell) == room_blueprints.end()) { blueprint.push_back(*part); placement_message.clear(); } else { placement_message = shows_bed_choices() && !selected_bed_base ? L"Выберите основу под кнопкой «Спальное место»." : L"Эта клетка занята или недоступна для чертежа."; } update_blueprint_controls(window); invalidate_scene(window); } void submit_blueprint(HWND window) { if (!world || !has_blueprint() || room_draft_move || !can_give_orders()) return; using settlement::CommandKind; using settlement::RecipeId; const auto rooms_sent = std::erase_if(room_blueprints, [](const auto& room) { return world->can_place_room(room) && submit_command(CommandKind::PlaceRoom, room.first, room.placement_value(), room.last) == settlement::CommandStatus::Accepted; }); const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { switch (part.recipe) { case RecipeId::BuildBed: return world->can_place_bed(part.cell) && send_command(CommandKind::PlaceBed, part.cell, static_cast(part.base)); case RecipeId::WeaveCloth: return world->can_place_storage(part.cell) && send_command(CommandKind::PlaceLoom, part.cell); case RecipeId::BuildCabin: try { world->queue_cabin(part.cell, sawmill, stonecutter); return true; } catch (const std::invalid_argument&) { return false; } default: return false; } }); const std::wstring count = std::to_wstring(rooms_sent + objects_sent); if (has_blueprint()) { placement_message = L"Принято мест: " + count + L". Осталось в чертеже: " + std::to_wstring(blueprint.size() + room_blueprints.size()) + (lan.is_guest() ? L". Проверьте карту и отправьте оставшиеся места снова." : L". Проверьте, свободны ли клетки и есть ли к ним проход."); } else { placement_message = (lan.is_guest() ? L"Передано хозяину мест: " : L"Утверждено мест: ") + count + L"."; } if (rooms_sent != 0 && world->scenario_active() && !has_carpenter()) { placement_message += L" Деревянные двери изготавливает плотник. Его можно назначить в списке «Жители»."; } update_blueprint_controls(window); update_status(); invalidate_scene(window); } void edit_at_cell(HWND window, settlement::GridPosition cell) { using settlement::CommandKind; using settlement::CommandStatus; using settlement::StorageKind; CommandKind command = CommandKind::DemolishObject; auto source = cell; settlement::GridPosition destination{}; std::uint8_t value = 0; if (placement_mode == PlacementMode::Move) { if (!move_source) { const auto status = world->object_status(cell, true); if (status == CommandStatus::Accepted) { move_source = cell; placement_message = L"Объект выбран. Щёлкните по свободной клетке для переноса."; } else if (status == CommandStatus::Busy) { placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; } else { placement_message = L"Выберите кровать, склад, станок или посаженный участок."; } invalidate_scene(window); return; } command = CommandKind::MoveObject; source = *move_source; destination = cell; } else if (placement_mode == PlacementMode::Demolish) { const auto store = std::find_if(world->storages().begin(), world->storages().end(), [&](const auto& storage) { return storage.position == cell; }); if (store != world->storages().end() && store->total_items() > 0 && world->object_status(cell, false) == CommandStatus::Accepted && MessageBoxW(window, L"Снести склад вместе с его запасами?", L"Снос склада", MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) != IDYES) return; } else if (placement_mode == PlacementMode::BerryField) { command = CommandKind::PlaceBerryField; } else if (placement_mode == PlacementMode::FlaxField) { command = CommandKind::PlaceFlaxField; } else if (placement_mode == PlacementMode::TreePlot) { command = CommandKind::PlaceTreePlot; } else if (placement_mode == PlacementMode::Mine) { command = CommandKind::PlaceMine; } else { command = CommandKind::PlaceStorage; value = static_cast(placement_mode == PlacementMode::Pantry ? StorageKind::Pantry : StorageKind::Materials); } const auto result = submit_command(command, source, value, destination); if (result == CommandStatus::Accepted) { move_source.reset(); placement_message = lan.is_guest() ? L"Команда отправлена хозяину." : L"Готово."; } else if (result == CommandStatus::Busy) { placement_message = L"Объект сейчас используется. Дождитесь завершения работы или сна."; } else { if (command == CommandKind::MoveObject && world->object_status(source, true) != CommandStatus::Accepted) { move_source.reset(); } placement_message = L"Действие недоступно для выбранной клетки."; } update_status(); invalidate_scene(window); } HMENU create_work_menu() { HMENU menu = CreatePopupMenu(); if (menu == nullptr) return nullptr; for (int id = farmer_menu_id; id <= builder_menu_id; ++id) { AppendMenuW(menu, MF_STRING, static_cast(id), role_choices[static_cast(id - farmer_menu_id + 1)].title); } AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник"); AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC"); return menu; } void apply_resident_role(HWND owner) { const auto* resident = selected_agent(); if (!resident || !roster.pending_role || *roster.pending_role == resident->profession || !can_give_orders()) return; using settlement::CommandStatus; const auto result = submit_command(settlement::CommandKind::AssignProfession, {}, static_cast(*roster.pending_role), {}, resident->id); if (result == CommandStatus::Accepted) { roster.pending_role.reset(); SetWindowTextW(roster.notice, lan.is_guest() ? L"Назначение отправлено хозяину." : L"Профессия назначена. Житель закончит текущее поручение."); } else { SetWindowTextW(roster.notice, L"Не удалось назначить профессию."); } sync_resident_roster(); update_roster_details(); invalidate_scene(owner); } LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { const auto owner = GetWindow(window, GW_OWNER); switch (message) { case WM_CREATE: { const auto control = [&](const wchar_t* type, const wchar_t* text, int id, DWORD style, int x, int y, int width, int height, DWORD ex_style = 0) { const auto child = CreateWindowExW(ex_style, type, text, WS_CHILD | WS_VISIBLE | style, x, y, width, height, window, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), FALSE); return child; }; roster.list = control(WC_LISTVIEWW, L"", resident_list_id, WS_TABSTOP | LVS_REPORT | LVS_OWNERDATA | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 16, 16, 282, 345, WS_EX_CLIENTEDGE); ListView_SetExtendedListViewStyle(roster.list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER); wchar_t resident_header[] = L"Житель"; wchar_t profession_header[] = L"Профессия"; LVCOLUMNW column{}; column.mask = LVCF_TEXT | LVCF_WIDTH; column.cx = 102; column.pszText = resident_header; ListView_InsertColumn(roster.list, 0, &column); column.cx = 156; column.pszText = profession_header; ListView_InsertColumn(roster.list, 1, &column); roster.current_role = control(L"STATIC", L"", 0, SS_LEFT, 316, 16, 234, 22); for (std::size_t index = 0; index < role_choices.size(); ++index) { const auto title = std::wstring(role_choices[index].title) + L" (0)"; roster.roles[index] = control(L"BUTTON", title.c_str(), first_role_id + static_cast(index), WS_TABSTOP | BS_OWNERDRAW, 316, 43 + static_cast(index) * 34, 234, 30); } roster.apply = control(L"BUTTON", L"Назначить профессию", IDOK, WS_TABSTOP | BS_DEFPUSHBUTTON, 316, 252, 234, 30); roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 290, 234, 44); const auto close = control(L"BUTTON", L"Закрыть", IDCANCEL, WS_TABSTOP | BS_PUSHBUTTON, 447, 335, 103, 26); if (!roster.list || !roster.current_role || !roster.apply || !roster.notice || !close || std::find(roster.roles.begin(), roster.roles.end(), nullptr) != roster.roles.end()) return -1; return 0; } case WM_NOTIFY: { const auto* notification = reinterpret_cast(lparam); if (!notification || notification->hwndFrom != roster.list) break; if (notification->code == LVN_GETDISPINFOW) { auto& item = reinterpret_cast(lparam)->item; if ((item.mask & LVIF_TEXT) != 0 && item.pszText && item.cchTextMax > 0 && item.iItem >= 0 && static_cast(item.iItem) < roster.rows.size()) { const auto& row = roster.rows[static_cast(item.iItem)]; const auto name = item.iSubItem == 0 ? L"Житель №" + std::to_wstring(row.id) : std::wstring(profession_name(row.role)); lstrcpynW(item.pszText, name.c_str(), item.cchTextMax); } return 0; } if (notification->code == LVN_ITEMCHANGED && !roster.updating_selection) { const auto& change = *reinterpret_cast(lparam); if ((change.uChanged & LVIF_STATE) != 0 && ((change.uOldState ^ change.uNewState) & LVIS_SELECTED) != 0) { const int index = ListView_GetNextItem(roster.list, -1, LVNI_SELECTED); std::optional resident; if (index >= 0 && static_cast(index) < roster.rows.size()) { resident = roster.rows[static_cast(index)].id; } if (selected_resident != resident) { selected_resident = resident; sync_resident_roster(true); invalidate_scene(owner); } } } break; } case WM_DRAWITEM: { const auto* item = reinterpret_cast(lparam); if (item && item->CtlType == ODT_BUTTON && item->CtlID >= first_role_id && item->CtlID < first_role_id + role_choices.size()) { const auto& choice = role_choices[item->CtlID - first_role_id]; const auto* resident = selected_agent(); const bool active = resident && roster.pending_role.value_or(resident->profession) == choice.role; draw_icon_button(*item, choice.icon, active); return TRUE; } break; } case WM_COMMAND: if (HIWORD(wparam) != BN_CLICKED) break; if (LOWORD(wparam) == IDCANCEL) { DestroyWindow(window); return 0; } if (LOWORD(wparam) == IDOK) { apply_resident_role(owner); return 0; } if (LOWORD(wparam) >= first_role_id && LOWORD(wparam) < first_role_id + role_choices.size() && selected_agent() && can_give_orders()) { roster.pending_role = role_choices[LOWORD(wparam) - first_role_id].role; SetWindowTextW(roster.notice, L""); update_roster_details(); return 0; } break; case DM_GETDEFID: return MAKELONG(IDOK, DC_HASDEFID); case WM_DESTROY: roster = {}; InvalidateRect(residents_button, nullptr, FALSE); return 0; } return DefWindowProcW(window, message, wparam, lparam); } void show_resident_roster(HWND owner) { if (roster.window) { SetActiveWindow(roster.window); return; } const auto instance = GetModuleHandleW(nullptr); WNDCLASSW window_info{}; window_info.lpfnWndProc = resident_roster_proc; window_info.hInstance = instance; window_info.lpszClassName = resident_window_class; window_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); window_info.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); if (!RegisterClassW(&window_info) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return; constexpr auto style = WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN; constexpr auto ex_style = WS_EX_TOOLWINDOW | WS_EX_CONTROLPARENT; RECT area{0, 0, 566, 377}; AdjustWindowRectEx(&area, style, FALSE, ex_style); RECT owner_rect{}; GetWindowRect(owner, &owner_rect); const int width = area.right - area.left; const int height = area.bottom - area.top; const int x = (owner_rect.left + owner_rect.right - width) / 2; const int y = (owner_rect.top + owner_rect.bottom - height) / 2; roster.window = CreateWindowExW(ex_style, resident_window_class, L"Жители поселения", style, x, y, width, height, owner, nullptr, instance, nullptr); if (!roster.window) return; if (!selected_agent() && !world->agents().empty()) selected_resident = world->agents().front().id; sync_resident_roster(true); InvalidateRect(residents_button, nullptr, FALSE); invalidate_scene(owner); ShowWindow(roster.window, SW_SHOW); SetFocus(roster.list); } std::optional resident_at(HWND window, POINT point) { RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) return std::nullopt; const auto scene = camera.to_scene({static_cast(point.x), static_cast(point.y)}); std::optional picked; double closest = 65.0; for (const auto& agent : world->agents()) { const auto position = resident_anchor( map_projection(agent.position.x, agent.position.y, client.right / 2, map_origin_y), agent); const double dx = scene.x - position.x; const double dy = scene.y - (position.y + 2); if (std::abs(dx) > 8 || std::abs(dy) > 8) continue; const double distance = dx * dx + dy * dy; if (distance <= closest) { closest = distance; picked = agent.id; } } return picked; } std::wstring resident_details() { const auto* resident = selected_agent(); if (resident == nullptr) return L"Щёлкните по жителю, чтобы увидеть его состояние и назначить профессию."; using settlement::ItemType; constexpr std::pair items[] = { {ItemType::Wood, L"древесина"}, {ItemType::Stone, L"камень"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"блоки"}, {ItemType::Berries, L"ягоды"}, {ItemType::Cloth, L"ткань"}, {ItemType::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"}, {ItemType::MedicineCabinet, L"аптечный шкаф"}, {ItemType::MiningRack, L"стойка шахтёра"}, {ItemType::Loom, L"ткацкий станок"} }; std::wstring cargo; for (const auto& [type, name] : items) { const auto count = resident->inventory.item_count(type); if (count == 0) continue; if (!cargo.empty()) cargo += L", "; cargo += std::wstring(name) + L" ×" + std::to_wstring(count); } const auto hunger = 100U * resident->hunger / settlement::max_hunger; std::wstring text = L"Житель №" + std::to_wstring(resident->id) + L" " + profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%"; if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой"; else if (resident->state == settlement::AgentState::Eating) text += L" Ест"; else if (resident->production_index != settlement::no_entity_index && settlement::is_carpentry_recipe(world->production_orders()[resident->production_index].recipe)) { text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" : L" Везёт материалы в мастерскую"; } else if (resident->resource_node_index != settlement::no_entity_index && resident->storage_index == settlement::no_entity_index) { const auto& site = world->resource_nodes()[resident->resource_node_index]; const bool trees = site.site == settlement::ResourceSite::TreePlot; if (resident->state == settlement::AgentState::Travelling) { text += trees ? L" Идёт на посадку деревьев" : L" Идёт засевать поле"; } else { text += trees ? L" Сажает деревья" : L" Засевает поле"; } } text += L" В сумке "; text += cargo.empty() ? L"пусто" : cargo; if (world->scenario_active()) { const auto* bed = world->assigned_bed(resident->id); const auto fatigue = 100U * resident->fatigue / settlement::max_fatigue; text += L" Усталость " + std::to_wstring(fatigue) + L"%"; if (resident->state == settlement::AgentState::GoingToSleep) { text += resident->resting_on_ground ? L" Идёт отдыхать" : L" Идёт к кровати"; } if (resident->state == settlement::AgentState::Sleeping) { text += resident->resting_on_ground ? L" Отдыхает на земле" : L" Спит в кровати"; } text += bed == nullptr ? L" Место ещё не назначено" : L" Место [" + std::to_wstring(bed->position.x + 1) + L", " + std::to_wstring(bed->position.y + 1) + L"]"; } return text; } std::wstring blueprint_details() { using settlement::ItemType; struct Material { ItemType type; const wchar_t* name; }; constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}, {ItemType::WoodenDoor, L"готовые двери"}, {ItemType::MedicineCabinet, L"аптечные шкафы"}, {ItemType::MiningRack, L"стойки шахтёра"}, {ItemType::Loom, L"ткацкие станки"}}; std::array totals{}; for (const auto& part : blueprint) { using settlement::RecipeId; const auto recipe = part.recipe == RecipeId::WeaveCloth && world->scenario_active() ? world->room_construction_recipe(RecipeId::BuildLoom) : part.recipe; for (const auto& material : world->construction_materials(recipe, part.base)) { totals[static_cast(material.type)] += material.count; } } 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 recipe = world->room_construction_recipe(room.recipe_at({x, y})); const auto ingredients = world->construction_materials(recipe, settlement::BedBase::Wood); for (const auto& item : ingredients) totals[static_cast(item.type)] += item.count; } } if (const auto furnishings = room.furnishings()) { for (const auto& part : *furnishings) { const auto recipe = world->room_construction_recipe(part.recipe); for (const auto& item : world->construction_materials(recipe, part.bed_base)) { 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); } return text; } void draw_world(HDC dc, int width, int height) { RECT bounds{0, 0, width, height}; HBRUSH background = CreateSolidBrush(color(239, 235, 222)); FillRect(dc, &bounds, background); DeleteObject(background); if (!world) return; if (!graphics.ready() && height > map_top + dock_layout.height) { RECT scene{16, map_top + 24, width - 16, height - dock_layout.height}; SetBkMode(dc, TRANSPARENT); SetTextColor(dc, color(55, 68, 59)); DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.", -1, &scene, DT_CENTER | DT_WORDBREAK); } const RECT dock{0, height - dock_layout.height, width, height}; const auto dock_brush = CreateSolidBrush(color(34, 46, 40)); FillRect(dc, &dock, dock_brush); DeleteObject(dock_brush); const RECT dock_edge{0, dock.top, width, dock.top + 2}; const auto edge_brush = CreateSolidBrush(color(142, 132, 92)); FillRect(dc, &dock_edge, edge_brush); DeleteObject(edge_brush); SetBkMode(dc, TRANSPARENT); SetTextColor(dc, color(231, 227, 205)); const wchar_t* hint = world->scenario_active() ? L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" : L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство"; if (!placement_message.empty()) hint = placement_message.c_str(); else if (placement_mode == PlacementMode::Foraging) { hint = L"Щёлкните по ягодному кусту, чтобы включить или выключить сбор. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::BerryField) { hint = L"Поле ягод. Выберите свободную клетку. Фермер засеет поле и соберёт урожай."; } else if (placement_mode == PlacementMode::FlaxField) { hint = L"Поле льна. Выберите свободную клетку. Фермер сначала засеет поле, затем соберёт лён."; } else if (placement_mode == PlacementMode::TreePlot) { hint = L"Посадка деревьев. Выберите свободную клетку. Лесоруб высадит деревья."; } else if (placement_mode == PlacementMode::Mine) { hint = L"Шахта. Щёлкните по скале, к которой ведёт свободный проход."; } else if (placement_mode == PlacementMode::Storage || placement_mode == PlacementMode::Pantry) { hint = L"Выберите свободную клетку для склада или кладовой."; } else if (placement_mode == PlacementMode::Move) { hint = move_source ? L"Выберите свободную клетку для переноса." : L"Выберите кровать, склад, станок или посаженный участок."; } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::Room) { if (room_draft_move) { hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос."; } else if (selected_room_template != settlement::RoomTemplate::Empty) { hint = L"Выберите площадку 4×4. R поворачивает дом, Shift + щелчок переносит чертёж."; } else { hint = room_anchor ? L"Укажите противоположный угол комнаты. R меняет сторону входа." : L"Укажите первый угол. Щелчок по краю меняет вход, Shift + щелчок переносит чертёж."; } } else if (is_blueprint_tool()) { hint = shows_bed_choices() && !selected_bed_base ? L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»." : L"Щёлкните по клетке, чтобы добавить объект или убрать его из чертежа."; } else if (work_panel == WorkPanel::Houses) { hint = L"Выберите проект дома для площадки 4×4."; } else if (work_panel == WorkPanel::Carpenter) { hint = L"Дверь и станок требуют по 2 дерева, шкаф — 1 дерево, стойка — по 1 дереву и камню."; } const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr; 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); auto details = has_blueprint() ? blueprint_details() : selected_room_template != settlement::RoomTemplate::Empty ? std::wstring(house_contents[static_cast(selected_room_template) - 1]) : resident_details(); if (work_panel == WorkPanel::Carpenter) { const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(), [](const auto& order) { return settlement::is_carpentry_recipe(order.recipe) && order.state != settlement::JobState::Completed; }); using settlement::ItemType; const auto stock = [](ItemType item) { std::uint64_t count = 0; for (const auto& storage : world->storages()) count += storage.available_item_count(item); return std::to_wstring(count); }; details = L"Заказы " + std::to_wstring(orders) + L" Двери " + stock(ItemType::WoodenDoor) + L" Шкафы " + stock(ItemType::MedicineCabinet) + L" Стойки " + stock(ItemType::MiningRack) + L" Станки " + stock(ItemType::Loom); if (!has_carpenter()) { details += L" Назначьте плотника в списке «Жители»."; } } 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); if (previous_font) SelectObject(dc, previous_font); } 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; std::optional room_preview; if (cursor && placement_mode == PlacementMode::Room && (room_draft_move || room_anchor || (selected_room_template != settlement::RoomTemplate::Empty && room_at(*cursor) == room_blueprints.end()))) { const auto room = preview_room(*cursor); if (room.valid_size()) room_preview = room; } const auto ignore = room_draft_move ? &room_blueprints[room_draft_move->index] : nullptr; const bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview, ignore) : 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, room_blueprints, room_preview, building_view, room_draft_move ? std::optional(room_draft_move->index) : std::nullopt}; } LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_NCHITTEST) return HTTRANSPARENT; if (message == WM_ERASEBKGND) return 1; if (message == WM_PAINT) { PAINTSTRUCT paint{}; BeginPaint(window, &paint); RECT client{}; GetClientRect(window, &client); const bool drawn = !world || !graphics.ready() || client.right <= 0 || client.bottom <= 0 || graphics.render(*world, scene_view(client.right, client.bottom)); EndPaint(window, &paint); if (!drawn) { graphics.reset(); const auto parent = GetParent(window); layout_scene(parent); invalidate_scene(parent); } return 0; } return DefWindowProcW(window, message, wparam, lparam); } struct MenuAction { int id; const wchar_t* caption; bool enabled = true; }; struct MenuDialog { const wchar_t* title; std::span actions; HBRUSH background; }; INT_PTR CALLBACK menu_dialog_proc(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_INITDIALOG: { const auto& menu = *reinterpret_cast(lparam); SetWindowLongPtrW(dialog, DWLP_USER, lparam); SetWindowTextW(dialog, menu.title); HWND first_enabled = nullptr; int y = 9; for (const auto& action : menu.actions) { RECT bounds{12, y, 218, y + 20}; MapDialogRect(dialog, &bounds); const auto child = CreateWindowExW(0, L"BUTTON", action.caption, WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_OWNERDRAW, bounds.left, bounds.top, bounds.right - bounds.left, bounds.bottom - bounds.top, dialog, reinterpret_cast(static_cast(action.id)), GetModuleHandleW(nullptr), nullptr); SendMessageW(child, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); EnableWindow(child, action.enabled); if (!first_enabled && action.enabled) first_enabled = child; y += 25; } SetFocus(first_enabled); return FALSE; } case WM_CTLCOLORDLG: if (const auto* menu = reinterpret_cast(GetWindowLongPtrW(dialog, DWLP_USER))) { return reinterpret_cast(menu->background); } break; case WM_DRAWITEM: if (const auto* item = reinterpret_cast(lparam); item && item->CtlType == ODT_BUTTON) { const bool storage = item->CtlID == save_menu_id || item->CtlID == load_menu_id; draw_icon_button(*item, storage ? WorkIcon::Crate : WorkIcon::Resident, item->CtlID == IDOK, true); return TRUE; } break; case WM_COMMAND: if (HIWORD(wparam) == BN_CLICKED) { EndDialog(dialog, LOWORD(wparam)); return TRUE; } break; case WM_CLOSE: EndDialog(dialog, IDCANCEL); return TRUE; } return FALSE; } int choose_menu_action(HWND window, const wchar_t* title, std::span actions) { 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 = 230; layout.header.cy = static_cast(13 + 25 * actions.size()); MenuDialog menu{title, actions, CreateSolidBrush(color(34, 46, 40))}; const auto action = DialogBoxIndirectParamW(GetModuleHandleW(nullptr), &layout.header, window, menu_dialog_proc, reinterpret_cast(&menu)); DeleteObject(menu.background); return static_cast(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) { 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); } } void open_pause_menu(HWND window) { if (!world || showing_title || pause_menu_open) return; camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); const bool offline = lan.state() == LanState::Offline; const auto interface_caption = L"Масштаб панели · " + std::to_wstring(interface_scale) + L"%…"; const MenuAction actions[] = { {IDOK, L"Продолжить"}, {save_menu_id, L"Сохранить поселение…", !lan.is_guest()}, {load_menu_id, L"Загрузить поселение…", offline}, {interface_scale_id, interface_caption.c_str()}, {title_menu_id, L"Главное меню"}, {exit_menu_id, L"Выйти из игры"}, }; pause_menu_open = true; const auto action = choose_menu_action(window, offline ? L"Меню паузы" : L"Меню игры", actions); switch (action) { case IDOK: if (offline && world->paused()) { static_cast(send_command(settlement::CommandKind::SetPaused)); } break; case save_menu_id: case load_menu_id: handle_save_menu(window, action == save_menu_id); break; case interface_scale_id: choose_interface_scale(window); break; case title_menu_id: show_title_screen(window, true); refresh_lan_controls(window); break; case exit_menu_id: DestroyWindow(window); break; } pause_menu_open = false; if (IsWindow(window)) SetFocus(window); } void open_coop_menu(HWND window) { std::vector actions; switch (lan.state()) { case LanState::Offline: actions.push_back({lan_host_id, has_session && world && world->scenario_active() ? L"Открыть текущую колонию для друга…" : L"Создать сетевую колонию…"}); actions.push_back({lan_join_id, L"Подключиться к другу…"}); break; case LanState::Hosting: case LanState::HostConnected: actions.push_back({lan_info_id, L"Адрес и код партии…"}); actions.push_back({pause_button_id, world->paused() ? L"Продолжить для всех" : L"Пауза для всех"}); actions.push_back({lan_leave_id, L"Закрыть сетевую игру"}); break; case LanState::Connecting: actions.push_back({lan_leave_id, L"Отменить подключение"}); break; case LanState::GuestDisconnected: actions.push_back({lan_reconnect_id, L"Подключиться снова"}); actions.push_back({lan_join_id, L"Подключиться к другу…"}); [[fallthrough]]; case LanState::GuestConnected: actions.push_back({lan_leave_id, L"Выйти из сетевой игры"}); break; } actions.push_back({IDCANCEL, L"Назад"}); coop_menu_open = true; const auto action = choose_menu_action(window, L"Кооператив", actions); coop_menu_open = false; if (action == pause_button_id && (lan.state() == LanState::Hosting || lan.state() == LanState::HostConnected)) { static_cast(send_command(settlement::CommandKind::SetPaused, {}, static_cast(!world->paused()))); placement_message = world->paused() ? L"Сетевая колония на паузе." : L"Сетевая колония продолжает работу."; InvalidateRect(window, nullptr, FALSE); } else if (action >= lan_host_id && action <= lan_leave_id) { handle_lan_menu(window, action); } } LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_GETMINMAXINFO: { auto& size = *reinterpret_cast(lparam); size.ptMinTrackSize.x = 775; size.ptMinTrackSize.y = 640; return 0; } case WM_CREATE: { const auto instance = GetModuleHandleW(nullptr); WNDCLASSW viewport{}; viewport.lpfnWndProc = scene_window_proc; viewport.hInstance = instance; viewport.lpszClassName = scene_window_class; viewport.hCursor = LoadCursorW(nullptr, IDC_ARROW); if (RegisterClassW(&viewport) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) { scene_window = CreateWindowExW(0, scene_window_class, L"", WS_CHILD, 0, map_top, 1, 1, window, nullptr, instance, nullptr); } status_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, 18, 14, 735, 24, window, reinterpret_cast(static_cast(status_label_id)), GetModuleHandleW(nullptr), nullptr); production_label = CreateWindowExW(0, L"STATIC", L"", WS_CHILD | WS_VISIBLE, 288, 47, 817, 24, window, nullptr, nullptr, nullptr); const auto button = [&](int id, int x, int width, const wchar_t* title, DWORD style = BS_PUSHBUTTON, int y = 41, int height = 28) { return CreateWindowExW(0, L"BUTTON", title, WS_CHILD | WS_VISIBLE | style, x, y, width, height, window, reinterpret_cast(static_cast(id)), GetModuleHandleW(nullptr), nullptr); }; priority_button = button(priority_button_id, 0, 142, L"Равный приоритет", BS_OWNERDRAW, 0); work_list_button = button(work_list_button_id, 0, 108, L"Работы", BS_OWNERDRAW, 0); residents_button = button(residents_button_id, 0, 112, L"Жители", BS_OWNERDRAW, 0); for (std::size_t index = 0; index < dock_sections.size(); ++index) { dock_section_buttons[index] = button(first_dock_section_id + static_cast(index), 0, 112, dock_sections[index].title, BS_OWNERDRAW, 0); } wood_bed_button = button(wood_bed_button_id, 0, 90, L"Дерево", BS_OWNERDRAW, 0); stone_bed_button = button(stone_bed_button_id, 0, 90, L"Камень", BS_OWNERDRAW, 0); build_blueprint_button = button(build_blueprint_id, 0, 180, L"Начать стройку", BS_OWNERDRAW, 0); clear_blueprint_button = button(clear_blueprint_id, 0, 180, L"Очистить чертёж", BS_OWNERDRAW, 0); building_view_button = button(building_view_id, 0, 184, building_view_labels[0], BS_OWNERDRAW); constexpr int icons[] = {IDI_DOCTOR_HOUSE, IDI_MINER_HOUSE, IDI_WEAVER_HOUSE}; for (std::size_t index = 0; index < house_artwork.size(); ++index) { house_artwork[index] = reinterpret_cast(LoadImageW(instance, MAKEINTRESOURCEW(icons[index]), IMAGE_ICON, 0, 0, LR_SHARED)); } for (std::size_t index = 0; index < work_choice_buttons.size(); ++index) { work_choice_buttons[index] = button(first_work_choice_id + static_cast(index), 0, 100, L"", BS_OWNERDRAW, 0); ShowWindow(work_choice_buttons[index], SW_HIDE); } title_screen.create(window); apply_interface_scale(window, read_interface_scale()); show_title_screen(window, true); refresh_lan_controls(window); SetTimer(window, timer_id, 60, nullptr); return 0; } case WM_DRAWITEM: if (const auto* item = reinterpret_cast(lparam); item && item->CtlType == ODT_BUTTON) { if (showing_title ? title::TitleScreen::draw_button(*item) : draw_toolbar_button(*item)) return TRUE; } break; case WM_CTLCOLORLISTBOX: if (showing_title) { if (const auto brush = title_screen.paint_list_background(reinterpret_cast(lparam), reinterpret_cast(wparam))) return reinterpret_cast(brush); } break; case WM_COMMAND: if (showing_title) { handle_title_command(window, LOWORD(wparam), HIWORD(wparam)); return 0; } if (LOWORD(wparam) == work_list_button_id && HIWORD(wparam) == BN_CLICKED && can_give_orders()) { if (const auto menu = create_work_menu()) { RECT bounds{}; GetWindowRect(work_list_button, &bounds); TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, bounds.left, bounds.top, 0, window, nullptr); DestroyMenu(menu); } SetFocus(window); return 0; } if (LOWORD(wparam) == residents_button_id && HIWORD(wparam) == BN_CLICKED) { if (world) show_resident_roster(window); return 0; } if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == build_blueprint_id) { submit_blueprint(window); SetFocus(window); return 0; } if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == clear_blueprint_id && has_blueprint()) { clear_blueprints(); placement_message = L"Чертёж очищен."; update_blueprint_controls(window); SetFocus(window); invalidate_scene(window); return 0; } if (LOWORD(wparam) >= farmer_menu_id && LOWORD(wparam) <= builder_menu_id && HIWORD(wparam) == BN_CLICKED) { const auto panel = static_cast(LOWORD(wparam) - farmer_menu_id); toggle_work_panel(window, panel); return 0; } if (LOWORD(wparam) == carpenter_menu_id && HIWORD(wparam) == BN_CLICKED) { toggle_work_panel(window, WorkPanel::Carpenter); update_status(); return 0; } if (HIWORD(wparam) == BN_CLICKED && (LOWORD(wparam) == craft_door_id || (LOWORD(wparam) >= first_furniture_craft_id && LOWORD(wparam) < first_furniture_craft_id + static_cast(furniture_products.size()))) && world && world->carpenter_workshop() && can_give_orders()) { const bool is_furniture_order = LOWORD(wparam) != craft_door_id; const int furniture_index = static_cast(LOWORD(wparam)) - first_furniture_craft_id; const bool accepted = is_furniture_order ? send_command(settlement::CommandKind::CraftFurniture, {}, static_cast(furniture_products[static_cast(furniture_index)])) : send_command(settlement::CommandKind::CraftDoor); if (accepted) { placement_message = lan.is_guest() ? L"Заказ отправлен хозяину." : L"Заказ принят мастерской."; } SetFocus(window); invalidate_scene(window); return 0; } if (LOWORD(wparam) >= first_dock_section_id && static_cast(LOWORD(wparam) - first_dock_section_id) < dock_sections.size() && HIWORD(wparam) == BN_CLICKED) { const auto panel = dock_sections[static_cast(LOWORD(wparam) - first_dock_section_id)].panel; toggle_work_panel(window, panel); return 0; } if (LOWORD(wparam) >= first_work_choice_id && static_cast(LOWORD(wparam) - first_work_choice_id) < work_choice_buttons.size() && HIWORD(wparam) == BN_CLICKED) { const auto choices = work_choices(); const auto index = static_cast(LOWORD(wparam) - first_work_choice_id); if (index >= choices.size() || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; SendMessageW(window, WM_COMMAND, static_cast(choices[index].command), 0); return 0; } if (LOWORD(wparam) >= berry_field_id && LOWORD(wparam) <= demolish_id) { if (!world || (lan.is_guest() && lan.state() != LanState::GuestConnected)) return 0; constexpr PlacementMode modes[] = {PlacementMode::BerryField, PlacementMode::TreePlot, PlacementMode::Mine, PlacementMode::Storage, PlacementMode::Pantry, PlacementMode::Move, PlacementMode::Demolish}; set_placement_mode(window, modes[LOWORD(wparam) - berry_field_id]); SetFocus(window); return 0; } if ((LOWORD(wparam) == flax_field_id || LOWORD(wparam) == loom_id) && HIWORD(wparam) == BN_CLICKED) { if (!world || !can_give_orders()) return 0; set_placement_mode(window, LOWORD(wparam) == flax_field_id ? PlacementMode::FlaxField : PlacementMode::Loom); SetFocus(window); return 0; } if (LOWORD(wparam) == reset_camera_id) { camera = {}; hover_cell.reset(); invalidate_scene(window); return 0; } if (LOWORD(wparam) == building_view_id && HIWORD(wparam) == BN_CLICKED) { const auto index = (static_cast(building_view) + 1) % std::size(building_view_labels); building_view = static_cast(index); SetWindowTextW(building_view_button, building_view_labels[index]); SetFocus(window); invalidate_scene(window); return 0; } if (LOWORD(wparam) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) { set_placement_mode(window, placement_mode == PlacementMode::Building ? PlacementMode::None : PlacementMode::Building); SetFocus(window); return 0; } if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { const bool editing_empty_room = placement_mode == PlacementMode::Room && selected_room_template == settlement::RoomTemplate::Empty; set_placement_mode(window, editing_empty_room ? PlacementMode::None : PlacementMode::Room); SetFocus(window); return 0; } if (LOWORD(wparam) == furnished_room_tool_id && HIWORD(wparam) == BN_CLICKED && world && world->scenario_active() && can_give_orders()) { house_list_parent = work_panel; set_placement_mode(window, PlacementMode::None); set_work_panel(window, WorkPanel::Houses); SetFocus(window); return 0; } if (LOWORD(wparam) == house_list_back_id && HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses) { set_placement_mode(window, PlacementMode::None); set_work_panel(window, house_list_parent); SetFocus(window); return 0; } if (LOWORD(wparam) >= first_house_tool_id && LOWORD(wparam) < first_house_tool_id + house_artwork.size() && HIWORD(wparam) == BN_CLICKED && work_panel == WorkPanel::Houses && can_give_orders()) { const auto layout = house_choices[LOWORD(wparam) - first_house_tool_id + 1].layout; const bool already_selected = placement_mode == PlacementMode::Room && selected_room_template == layout; set_placement_mode(window, already_selected ? PlacementMode::None : PlacementMode::Room); if (!already_selected) selected_room_template = layout; invalidate_work_choices(); 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; placement_message.clear(); update_bed_choices(); SetFocus(window); invalidate_scene(window); return 0; } if (LOWORD(wparam) == forage_action_id && HIWORD(wparam) == BN_CLICKED && world && (!lan.is_guest() || lan.state() == LanState::GuestConnected)) { set_placement_mode(window, placement_mode == PlacementMode::Foraging ? PlacementMode::None : PlacementMode::Foraging); SetFocus(window); return 0; } if (LOWORD(wparam) == priority_button_id && HIWORD(wparam) == BN_CLICKED && world && world->scenario_active()) { const auto next = (static_cast(world->work_priority()) + 1U) % 3U; static_cast(send_command(settlement::CommandKind::SetPriority, {}, static_cast(next))); update_status(); return 0; } break; case WM_MOUSEWHEEL: { POINT point = client_point(lparam); if (!ScreenToClient(window, &point)) break; RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) break; const double steps = static_cast(GET_WHEEL_DELTA_WPARAM(wparam)) / WHEEL_DELTA; camera.zoom_at({static_cast(point.x), static_cast(point.y)}, steps); update_map_hover(window, point); invalidate_scene(window); return 0; } case WM_MBUTTONDOWN: { RECT client{}; GetClientRect(window, &client); const POINT point = client_point(lparam); if (!is_map_point(client, point) || camera_drag) break; SetFocus(window); SetCapture(window); camera_drag = CameraDrag{point, false, false}; return 0; } case WM_MBUTTONUP: if (camera_drag && !camera_drag->left_button) { update_camera_drag(client_point(lparam)); camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); invalidate_scene(window); return 0; } break; case WM_CAPTURECHANGED: camera_drag.reset(); break; case WM_MOUSEMOVE: { const POINT point = client_point(lparam); if (camera_drag) { update_camera_drag(point); invalidate_scene(window); } update_map_hover(window, point); return 0; } case WM_MOUSELEAVE: hover_cell.reset(); invalidate_scene(window); return 0; case WM_LBUTTONDOWN: { RECT client{}; GetClientRect(window, &client); const POINT point = client_point(lparam); if (camera_drag || !is_map_point(client, point)) break; SetFocus(window); SetCapture(window); camera_drag = CameraDrag{point, true, false}; return 0; } case WM_LBUTTONUP: { if (!camera_drag || !camera_drag->left_button) break; const POINT point = client_point(lparam); update_camera_drag(point); const bool moved = camera_drag->moved; camera_drag.reset(); if (GetCapture() == window) ReleaseCapture(); if (moved) { update_map_hover(window, point); invalidate_scene(window); return 0; } RECT client{}; GetClientRect(window, &client); if (!is_map_point(client, point)) break; if (placement_mode == PlacementMode::Foraging && world) { const auto cell = map_cell(client, point); const auto* source = cell ? berry_source(*cell) : nullptr; if (source != nullptr) { static_cast(send_command(settlement::CommandKind::SetForaging, *cell, static_cast(!source->foraging_enabled))); } else { placement_message = L"Для сбора выберите ягодный куст."; } invalidate_scene(window); return 0; } if (world && is_blueprint_tool()) { if (const auto cell = map_cell(client, point)) { if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell, (wparam & MK_SHIFT) != 0); else edit_blueprint(window, *cell); } return 0; } if (world && placement_mode >= PlacementMode::BerryField) { if (const auto cell = map_cell(client, point)) edit_at_cell(window, *cell); return 0; } if (world) { selected_resident = resident_at(window, point); update_status(); sync_resident_roster(true); invalidate_scene(window); return 0; } break; } case WM_RBUTTONDOWN: if (placement_mode == PlacementMode::Room) { if (room_draft_move) { room_draft_move.reset(); placement_message.clear(); update_blueprint_controls(window); invalidate_scene(window); return 0; } 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); return 0; } break; case WM_KEYDOWN: if (showing_title) break; if (placement_mode == PlacementMode::Room && (wparam == 'R' || wparam == VK_OEM_COMMA || wparam == VK_OEM_PERIOD)) { if ((lparam & (1L << 30)) == 0) rotate_room_preview(window, wparam == VK_OEM_COMMA ? -1 : 1); return 0; } if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (wparam == 'H' || wparam == 'Z' || wparam == 'B')) { if ((lparam & (1L << 30)) == 0) { toggle_work_panel(window, wparam == 'H' ? WorkPanel::Gathering : wparam == 'Z' ? WorkPanel::Zones : WorkPanel::Construction); } return 0; } if (wparam == 'C' && (GetKeyState(VK_CONTROL) & 0x8000) == 0) { if (world) show_resident_roster(window); return 0; } if (wparam == VK_HOME) { SendMessageW(window, WM_COMMAND, reset_camera_id, 0); return 0; } if (wparam == VK_ESCAPE) { if ((lparam & (1L << 30)) == 0) open_pause_menu(window); return 0; } break; case WM_TIMER: if (wparam == timer_id && world) { const auto state = lan.state(); if (showing_title && (state == LanState::Offline || state == LanState::GuestDisconnected)) return 0; if (!file_dialog_active && !lan.is_guest() && (state != LanState::Offline || (!showing_title && !pause_menu_open))) world->step(); if (auto snapshot = lan.poll(*world)) { world = std::move(snapshot); has_session = true; } if (showing_title && enter_game_on_snapshot && !coop_menu_open && lan.state() == LanState::GuestConnected) { show_title_screen(window, false); } sync_resident_roster(); if (lan.state() != displayed_lan_state) refresh_lan_controls(window); if (const auto rejection = lan.take_rejection()) { using settlement::CommandKind; using settlement::RecipeId; const bool bed = rejection->kind == CommandKind::PlaceBed; if (rejection->kind == CommandKind::PlaceRoom) { const auto room = settlement::RoomPlan::from_placement( rejection->cell, rejection->destination, rejection->value); if (room.valid_size() && std::none_of(room_blueprints.begin(), room_blueprints.end(), [&](const auto& other) { return other.first == room.first && other.last == room.last; })) { room_blueprints.push_back(room); update_blueprint_controls(window); } placement_message = L"Хозяин отклонил площадку. Комната возвращена в чертёж."; } else if (bed || rejection->kind == CommandKind::PlaceLoom) { if (std::none_of(blueprint.begin(), blueprint.end(), [&](const auto& part) { return part.cell == rejection->cell; })) { blueprint.push_back({rejection->cell, bed ? RecipeId::BuildBed : RecipeId::WeaveCloth, static_cast(rejection->value)}); update_blueprint_controls(window); } placement_message = L"Клетка отклонена хозяином и оставлена в чертеже."; } else { placement_message = rejection->status == settlement::CommandStatus::Busy ? L"Объект занят. Дождитесь окончания работы или сна." : L"Хозяин отклонил команду. Проверьте выбранную клетку."; } } update_status(); invalidate_scene(window); return 0; } break; case WM_ERASEBKGND: return 1; case WM_SIZE: if (showing_title) { RECT client{}; GetClientRect(window, &client); title_screen.layout(client.right, client.bottom); } else { layout_command_dock(window); } InvalidateRect(window, nullptr, FALSE); break; case WM_PAINT: { PAINTSTRUCT paint{}; HDC target = BeginPaint(window, &paint); RECT client{}; GetClientRect(window, &client); const int width = client.right - client.left; const int height = client.bottom - client.top; HDC buffer = CreateCompatibleDC(target); HBITMAP bitmap = CreateCompatibleBitmap(target, width, height); HGDIOBJ old_bitmap = SelectObject(buffer, bitmap); if (showing_title) title_screen.draw(buffer, width, height, placement_message); else draw_world(buffer, width, height); const RECT& dirty = paint.rcPaint; BitBlt(target, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top, buffer, dirty.left, dirty.top, SRCCOPY); SelectObject(buffer, old_bitmap); DeleteObject(bitmap); DeleteDC(buffer); EndPaint(window, &paint); return 0; } case WM_DESTROY: KillTimer(window, timer_id); lan.leave(); graphics.reset(); if (dock_font) DeleteObject(std::exchange(dock_font, nullptr)); scene_window = nullptr; PostQuitMessage(0); return 0; } return DefWindowProcW(window, message, wparam, lparam); } } // namespace int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show_command) { INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls); WNDCLASSEXW window_class_info{}; window_class_info.cbSize = sizeof(window_class_info); window_class_info.hInstance = instance; window_class_info.lpfnWndProc = window_proc; window_class_info.lpszClassName = window_class; window_class_info.hCursor = LoadCursorW(nullptr, IDC_ARROW); window_class_info.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); RegisterClassExW(&window_class_info); HWND window = CreateWindowExW(0, window_class, L"Settlement", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1120, 752, nullptr, nullptr, instance, nullptr); if (!window) return 1; ShowWindow(window, show_command); UpdateWindow(window); MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { if (roster.window && IsDialogMessageW(roster.window, &message)) continue; if (showing_title && IsDialogMessageW(window, &message)) continue; if (!showing_title && message.message == WM_KEYDOWN && message.wParam == VK_ESCAPE && (message.hwnd == window || IsChild(window, message.hwnd))) { SendMessageW(window, message.message, message.wParam, message.lParam); continue; } TranslateMessage(&message); DispatchMessageW(&message); } return static_cast(message.wParam); }