#define NOMINMAX #define UNICODE #define _UNICODE #include #include #include #include #include "d3d_scene_win32.hpp" #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 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 exit_menu_id = 1121; 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 int map_footer = 166; constexpr int dock_sections_offset = 40; constexpr int dock_actions_offset = 110; constexpr int dock_materials_offset = 77; constexpr int bed_choice_width = 78; constexpr int bed_choice_height = 28; constexpr int work_button_gap = 8; 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; 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::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 }; PlacementMode placement_mode = PlacementMode::None; enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, None }; WorkPanel work_panel = WorkPanel::None; enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish }; struct WorkChoice { int command; const wchar_t* title; WorkIcon icon; int width; PlacementMode mode = PlacementMode::None; }; 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 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}, }; std::array work_choice_buttons{}; constexpr std::array gathering_choices = {farmer_choices[0], miner_choices[0]}; constexpr std::array zones_choices = {farmer_choices[1], farmer_choices[2], woodcutter_choices[0], builder_choices[2], builder_choices[3]}; constexpr std::array construction_choices = {builder_choices[0], builder_choices[1], builder_choices[4], builder_choices[5]}; 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}, }; 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::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; 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) { 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; 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; } 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_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 - map_footer; } 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); 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 - map_footer), 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::None: return {}; } return {}; } void layout_command_dock(HWND window) { const auto choices = work_choices(); RECT client{}; GetClientRect(window, &client); const auto width = static_cast(client.right); const auto height = static_cast(client.bottom); constexpr int section_widths[] = {112, 112, 112, 160}; constexpr int sections_width = 112 * 3 + 160 + 3 * work_button_gap; int section_x = std::max(16, (width - sections_width) / 2); const auto place = [](HWND button, int x, int y, int w, int h) { SetWindowPos(button, nullptr, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); }; place(residents_button, section_x, height - dock_sections_offset, section_widths[0], 31); section_x += section_widths[0] + work_button_gap; for (std::size_t index = 0; index < dock_section_buttons.size(); ++index) { const int button_width = section_widths[index + 1]; place(dock_section_buttons[index], section_x, height - dock_sections_offset, button_width, 31); section_x += button_width + work_button_gap; } int row_width = choices.empty() ? 0 : -work_button_gap; for (const auto& choice : choices) row_width += choice.width + work_button_gap; int x = std::max(16, (width - row_width) / 2); for (std::size_t index = 0; index < choices.size(); ++index) { const auto& choice = choices[index]; place(work_choice_buttons[index], x, height - dock_actions_offset, choice.width, 28); if (choice.command == cabin_button_id) { place(wood_bed_button, x, height - dock_materials_offset, bed_choice_width, bed_choice_height); place(stone_bed_button, x + bed_choice_width + 4, height - dock_materials_offset, bed_choice_width, bed_choice_height); } x += choice.width + work_button_gap; } } 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); 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 - map_footer; InvalidateRect(window, &row, FALSE); } void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false) { 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 icon_width = 17; 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; draw_work_icon(dc, icon, left + offset, (box.top + box.bottom - icon_width) / 2 + offset); 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); switch (id) { case wood_bed_button_id: draw_icon_button(item, WorkIcon::Wood, selected_bed_base == settlement::BedBase::Wood, true); return true; case stone_bed_button_id: draw_icon_button(item, WorkIcon::Stone, selected_bed_base == settlement::BedBase::Stone, true); return true; case residents_button_id: draw_icon_button(item, WorkIcon::Resident, roster.window != nullptr, true); return true; case work_list_button_id: draw_icon_button(item, WorkIcon::Hammer, false); return true; } 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)]; draw_icon_button(item, section.icon, work_panel == section.panel, true); return true; } 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)]; draw_icon_button(item, choice.icon, placement_mode == choice.mode, true); return true; } 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; 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); } 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(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); 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 = shows_bed_choices() ? SW_SHOW : 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 set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message = L"") { placement_mode = mode; selected_bed_base.reset(); move_source.reset(); hover_cell.reset(); placement_message = message; update_bed_choices(); invalidate_work_choices(); invalidate_scene(window); } 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); layout_command_dock(window); layout_scene(window); SetFocus(window); InvalidateRect(window, nullptr, FALSE); } void reset_world(HWND window) { world = settlement::make_first_colony(local_worker_count); 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); 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); 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())); 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::None: return false; } return false; } 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 if (placement_mode == PlacementMode::Loom) { command = CommandKind::PlaceLoom; } 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 (std::size_t index = 0; index + 1 < role_choices.size(); ++index) { AppendMenuW(menu, MF_STRING, farmer_menu_id + index, role_choices[index + 1].title); } 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, 311, 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, 218, 234, 30); roster.notice = control(L"STATIC", L"", 0, SS_LEFT, 316, 256, 234, 44); const auto close = control(L"BUTTON", L"Закрыть", IDCANCEL, WS_TABSTOP | BS_PUSHBUTTON, 447, 301, 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, 343}; 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"лён"} }; 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->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; } 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 + map_footer) { RECT scene{16, map_top + 24, width - 16, height - map_footer}; 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 - map_footer, 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::Loom) { 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::Building) { if (world->staged_beds()) { hint = selected_bed_base ? L"Щёлкайте по свободным клеткам. Основу можно сменить под кнопкой «Спальное место»." : L"Выберите «Дерево» или «Камень» под кнопкой «Спальное место»."; } else if (world->scenario_active()) { hint = L"Щёлкайте по свободным клеткам. Одно место требует доску. Правая кнопка — отмена."; } else { hint = L"Выберите свободную клетку. Домик стоит три доски и два блока. Правая кнопка — отмена."; } } RECT legend{24, height - 159, width - 24, height - 136}; DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); const auto details = resident_details(); SetTextColor(dc, color(190, 201, 178)); RECT inspector{24, height - 135, width - 24, height - 113}; DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } 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; 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, cursor && valid_edit_cell(*cursor), move_source, selected_resident}; } 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); } 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 MenuAction actions[] = { {IDOK, L"Продолжить"}, {save_menu_id, L"Сохранить поселение…", !lan.is_guest()}, {load_menu_id, L"Загрузить поселение…", offline}, {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 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 = 490; 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, 18, 142, L"Равный приоритет"); work_list_button = button(work_list_button_id, 168, 108, L"Работы", BS_OWNERDRAW); 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, bed_choice_width, L"Дерево", BS_OWNERDRAW, 0); stone_bed_button = button(stone_bed_button_id, 0, bed_choice_width, L"Камень", BS_OWNERDRAW, 0); 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); 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_TOPALIGN | TPM_RIGHTBUTTON, bounds.left, bounds.bottom, 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 (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) >= 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) == cabin_button_id && HIWORD(wparam) == BN_CLICKED) { set_placement_mode(window, placement_mode == PlacementMode::Building ? PlacementMode::None : PlacementMode::Building); 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 (placement_mode == PlacementMode::Building && world) { const auto cell = map_cell(client, point); if (world->scenario_active()) { if (!cell || !world->can_place_bed(*cell)) { placement_message = L"Для спального места нужна свободная клетка."; invalidate_scene(window); return 0; } if (shows_bed_choices() && !selected_bed_base) { placement_message = L"Сначала выберите основу под кнопкой «Спальное место»."; invalidate_scene(window); return 0; } const auto base = selected_bed_base.value_or(settlement::BedBase::Wood); if (send_command(settlement::CommandKind::PlaceBed, *cell, static_cast(base))) { hover_cell = cell; placement_message = lan.is_guest() ? L"Запрос на спальное место отправлен. Можно выбрать следующую клетку." : L"Спальное место заказано. Выберите следующую клетку или нажмите Esc."; update_status(); } else { placement_message = L"Для спального места нужна свободная клетка с проходом к мастерской."; } invalidate_scene(window); return 0; } if (!cell || !world->can_place_cabin(*cell)) { placement_message = L"Здесь нельзя поставить домик. Выберите свободную клетку."; invalidate_scene(window); return 0; } try { world->queue_cabin(*cell, sawmill, stonecutter); } catch (const std::invalid_argument&) { placement_message = L"К участку нет прохода от мастерских. Выберите другую клетку."; invalidate_scene(window); return 0; } set_placement_mode(window, PlacementMode::None, L"Чертёж поставлен. Материалы заказаны в мастерских."); update_status(); 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::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 ((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()) { placement_message = *rejection == 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); layout_scene(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(); 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_STANDARD_CLASSES | ICC_LISTVIEW_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); }