diff --git a/CMakeLists.txt b/CMakeLists.txt index c57a419..7e74e26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,18 +35,21 @@ add_executable(settlement_colony_benchmark benchmarks/colony.cpp) target_link_libraries(settlement_colony_benchmark PRIVATE settlement_core) if(WIN32) + enable_language(RC) add_executable(settlement_viewer WIN32 app/d3d_scene_win32.cpp app/viewer_win32.cpp app/lan_session_win32.cpp + app/house_icons.rc ) target_link_libraries(settlement_viewer PRIVATE settlement_core user32 gdi32 comctl32 comdlg32 ws2_32 bcrypt iphlpapi d3d11 d3dcompiler) if(NOT MSVC) target_link_options(settlement_viewer PRIVATE -municode) - target_compile_options(settlement_viewer PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) + target_compile_options(settlement_viewer PRIVATE + $<$:-Wall;-Wextra;-Wpedantic;-Wconversion;-Wshadow>) else() - target_compile_options(settlement_viewer PRIVATE /W4 /permissive-) + target_compile_options(settlement_viewer PRIVATE $<$:/W4;/permissive->) endif() endif() @@ -58,13 +61,18 @@ endif() include(CTest) if(BUILD_TESTING) + if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) + message(FATAL_ERROR "The reflection test suites need GCC 16 or later. Set BUILD_TESTING=OFF to build the game alone.") + endif() add_executable(settlement_core_tests tests/core_tests.cpp ) + target_compile_options(settlement_core_tests PRIVATE -std=c++26 -freflection) target_link_libraries(settlement_core_tests PRIVATE settlement_core) add_test(NAME settlement_core_tests COMMAND settlement_core_tests) if(WIN32) add_executable(settlement_lan_tests tests/lan_tests.cpp app/lan_session_win32.cpp) + target_compile_options(settlement_lan_tests PRIVATE -std=c++26 -freflection) target_include_directories(settlement_lan_tests PRIVATE app) target_link_libraries(settlement_lan_tests PRIVATE settlement_core ws2_32 bcrypt iphlpapi) add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests) diff --git a/PLAN.md b/PLAN.md index 861d0cd..c6445fc 100644 --- a/PLAN.md +++ b/PLAN.md @@ -9,7 +9,7 @@ ### P0 — Инструменты и границы проекта - [x] Отдельный каталог, CMake, C++20, лицензия и базовая структура. -- [x] Portable-установщик CMake/LLVM-MinGW и скрипт сборки с CTest. +- [x] Portable-установщик MSYS2 UCRT64 с GCC 16 и сборка с CTest. - [ ] CI для Windows и Linux. - [x] Не включать код и ресурсы Stonehearth. diff --git a/README.md b/README.md index a3e093a..344f8e8 100644 --- a/README.md +++ b/README.md @@ -42,16 +42,18 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tools\render-svg-to-pn По умолчанию он читает `build/workload.svg` и создаёт `build/workload.png`. -## Portable toolchain и сборка +## Сборка Windows на MSYS2 UCRT64 -Требуется 64-битная Windows с доступом к GitHub. Toolchain устанавливается локально в `.tools/`, не меняет системный PATH и не требует администратора. Скрипт загружает CMake и LLVM-MinGW с официальных релизов и проверяет доступные SHA-256 digests. +Требуется 64-битная Windows. Скрипт установки разворачивает MSYS2 в `.tools/toolchain/msys64`, проверяет SHA-256 архива и устанавливает GCC 16, CMake и Ninja через UCRT64. Если MSYS2 уже установлен, передайте его каталог обоим скриптам через `-Msys2Root` или задайте `SETTLEMENT_MSYS2_ROOT`. ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\setup-toolchain.ps1 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 ``` -Сборка запускает CTest и копирует runtime-библиотеки LLVM рядом с исполняемыми файлами, чтобы их можно было запускать без глобального PATH. +Сборка запускает CTest и помещает проверенные исполняемые файлы и библиотеки GCC в `build/`. Просмотрщик запускается из `build/settlement_viewer.exe`. + +Тесты используют C++26 и `-freflection`. `Void::Testing::Suite` находит методы с возвращаемым типом `Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры на другом компиляторе через CMake есть `-DBUILD_TESTING=OFF`. ## Структура diff --git a/app/art/doctor_house.ico b/app/art/doctor_house.ico new file mode 100644 index 0000000..9bc0d00 Binary files /dev/null and b/app/art/doctor_house.ico differ diff --git a/app/art/miner_house.ico b/app/art/miner_house.ico new file mode 100644 index 0000000..6873e31 Binary files /dev/null and b/app/art/miner_house.ico differ diff --git a/app/art/weaver_house.ico b/app/art/weaver_house.ico new file mode 100644 index 0000000..f191e24 Binary files /dev/null and b/app/art/weaver_house.ico differ diff --git a/app/d3d_scene_win32.cpp b/app/d3d_scene_win32.cpp index fadeacc..0eb447b 100644 --- a/app/d3d_scene_win32.cpp +++ b/app/d3d_scene_win32.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -140,20 +141,191 @@ void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool .02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color); } mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f)); - } -} - -void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { - for (int y = plan.first.y; y <= plan.last.y; ++y) { - for (int x = plan.first.x; x <= plan.last.x; ++x) { - const GridPosition cell{x, y}; - room_part(mesh, cell, plan.recipe_at(cell), !valid ? rgb(203, 113, 101) : - (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)), true); + if (!draft) { + const auto leaf = [x, y, along_x](float side, float inward, float height) { + return along_x ? Point{x + side, y + inward, height} : Point{x + inward, y + side, height}; + }; + mesh.quad(leaf(-.28f, 0.f, .04f), leaf(-.06f, .40f, .04f), leaf(-.06f, .40f, .66f), + leaf(-.28f, 0.f, .66f), shade(color, .75f)); + const auto handle = leaf(-.09f, .32f, .37f); + mesh.box(handle.x, handle.y, handle.z, .06f, .06f, .06f, rgb(215, 183, 107)); } } } -void construction(Mesh& mesh, const World& world) { +void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview); + +void draw_furnishing(Mesh& mesh, GridPosition cell, RecipeId recipe, Color wood, Color detail) { + const float x = static_cast(cell.x), y = static_cast(cell.y); + if (recipe == RecipeId::BuildMedicineCabinet) { + mesh.box(x, y + .10f, .03f, .64f, .35f, .61f, wood); + for (const float offset : {-.22f, 0.f, .22f}) { + mesh.box(x + offset, y - .13f, .34f, .15f, .15f, .22f, detail); + mesh.box(x + offset, y - .13f, .56f, .10f, .10f, .056f, shade(detail, .73f)); + } + } else if (recipe == RecipeId::BuildMiningRack) { + mesh.box(x, y, .03f, .74f, .45f, .12f, wood); + for (const float offset : {-.25f, .25f}) { + mesh.box(x + offset, y + .1f, .15f, .09f, .10f, .62f, wood); + } + mesh.box(x, y + .1f, .64f, .64f, .10f, .11f, wood); + for (const float offset : {-.15f, .15f}) { + mesh.box(x + offset, y - .04f, .22f, .045f, .05f, .39f, shade(wood, 1.25f)); + mesh.box(x + offset, y - .04f, .59f, .23f, .08f, .07f, detail); + } + } else { + mesh.box(x, y, .025f, .71f, .58f, .34f, shade(wood, .82f)); + mesh.box(x, y, .37f, .77f, .62f, .10f, wood); + mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, wood); + mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, detail); + } +} + +void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) { + const auto ink = !valid ? rgb(203, 113, 101) : + (preview ? rgb(169, 224, 232) : rgb(104, 176, 212)); + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + room_part(mesh, cell, plan.recipe_at(cell), ink, true); + } + } + if (const auto furnishings = plan.furnishings()) { + for (const auto& part : *furnishings) { + if (part.recipe == RecipeId::BuildBed) { + draw_blueprint(mesh, {part.position, part.recipe, part.bed_base}, preview); + } else { + draw_furnishing(mesh, part.position, part.recipe, ink, shade(ink, .73f)); + } + } + } +} + +void draw_gabled_roof(Mesh& mesh, float left, float top, float right, float bottom, float eaves, + float ridge, bool along_x, Color tiles, Color gable) { + if (!along_x) { + std::swap(left, top); + std::swap(right, bottom); + } + const auto point = [along_x](float x, float y, float z) { + return along_x ? Point{x, y, z} : Point{y, x, z}; + }; + const float middle = (top + bottom) / 2.f; + constexpr float overhang = .12f; + for (const float edge : {left, right}) { + const auto peak = point(edge, middle, ridge); + mesh.quad(point(edge, top, eaves), point(edge, bottom, eaves), peak, peak, gable); + } + left -= overhang; + right += overhang; + const auto slope = [&](float edge, float light) { + constexpr std::array shades{.90f, 1.03f, .95f, 1.08f}; + for (std::size_t i = 0; i < shades.size(); ++i) { + const float a = static_cast(i) / static_cast(shades.size()); + const float b = static_cast(i + 1) / static_cast(shades.size()); + const float y1 = std::lerp(edge, middle, a), y2 = std::lerp(edge, middle, b); + const float z1 = std::lerp(eaves, ridge, a), z2 = std::lerp(eaves, ridge, b); + mesh.quad(point(left, y1, z1), point(right, y1, z1), point(right, y2, z2), + point(left, y2, z2), shade(tiles, light * shades[i])); + } + }; + slope(top - overhang, .93f); + slope(bottom + overhang, 1.12f); + mesh.quad(point(left, middle - .035f, ridge + .02f), point(right, middle - .035f, ridge + .02f), + point(right, middle + .035f, ridge + .02f), point(left, middle + .035f, ridge + .02f), + shade(tiles, .72f)); +} + +void draw_room_roofs(Mesh& mesh, const World& world) { + struct Tile { + RecipeId structure = RecipeId::SawPlank; + RoomTemplate furnishing = RoomTemplate::Empty; + bool visited = false; + }; + const auto width = static_cast(world.width()); + std::vector map(width * static_cast(world.height())); + const auto tile = [&](GridPosition cell) -> Tile& { + return map[static_cast(cell.y) * width + static_cast(cell.x)]; + }; + for (const auto& order : world.production_orders()) { + auto& cell = tile(order.position); + if (is_room_part(order.recipe) && order.state == JobState::Completed) { + cell.structure = room_part_shape(order.recipe); + } + switch (order.recipe) { + case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break; + case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break; + case RecipeId::BuildLoom: + case RecipeId::WeaveCloth: cell.furnishing = RoomTemplate::Weaver; break; + default: break; + } + } + const auto in_bounds = [&](GridPosition cell) { + return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height(); + }; + const GridPosition neighbors[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + const auto intact = [&](const RoomPlan& plan) { + for (int y = plan.first.y; y <= plan.last.y; ++y) { + for (int x = plan.first.x; x <= plan.last.x; ++x) { + const GridPosition cell{x, y}; + if (tile(cell).structure != plan.recipe_at(cell)) return false; + } + } + return true; + }; + constexpr Color finishes[] = {rgb(146, 94, 66), rgb(107, 136, 76), rgb(86, 116, 136), rgb(169, 91, 65)}; + std::vector floor; + const auto visit = [&](GridPosition cell) { + if (!in_bounds(cell)) return; + auto& entry = tile(cell); + if (entry.visited || entry.structure != RecipeId::BuildFloor) return; + entry.visited = true; + floor.push_back(cell); + }; + for (int y = 0; y < world.height(); ++y) { + for (int x = 0; x < world.width(); ++x) { + floor.clear(); + visit({x, y}); + if (floor.empty()) continue; + GridPosition first{x, y}, last{x, y}; + auto finish = RoomTemplate::Empty; + for (std::size_t i = 0; i < floor.size(); ++i) { + const auto from = floor[i]; + first.x = std::min(first.x, from.x); + first.y = std::min(first.y, from.y); + last.x = std::max(last.x, from.x); + last.y = std::max(last.y, from.y); + if (tile(from).furnishing != RoomTemplate::Empty) finish = tile(from).furnishing; + for (const auto offset : neighbors) visit({from.x + offset.x, from.y + offset.y}); + } + RoomPlan plan{{first.x - 1, first.y - 1}, {last.x + 1, last.y + 1}}; + if (!plan.valid_size() || !in_bounds(plan.first) || !in_bounds(plan.last)) continue; + // A room from an older save has the same completed floor and perimeter as a new room. + for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) { + plan.entrance = side; + if (!intact(plan)) continue; + const bool along_x = side == RoomSide::East || side == RoomSide::West; + const int span = along_x ? plan.last.y - plan.first.y : plan.last.x - plan.first.x; + draw_gabled_roof(mesh, static_cast(plan.first.x) - .5f, static_cast(plan.first.y) - .5f, + static_cast(plan.last.x) + .5f, static_cast(plan.last.y) + .5f, .85f, + .85f + std::min(.24f * static_cast(span + 1), 1.65f), along_x, + finishes[static_cast(finish)], rgb(176, 127, 82)); + break; + } + } + } +} + +void construction(Mesh& mesh, const World& world, BuildingView building_view) { + const auto workshop = world.carpenter_workshop(); + if (workshop) { + const auto x = static_cast(workshop->x); + const auto y = static_cast(workshop->y); + mesh.box(x, y, .02f, .87f, .74f, .36f, rgb(142, 95, 59)); + mesh.box(x, y, .38f, .92f, .77f, .12f, rgb(209, 161, 104)); + mesh.box(x, y - .12f, .50f, .59f, .12f, .08f, rgb(180, 190, 191)); + mesh.box(x - .29f, y - .12f, .52f, .16f, .17f, .12f, rgb(123, 68, 46)); + } for (const auto& storage : world.storages()) { const float x = static_cast(storage.position.x), y = static_cast(storage.position.y); mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65)); @@ -162,27 +334,39 @@ void construction(Mesh& mesh, const World& world) { mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124)); } for (const auto& order : world.production_orders()) { + if (order.recipe == RecipeId::CraftWoodenDoor || + (order.recipe == RecipeId::SawPlank && workshop == order.position)) continue; const float x = static_cast(order.position.x), y = static_cast(order.position.y); + if (order.recipe == RecipeId::WeaveCloth) { + draw_furnishing(mesh, order.position, order.recipe, rgb(185, 140, 86), rgb(235, 225, 193)); + continue; + } if (!is_construction(order.recipe)) { mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73)); mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100)); - if (order.recipe == RecipeId::WeaveCloth) { - mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, rgb(167, 124, 79)); - mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, rgb(235, 225, 193)); - } continue; } if (order.state != JobState::Completed) { const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99); mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked); } - if (order.recipe >= RecipeId::BuildFloor) { + if (is_room_part(order.recipe)) { + const auto shape = room_part_shape(order.recipe); + if (building_view == BuildingView::FloorsOnly && shape != RecipeId::BuildFloor) continue; if (order.state == JobState::Completed) { - room_part(mesh, order.position, order.recipe, rgb(175, 123, 78), false); - } else if (order.recipe != RecipeId::BuildFloor) { - room_part(mesh, order.position, order.recipe, + room_part(mesh, order.position, shape, rgb(175, 123, 78), false); + } else if (shape != RecipeId::BuildFloor) { + room_part(mesh, order.position, shape, order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true); } + } else if (order.recipe == RecipeId::BuildMedicineCabinet || order.recipe == RecipeId::BuildMiningRack || + order.recipe == RecipeId::BuildLoom) { + const bool finished = order.state == JobState::Completed; + const auto wood = finished ? rgb(175, 123, 78) : rgb(117, 168, 181); + const auto detail = finished + ? (order.recipe == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172)) + : rgb(158, 202, 209); + draw_furnishing(mesh, order.position, order.recipe, wood, detail); } else if (order.recipe == RecipeId::BuildBed && (order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) { mesh.box(x, y, .045f, .77f, .43f, .18f, @@ -193,16 +377,18 @@ void construction(Mesh& mesh, const World& world) { if (order.state == JobState::Completed) { mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194)); } + } else if (order.recipe == RecipeId::BuildBed) { + draw_blueprint(mesh, {order.position, order.recipe, order.bed_base}, false); } else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) { - mesh.box(x, y, .03f, .83f, .82f, .65f, rgb(194, 151, 103)); - mesh.quad({x - .46f, y + .46f, .64f}, {x + .46f, y + .46f, .64f}, - {x + .46f, y, 1.03f}, {x - .46f, y, 1.03f}, rgb(158, 83, 62)); - mesh.quad({x - .46f, y, 1.03f}, {x + .46f, y, 1.03f}, - {x + .46f, y - .46f, .64f}, {x - .46f, y - .46f, .64f}, rgb(193, 113, 79)); - mesh.quad({x + .42f, y - .42f, .67f}, {x + .42f, y + .42f, .67f}, - {x + .42f, y, 1.01f}, {x + .42f, y, 1.01f}, rgb(174, 126, 80)); + const float walls = building_view == BuildingView::FloorsOnly ? .07f : .65f; + mesh.box(x, y, .03f, .83f, .82f, walls, rgb(194, 151, 103)); + if (building_view == BuildingView::Full) { + draw_gabled_roof(mesh, x - .415f, y - .41f, x + .415f, y + .41f, + .68f, 1.03f, true, rgb(159, 90, 66), rgb(174, 126, 80)); + } } } + if (building_view == BuildingView::Full) draw_room_roofs(mesh, world); for (const auto& job : world.jobs()) { if (job.state == JobState::Completed) continue; const float x = static_cast(job.position.x), y = static_cast(job.position.y); @@ -266,7 +452,9 @@ void residents(Mesh& mesh, const World& world, const SceneView& view) { mesh.box(x, y, .167f, .27f, .22f, .22f, clothes); mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144)); mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56)); - if (!agent.inventory.empty()) { + if (agent.inventory.item_count(ItemType::WoodenDoor) != 0) { + mesh.box(x - .14f, y - .12f, .09f, .13f, .30f, .39f, rgb(177, 116, 70)); + } else if (!agent.inventory.empty()) { mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92)); } } @@ -446,8 +634,12 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector preview; std::span room_blueprints; std::optional room_preview; + BuildingView building_view = BuildingView::Full; + std::optional moving_room; }; class D3DScene { diff --git a/app/house_icons.h b/app/house_icons.h new file mode 100644 index 0000000..47891e3 --- /dev/null +++ b/app/house_icons.h @@ -0,0 +1,8 @@ +#ifndef SETTLEMENT_HOUSE_ICONS_H +#define SETTLEMENT_HOUSE_ICONS_H + +#define IDI_DOCTOR_HOUSE 201 +#define IDI_MINER_HOUSE 202 +#define IDI_WEAVER_HOUSE 203 + +#endif diff --git a/app/house_icons.rc b/app/house_icons.rc new file mode 100644 index 0000000..93ca12b --- /dev/null +++ b/app/house_icons.rc @@ -0,0 +1,5 @@ +#include "house_icons.h" + +IDI_DOCTOR_HOUSE ICON "art/doctor_house.ico" +IDI_MINER_HOUSE ICON "art/miner_house.ico" +IDI_WEAVER_HOUSE ICON "art/weaver_house.ico" diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index 49b1b3d..c24e5c6 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -24,7 +24,7 @@ namespace { using Clock = std::chrono::steady_clock; using namespace std::chrono_literals; -constexpr std::uint32_t protocol_version = 8; +constexpr std::uint32_t protocol_version = 10; constexpr std::size_t frame_limit = 4 * 1024 * 1024; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; diff --git a/app/viewer_win32.cpp b/app/viewer_win32.cpp index 340a63b..abeded6 100644 --- a/app/viewer_win32.cpp +++ b/app/viewer_win32.cpp @@ -7,6 +7,7 @@ #include #include "d3d_scene_win32.hpp" +#include "house_icons.h" #include "map_camera.hpp" #include "lan_session.hpp" #include "title_screen_win32.hpp" @@ -65,6 +66,10 @@ 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_work_choice_id = 1050; constexpr int resident_list_id = 1060; constexpr int first_role_id = 1070; @@ -72,10 +77,12 @@ 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; @@ -97,6 +104,7 @@ 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 { @@ -117,6 +125,11 @@ 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; @@ -124,15 +137,17 @@ 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, None }; +enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None }; WorkPanel work_panel = WorkPanel::None; -enum class WorkIcon { Berries, Field, Flax, Tree, Pickaxe, Hammer, Loom, Resident, Bed, Wood, Stone, Crate, Pantry, Move, Demolish, Priority }; +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}, @@ -145,6 +160,9 @@ constexpr std::array woodcutter_choices = { constexpr std::array miner_choices = { WorkChoice{mine_id, L"Шахта", WorkIcon::Pickaxe, 98, PlacementMode::Mine}, }; +constexpr std::array carpenter_choices = { + WorkChoice{craft_door_id, L"Изготовить дверь", WorkIcon::Wood, 190}, +}; constexpr std::array builder_choices = { WorkChoice{cabin_button_id, L"Спальное место", WorkIcon::Bed, 153, PlacementMode::Building}, WorkChoice{loom_id, L"Ткацкий станок", WorkIcon::Loom, 149, PlacementMode::Loom}, @@ -153,13 +171,29 @@ constexpr std::array builder_choices = { 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[4], builder_choices[5]}; + 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; @@ -182,6 +216,7 @@ constexpr std::array role_choices = { 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; @@ -203,6 +238,14 @@ 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 { @@ -344,6 +387,14 @@ void draw_work_icon(HDC dc, WorkIcon icon, int x, int y, int extent = 17) { 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); } @@ -393,12 +444,17 @@ 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) { @@ -475,6 +531,8 @@ std::span work_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 {}; @@ -539,7 +597,7 @@ DockLayout measure_command_dock(int width, int height, int scale, bool position_ 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(compact ? 30 : 36); + 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); @@ -558,7 +616,7 @@ void update_dock_font() { 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}) set_font(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); @@ -639,6 +697,7 @@ void set_work_panel(HWND window, WorkPanel panel) { const auto& choice = choices[index]; SetWindowTextW(button, choice.command == cabin_button_id && world && !world->scenario_active() ? L"Чертёж домика" : choice.title); + EnableWindow(button, choice.command != craft_door_id || (world && world->scenario_active())); ShowWindow(button, SW_SHOWNA); } for (const auto button : dock_section_buttons) InvalidateRect(button, nullptr, FALSE); @@ -649,7 +708,8 @@ void set_work_panel(HWND window, WorkPanel panel) { InvalidateRect(window, &row, FALSE); } -void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bool dock = false, int icon_width = 17) { +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; @@ -681,7 +741,9 @@ void draw_icon_button(const DRAWITEMSTRUCT& item, WorkIcon icon, bool active, bo 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, icon_width); + 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); @@ -708,15 +770,24 @@ bool draw_toolbar_button(const DRAWITEMSTRUCT& item) { 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); + 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)]; - return draw(choice.icon, placement_mode == choice.mode); + 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() { @@ -795,6 +866,7 @@ void update_status() { 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); @@ -803,11 +875,13 @@ void update_status() { 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(); @@ -818,7 +892,7 @@ void update_status() { for (const HWND button : dock_section_buttons) EnableWindow(button, can_play); EnableWindow(priority_button, scenario && can_play); EnableWindow(work_list_button, can_play); - EnableWindow(build_blueprint_button, has_blueprint() && 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"Сначала стройка"; @@ -871,7 +945,7 @@ 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()); + EnableWindow(build_blueprint_button, has_blueprint() && can_give_orders() && !room_draft_move); EnableWindow(clear_blueprint_button, has_blueprint()); layout_command_dock(window); } @@ -881,6 +955,9 @@ void set_placement_mode(HWND window, PlacementMode mode, const wchar_t* message 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(); @@ -893,6 +970,7 @@ void clear_blueprints() { blueprint.clear(); room_blueprints.clear(); room_anchor.reset(); + room_draft_move.reset(); } void toggle_work_panel(HWND window, WorkPanel panel) { @@ -1305,22 +1383,43 @@ bool valid_edit_cell(settlement::GridPosition cell) { 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) { +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 room.first.x <= other.last.x && room.last.x >= other.first.x && + 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) { - auto room = settlement::make_room_plan(*room_anchor, 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; @@ -1331,10 +1430,36 @@ settlement::RoomPlan preview_room(settlement::GridPosition cell) { return room; } -void edit_room_blueprint(HWND window, settlement::GridPosition cell) { +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_anchor) { + 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 клеток."; @@ -1345,23 +1470,40 @@ void edit_room_blueprint(HWND window, settlement::GridPosition cell) { room_anchor.reset(); placement_message.clear(); } - } else if (const auto room = room_at(cell); room != room_blueprints.end()) { - auto candidate = *room; - if (cell.y == room->first.y) candidate.entrance = RoomSide::North; - else if (cell.y == room->last.y) candidate.entrance = RoomSide::South; - else if (cell.x == room->first.x) candidate.entrance = RoomSide::West; - else if (cell.x == room->last.x) candidate.entrance = RoomSide::East; + } else 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)) { - *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(); @@ -1401,12 +1543,12 @@ void edit_blueprint(HWND window, settlement::GridPosition cell) { } void submit_blueprint(HWND window) { - if (!world || !has_blueprint() || !can_give_orders()) return; + 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, - static_cast(room.entrance), room.last) == settlement::CommandStatus::Accepted; + room.placement_value(), room.last) == settlement::CommandStatus::Accepted; }); const auto objects_sent = std::erase_if(blueprint, [](const auto& part) { switch (part.recipe) { @@ -1435,6 +1577,9 @@ void submit_blueprint(HWND window) { } 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); @@ -1506,9 +1651,11 @@ void edit_at_cell(HWND window, settlement::GridPosition cell) { 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); + 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; @@ -1546,7 +1693,7 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, }; 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); + 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"Профессия"; @@ -1566,10 +1713,10 @@ LRESULT CALLBACK resident_roster_proc(HWND window, UINT message, WPARAM wparam, 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); + 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, 301, 103, 26); + 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; @@ -1660,7 +1807,7 @@ void show_resident_roster(HWND owner) { 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}; + RECT area{0, 0, 566, 377}; AdjustWindowRectEx(&area, style, FALSE, ex_style); RECT owner_rect{}; GetWindowRect(owner, &owner_rect); @@ -1709,7 +1856,7 @@ std::wstring resident_details() { 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::Flax, L"лён"}, {ItemType::WoodenDoor, L"деревянная дверь"} }; std::wstring cargo; for (const auto& [type, name] : items) { @@ -1723,6 +1870,11 @@ std::wstring resident_details() { 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 && + world->production_orders()[resident->production_index].recipe == settlement::RecipeId::CraftWoodenDoor) { + 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]; @@ -1759,7 +1911,8 @@ std::wstring blueprint_details() { const wchar_t* name; }; constexpr Material materials[] = {{ItemType::Wood, L"дерево"}, {ItemType::Stone, L"камень"}, - {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}}; + {ItemType::Cloth, L"ткань"}, {ItemType::Plank, L"доски"}, {ItemType::StoneBlock, L"каменные блоки"}, + {ItemType::WoodenDoor, L"готовые двери"}}; std::array totals{}; for (const auto& part : blueprint) { for (const auto& material : world->construction_materials(part.recipe, part.base)) { @@ -1769,10 +1922,18 @@ std::wstring blueprint_details() { for (const auto& room : room_blueprints) { for (int y = room.first.y; y <= room.last.y; ++y) { for (int x = room.first.x; x <= room.last.x; ++x) { - const auto ingredients = world->construction_materials(room.recipe_at({x, y}), settlement::BedBase::Wood); + 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) { + for (const auto& item : world->construction_materials(part.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) { @@ -1829,18 +1990,41 @@ void draw_world(HDC dc, int width, int height) { } else if (placement_mode == PlacementMode::Demolish) { hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена."; } else if (placement_mode == PlacementMode::Room) { - hint = room_anchor ? L"Укажите противоположный угол комнаты." : - L"Укажите первый угол. Щелчок по краю чертежа меняет вход, правый щелчок удаляет комнату."; + 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"Плотник делает дверь из двух единиц дерева. При подтверждении дома заказ создаётся автоматически."; } 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); - const auto details = has_blueprint() ? blueprint_details() : resident_details(); + 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 order.recipe == settlement::RecipeId::CraftWoodenDoor && order.state != settlement::JobState::Completed; + }); + details = L"Заказов на двери " + std::to_wstring(orders); + 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); @@ -1852,11 +2036,14 @@ settlement::viewer::SceneView scene_view(int width, int height) { const auto scale = camera.scale(); const auto cursor = !shows_bed_choices() || selected_bed_base ? hover_cell : std::nullopt; std::optional room_preview; - if (cursor && room_anchor && placement_mode == PlacementMode::Room) { + 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 bool valid_cursor = room_preview ? world->can_place_room(*room_preview) && room_fits_blueprint(*room_preview) + 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() && @@ -1865,7 +2052,8 @@ settlement::viewer::SceneView scene_view(int width, int height) { 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}; + 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) { @@ -2159,6 +2347,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); @@ -2221,6 +2415,20 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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 (LOWORD(wparam) == craft_door_id && HIWORD(wparam) == BN_CLICKED && + world && world->carpenter_workshop() && can_give_orders()) { + if (send_command(settlement::CommandKind::CraftDoor)) { + 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) { @@ -2258,6 +2466,14 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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); @@ -2265,7 +2481,33 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp return 0; } if (LOWORD(wparam) == room_tool_id && HIWORD(wparam) == BN_CLICKED && world && can_give_orders()) { - set_placement_mode(window, placement_mode == PlacementMode::Room ? PlacementMode::None : PlacementMode::Room); + 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; } @@ -2378,7 +2620,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } if (world && is_blueprint_tool()) { if (const auto cell = map_cell(client, point)) { - if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell); + if (placement_mode == PlacementMode::Room) edit_room_blueprint(window, *cell, (wparam & MK_SHIFT) != 0); else edit_blueprint(window, *cell); } return 0; @@ -2398,6 +2640,13 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp } 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(); @@ -2425,6 +2674,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp 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 : @@ -2465,8 +2719,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp using settlement::RecipeId; const bool bed = rejection->kind == CommandKind::PlaceBed; if (rejection->kind == CommandKind::PlaceRoom) { - const settlement::RoomPlan room{rejection->cell, rejection->destination, - static_cast(rejection->value)}; + 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); diff --git a/build.ps1 b/build.ps1 index f27b088..7422c22 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,59 +1,49 @@ param( [ValidateSet('Debug', 'Release', 'RelWithDebInfo')] - [string]$Configuration = 'Release' + [string]$Configuration = 'Release', + [string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT ) $ErrorActionPreference = 'Stop' -$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path -$toolRoot = Join-Path $projectRoot '.tools\toolchain' - -if (-not (Test-Path -LiteralPath $toolRoot -PathType Container)) { - throw 'Portable tools are missing. Run .\setup-toolchain.ps1 first.' -} - -$cmakeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'cmake') -Filter 'cmake.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$clangxxExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'clang++.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$ninjaExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'ninja.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -$makeExe = Get-ChildItem -LiteralPath (Join-Path $toolRoot 'llvm-mingw') -Filter 'mingw32-make.exe' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - -if ($null -eq $cmakeExe -or $null -eq $clangxxExe) { - throw 'CMake or Clang is missing. Run .\setup-toolchain.ps1 again.' -} - -$compilerBin = Split-Path -Parent $clangxxExe.FullName -$cmakeBin = Split-Path -Parent $cmakeExe.FullName -$env:Path = "$compilerBin;$cmakeBin;$env:Path" -$buildDirectory = Join-Path $projectRoot 'build' -$generatorArguments = @() -if ($null -ne $ninjaExe) { - $generatorArguments = @('-G', 'Ninja', "-DCMAKE_MAKE_PROGRAM=$($ninjaExe.FullName)") -} elseif ($null -ne $makeExe) { - $generatorArguments = @('-G', 'MinGW Makefiles', "-DCMAKE_MAKE_PROGRAM=$($makeExe.FullName)") -} else { - throw 'The LLVM-MinGW archive contains neither Ninja nor mingw32-make.' -} - -& $cmakeExe.FullName -S $projectRoot -B $buildDirectory @generatorArguments -U CMAKE_C_COMPILER ` - "-DCMAKE_CXX_COMPILER=$($clangxxExe.FullName)" ` - "-DCMAKE_BUILD_TYPE=$Configuration" -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - -& $cmakeExe.FullName --build $buildDirectory --parallel --config $Configuration -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - -# LLVM-MinGW links libc++ dynamically. Copy its runtime beside the executables -# so they can be launched from Explorer without editing the system PATH. -foreach ($runtimeName in @('libc++.dll', 'libunwind.dll')) { - $runtimeSource = Join-Path $compilerBin $runtimeName - if (-not (Test-Path -LiteralPath $runtimeSource -PathType Leaf)) { - throw "Required LLVM-MinGW runtime was not found: $runtimeSource" +$projectRoot = $PSScriptRoot +if (-not $Msys2Root) { $Msys2Root = Join-Path $projectRoot '.tools\toolchain\msys64' } +$bin = Join-Path $Msys2Root 'ucrt64\bin' +foreach ($tool in @('g++.exe', 'cmake.exe', 'ctest.exe', 'ninja.exe', 'windres.exe')) { + if (-not (Test-Path -LiteralPath (Join-Path $bin $tool) -PathType Leaf)) { + throw "MSYS2 UCRT64 tool missing: $tool. Run .\setup-toolchain.ps1." } - Copy-Item -LiteralPath $runtimeSource -Destination $buildDirectory -Force } +$bin = (Get-Item -LiteralPath $bin).FullName.Replace('\', '/') +$buildRoot = Join-Path $projectRoot 'build' +$buildDirectory = Join-Path $buildRoot 'msys2-ucrt64' +$previousPath = $env:Path +try { + $env:Path = "$bin;$previousPath" + $version = & (Join-Path $bin 'g++.exe') -dumpfullversion + if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { + throw "MSYS2 UCRT64 GCC 16 is required. Found: $version" + } + Write-Output "Building with MSYS2 UCRT64 GCC $version" + $cmake = Join-Path $bin 'cmake.exe' + $options = @('-S', $projectRoot, '-B', $buildDirectory, '-G', 'Ninja', + "-DCMAKE_CXX_COMPILER=$bin/g++.exe", + "-DCMAKE_RC_COMPILER=$bin/windres.exe", + "-DCMAKE_MAKE_PROGRAM=$bin/ninja.exe", + "-DCMAKE_BUILD_TYPE=$Configuration", '-DBUILD_TESTING=ON') + & $cmake @options + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $cmake --build $buildDirectory --parallel + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & (Join-Path $bin 'ctest.exe') --test-dir $buildDirectory --output-on-failure + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } -$ctestExe = Join-Path $cmakeBin 'ctest.exe' -if (-not (Test-Path -LiteralPath $ctestExe -PathType Leaf)) { - throw 'CTest was not found beside CMake.' + foreach ($runtime in @('libstdc++-6.dll', 'libgcc_s_seh-1.dll', 'libwinpthread-1.dll')) { + Copy-Item -LiteralPath (Join-Path $bin $runtime) -Destination $buildRoot -Force + } + foreach ($program in @('settlement_viewer', 'settlement_sim', 'settlement_colony_benchmark', + 'settlement_core_tests', 'settlement_lan_tests')) { + Copy-Item -LiteralPath (Join-Path $buildDirectory "$program.exe") -Destination $buildRoot -Force + } +} finally { + $env:Path = $previousPath } -& $ctestExe --test-dir $buildDirectory -C $Configuration --output-on-failure -exit $LASTEXITCODE diff --git a/docs/viewer.md b/docs/viewer.md index fcbc993..38815eb 100644 --- a/docs/viewer.md +++ b/docs/viewer.md @@ -20,7 +20,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 Нажмите «Начать стройку», чтобы отправить выбранные места в работу, или «Очистить чертёж», чтобы убрать всю раскладку. Чертёж остаётся доступным при смене инструмента и через Esc. Это локальная раскладка текущей партии. В сохранение и общую колонию попадают утверждённые постройки. Если хозяин отклоняет клетку в кооперативе, она возвращается в чертёж. -В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево и собирают пол, стены и проём по частям. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. +В разделе «Строительство → Комната» укажите два противоположных угла прямоугольника от 3×3 до 12×12 клеток. По краям чертежа появятся стены, внутри — пол. Щёлкните по стороне, чтобы перенести вход в её середину. Правый щелчок по чертежу удаляет комнату. «Начать стройку» отправляет комнату в работу целиком. Поселенцы доставляют дерево для пола и стен. На готовый пол можно поставить мебель. В этой версии маршруты жителей проходят через стены. + +В нижней панели «Строительство → Готовые дома» выберите проект 4×4 по картинке. В доме врача есть деревянная кровать и аптечный шкаф, в доме шахтёра — каменная кровать и стойка с инструментами, в доме ткача — деревянная кровать и рабочий ткацкий станок. Укажите площадку одним щелчком. Щелчок по краю переносит вход и переставляет мебель к противоположной стене. Смета включает мебель, а строители собирают её после укладки пола под ней. Аптечный шкаф и стойка служат обстановкой. + +Когда пол, стены и вход готовы, у комнаты появляется крыша. Кнопка «Вид» в правом верхнем углу карты переключает полный вид, вид без крыш и вид без стен и крыш. Последний режим оставляет открытыми полы и мебель. Следующее нажатие возвращает полный вид. + +Клавиша R поворачивает вход и раскладку готового дома ещё до размещения. Клавиши «,» и «.» поворачивают в обе стороны. Чтобы перенести уже поставленный чертёж, щёлкните по нему с Shift, затем укажите новое место. Правый щелчок во время переноса возвращает чертёж на старое место. + +Новые комнаты и готовые дома требуют деревянную дверь как предмет. Если на складе нет свободной двери, «Начать стройку» автоматически ставит заказ в мастерскую. В списке «Жители» назначьте плотника. Он заберёт со склада две единицы дерева, сделает дверь за верстаком и отнесёт её на склад. Строитель или разнорабочий заберёт оттуда готовую дверь и установит её. Чтобы заготовить двери заранее, откройте «Работы → Плотник» и выберите «Изготовить дверь». Жители отдельно доставляют основу, ткань для настила и ткань для подушки. Каждая деталь появляется после завершения своего этапа. Камень и ткань доступны в стартовых запасах. Жители получают по одному готовому месту. diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp index 6748972..eb81080 100644 --- a/engine/include/settlement/core/world.hpp +++ b/engine/include/settlement/core/world.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -51,9 +52,10 @@ enum class ItemType : std::uint8_t { StoneBlock, Berries, Cloth, - Flax + Flax, + WoodenDoor }; -inline constexpr std::size_t item_type_count = static_cast(ItemType::Flax); +inline constexpr std::size_t item_type_count = static_cast(ItemType::WoodenDoor); enum class StorageKind : std::uint8_t { Materials, Pantry }; enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField }; @@ -78,33 +80,68 @@ enum class RecipeId : std::uint8_t { BuildFloor, BuildWall, BuildDoorAlongX, - BuildDoorAlongY + BuildDoorAlongY, + BuildMedicineCabinet, + BuildMiningRack, + BuildLoom, + InstallDoorAlongX, + InstallDoorAlongY, + CraftWoodenDoor }; enum class BedBase : std::uint8_t { Wood, Stone }; enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; +constexpr RecipeId room_part_shape(RecipeId recipe) noexcept { + if (recipe == RecipeId::InstallDoorAlongX) return RecipeId::BuildDoorAlongX; + if (recipe == RecipeId::InstallDoorAlongY) return RecipeId::BuildDoorAlongY; + return recipe; +} + +constexpr bool is_room_part(RecipeId recipe) noexcept { + recipe = room_part_shape(recipe); + return recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY; +} + constexpr bool is_construction(RecipeId recipe) noexcept { return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed || - (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::BuildDoorAlongY); + (recipe >= RecipeId::BuildFloor && recipe <= RecipeId::InstallDoorAlongY); +} + +constexpr bool delivers_materials(RecipeId recipe) noexcept { + return is_construction(recipe) || recipe == RecipeId::CraftWoodenDoor; } enum class RoomSide : std::uint8_t { North, East, South, West }; +enum class RoomTemplate : std::uint8_t { Empty, Doctor, Miner, Weaver }; +inline constexpr int furnished_room_size = 4; + +struct RoomFurnishing { + GridPosition position; + RecipeId recipe; + BedBase bed_base = BedBase::Wood; +}; + struct RoomPlan { GridPosition first; GridPosition last; RoomSide entrance = RoomSide::South; + RoomTemplate layout = RoomTemplate::Empty; [[nodiscard]] bool valid_size() const noexcept; [[nodiscard]] bool contains(GridPosition cell) const noexcept; [[nodiscard]] RecipeId recipe_at(GridPosition cell) const noexcept; + [[nodiscard]] std::optional> furnishings() const noexcept; + [[nodiscard]] std::uint8_t placement_value() const noexcept; + [[nodiscard]] static RoomPlan from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept; }; [[nodiscard]] RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept; enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; -enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; +enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder, Carpenter }; enum class CommandKind : std::uint8_t { PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, - PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13 + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12, PlaceRoom = 13, + CraftDoor = 14 }; enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; @@ -234,6 +271,13 @@ struct Storage { return 0; } + [[nodiscard]] std::uint32_t available_item_count(ItemType type) const noexcept { + for (const ItemStack& stack : items) { + if (stack.type == type) return stack.count - stack.reserved; + } + return 0; + } + [[nodiscard]] std::uint64_t total_items() const noexcept { std::uint64_t total = 0; for (const ItemStack& stack : items) total += stack.count; @@ -291,6 +335,11 @@ public: [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; [[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept; [[nodiscard]] std::array construction_materials(RecipeId recipe, BedBase base) const; + [[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept; + [[nodiscard]] std::optional carpenter_workshop() const noexcept { + if (!scenario_active_) return std::nullopt; + return scenario_sawmill_; + } void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); void start_scenario(GridPosition sawmill); [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); @@ -348,6 +397,7 @@ private: void finish_rest_step(Agent& agent); void advance_construction_delivery(Agent& agent); void finish_production(Agent& agent); + [[nodiscard]] std::size_t missing_door_orders(std::size_t new_installations = 0) const; void update_scenario(); [[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept; [[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept; diff --git a/engine/src/world.cpp b/engine/src/world.cpp index 6458412..10b05e2 100644 --- a/engine/src/world.cpp +++ b/engine/src/world.cpp @@ -69,6 +69,12 @@ const Recipe& recipe_for(RecipeId id) { static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6}; static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9}; static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10}; + static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}}, + ItemType::None, 10}; + static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12}; + static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8}; + static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14}; switch (id) { case RecipeId::SawPlank: return saw; case RecipeId::CutStoneBlock: return cut; @@ -79,6 +85,12 @@ const Recipe& recipe_for(RecipeId id) { case RecipeId::BuildWall: return wall; case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongY: return door; + case RecipeId::BuildMedicineCabinet: return cabinet; + case RecipeId::BuildMiningRack: return mining_rack; + case RecipeId::BuildLoom: return loom; + case RecipeId::InstallDoorAlongX: + case RecipeId::InstallDoorAlongY: return install_door; + case RecipeId::CraftWoodenDoor: return craft_door; } throw std::invalid_argument("unknown production recipe"); } @@ -143,7 +155,9 @@ RoomPlan make_room_plan(GridPosition first, GridPosition last) noexcept { bool RoomPlan::valid_size() const noexcept { const auto width = static_cast(last.x) - first.x + 1; const auto height = static_cast(last.y) - first.y + 1; - return width >= 3 && width <= 12 && height >= 3 && height <= 12 && entrance <= RoomSide::West; + if (entrance > RoomSide::West || layout > RoomTemplate::Weaver) return false; + if (layout == RoomTemplate::Empty) return width >= 3 && width <= 12 && height >= 3 && height <= 12; + return width == furnished_room_size && height == furnished_room_size; } bool RoomPlan::contains(GridPosition cell) const noexcept { @@ -167,6 +181,29 @@ RecipeId RoomPlan::recipe_at(GridPosition cell) const noexcept { return RecipeId::BuildFloor; } +std::optional> RoomPlan::furnishings() const noexcept { + if (layout == RoomTemplate::Empty || !valid_size()) return std::nullopt; + // Keep the entry aisle clear by placing both pieces against the back wall. + const GridPosition bed_offsets[] = {{1, 2}, {1, 1}, {1, 1}, {2, 1}}; + const GridPosition fixture_offsets[] = {{2, 2}, {1, 2}, {2, 1}, {2, 2}}; + const RecipeId fixtures[] = {RecipeId::BuildMedicineCabinet, RecipeId::BuildMiningRack, RecipeId::BuildLoom}; + const auto side = static_cast(entrance); + const auto bed = bed_offsets[side]; + const auto fixture = fixture_offsets[side]; + return std::array{RoomFurnishing{{first.x + bed.x, first.y + bed.y}, RecipeId::BuildBed, + layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood}, + RoomFurnishing{{first.x + fixture.x, first.y + fixture.y}, + fixtures[static_cast(layout) - 1]}}; +} + +std::uint8_t RoomPlan::placement_value() const noexcept { + return static_cast((static_cast(layout) << 2) | static_cast(entrance)); +} + +RoomPlan RoomPlan::from_placement(GridPosition first, GridPosition last, std::uint8_t value) noexcept { + return {first, last, static_cast(value & 3U), static_cast(value >> 2)}; +} + std::uint32_t Inventory::item_count(ItemType type) const noexcept { const auto index = static_cast(type); return index != 0 && index <= counts_.size() ? counts_[index - 1] : 0; @@ -263,8 +300,14 @@ void World::set_blocked(GridPosition position, bool blocked) { } } for (const Agent& agent : agents_) { + if (agent.production_index != no_entity_index && + production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor && + std::find(agent.haul_route.begin(), agent.haul_route.end(), position) != agent.haul_route.end()) { + throw std::logic_error("cannot block the carpenter's delivery route"); + } if (agent.production_index == no_entity_index && - agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) continue; + agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep && + agent.inventory.item_count(ItemType::WoodenDoor) == 0) continue; const auto remaining = agent.route.begin() + static_cast(agent.route_cursor); if (std::find(remaining, agent.route.end(), position) != agent.route.end()) { throw std::logic_error("cannot block an active production, meal, or sleep route"); @@ -357,6 +400,9 @@ void World::queue_production(GridPosition position, RecipeId recipe) { if (!is_walkable(position)) { throw std::invalid_argument("production site must be on a walkable cell"); } + if (recipe == RecipeId::CraftWoodenDoor && carpenter_workshop() != position) { + throw std::invalid_argument("wooden doors need the carpenter's workshop"); + } if (is_production_object(recipe) && !can_place_storage(position)) { throw std::invalid_argument("the production site is occupied"); } @@ -382,7 +428,8 @@ bool World::can_place_cabin(GridPosition position) const noexcept { } bool World::can_place_room(const RoomPlan& plan) const noexcept { - if (!plan.valid_size() || !is_walkable(plan.first) || !is_walkable(plan.last)) return false; + if (!plan.valid_size() || (plan.layout != RoomTemplate::Empty && !scenario_active_) || + !is_walkable(plan.first) || !is_walkable(plan.last)) return false; const int middle_x = std::midpoint(plan.first.x, plan.last.x); const int middle_y = std::midpoint(plan.first.y, plan.last.y); const GridPosition exits[] = {{middle_x, plan.first.y - 1}, {plan.last.x + 1, middle_y}, @@ -413,6 +460,35 @@ std::array World::construction_materials(RecipeId recipe, BedBase return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array{}; } +RecipeId World::room_construction_recipe(RecipeId part) const noexcept { + if (scenario_active_) { + if (part == RecipeId::BuildDoorAlongX) return RecipeId::InstallDoorAlongX; + if (part == RecipeId::BuildDoorAlongY) return RecipeId::InstallDoorAlongY; + } + return part; +} + +std::size_t World::missing_door_orders(std::size_t new_installations) const { + std::uint64_t waiting_installations = new_installations, supply = 0; + for (const auto& order : production_orders_) { + if (order.recipe == RecipeId::CraftWoodenDoor && order.state != JobState::Completed) ++supply; + if (order.state == JobState::Available && + (order.recipe == RecipeId::InstallDoorAlongX || order.recipe == RecipeId::InstallDoorAlongY)) { + ++waiting_installations; + } + } + for (const auto& agent : agents_) { + if (agent.state == AgentState::Hauling && agent.production_index == no_entity_index) { + supply += agent.inventory.item_count(ItemType::WoodenDoor); + } + } + for (const auto& storage : storages_) { + const auto available = storage.available_item_count(ItemType::WoodenDoor); + if (available != 0 && find_path(scenario_sawmill_, storage.position).reachable) supply += available; + } + return waiting_installations > supply ? static_cast(waiting_installations - supply) : 0; +} + void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { if (!can_place_cabin(position) || position == sawmill || position == stonecutter || (scenario_active_ && position == scenario_sawmill_)) { @@ -485,7 +561,7 @@ CommandStatus World::object_status(GridPosition position, bool moving) const noe for (const auto& order : production_orders_) { if (order.position != position || !is_production_object(order.recipe)) continue; if (is_finished_floor(order)) continue; - if (moving && order.recipe >= RecipeId::BuildFloor) return CommandStatus::InvalidTarget; + if (moving && is_room_part(order.recipe)) return CommandStatus::InvalidTarget; return order.state == JobState::InProgress || resting_at(position) ? busy : ready; } for (std::size_t i = 0; i < storages_.size(); ++i) { @@ -537,6 +613,7 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest if (storage != storages_.end()) { if (destination) storage->position = *destination; else { + const bool loses_doors = storage->item_count(ItemType::WoodenDoor) != 0; const auto removed = static_cast(storage - storages_.begin()); storages_.erase(storage); for (auto& agent : agents_) shift_index(agent.storage_index, removed); @@ -544,6 +621,10 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest for (auto& material : entry.materials) shift_index(material.storage_index, removed); for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed); } + if (scenario_active_ && loses_doors) { + const auto missing = missing_door_orders(); + for (std::size_t i = 0; i < missing; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); + } } return CommandStatus::Accepted; } @@ -661,23 +742,42 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { } queue_production(command.cell, RecipeId::WeaveCloth); break; + case CommandKind::CraftDoor: + queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); + break; case CommandKind::PlaceRoom: { - const RoomPlan plan{command.cell, command.destination, static_cast(command.value)}; + const auto plan = RoomPlan::from_placement(command.cell, command.destination, command.value); if (!can_place_room(plan) || !can_reach_object_cell(plan.first)) { return receipt(CommandStatus::InvalidTarget); } const auto width = static_cast(plan.last.x - plan.first.x + 1); const auto height = static_cast(plan.last.y - plan.first.y + 1); - production_orders_.reserve(production_orders_.size() + width * height); + const auto furnishings = plan.furnishings(); + const bool legacy_bed = furnishings.has_value() && !staged_beds_; + const auto door_orders = scenario_active_ ? missing_door_orders(1) : 0; + production_orders_.reserve(production_orders_.size() + width * height + + (furnishings ? furnishings->size() : 0) + (legacy_bed ? 1U : 0U) + door_orders); + if (legacy_bed) queue_production(scenario_sawmill_, RecipeId::SawPlank); + if (furnishings) { + for (const auto& part : *furnishings) { + ProductionOrder order{}; + order.position = part.position; + order.recipe = part.recipe; + order.bed_base = part.bed_base; + if (order.recipe == RecipeId::BuildBed && staged_beds_) order.bed_stage = BedStage::Foundation; + production_orders_.push_back(std::move(order)); + } + } for (int y = plan.first.y; y <= plan.last.y; ++y) { for (int x = plan.first.x; x <= plan.last.x; ++x) { const GridPosition cell{x, y}; ProductionOrder order{}; order.position = cell; - order.recipe = plan.recipe_at(cell); + order.recipe = room_construction_recipe(plan.recipe_at(cell)); production_orders_.push_back(std::move(order)); } } + for (std::size_t i = 0; i < door_orders; ++i) queue_production(scenario_sawmill_, RecipeId::CraftWoodenDoor); break; } case CommandKind::PlaceStorage: @@ -695,7 +795,7 @@ CommandReceipt World::apply_command(const PlayerCommand& command) { break; } case CommandKind::AssignProfession: { - if (command.value > static_cast(Profession::Builder) || command.resident == 0) { + if (command.value > static_cast(Profession::Carpenter) || command.resident == 0) { return receipt(CommandStatus::InvalidTarget); } const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident, @@ -1004,10 +1104,11 @@ void World::assign_resource_tasks(ResourceFocus focus) { } for (Agent& agent : agents_) { if (open_pantry_count == 0 && open_material_store_count == 0 && untended_sites == 0) break; - if (agent.profession == Profession::Builder || agent.state != AgentState::Idle || agent.current_job != 0 || + const auto profession = static_cast(agent.profession); + if (profession >= available.size() || agent.state != AgentState::Idle || agent.current_job != 0 || !agent.inventory.empty()) continue; - const auto& candidates = available[static_cast(agent.profession)]; + const auto& candidates = available[profession]; if (candidates.empty()) continue; std::vector tried_nodes(candidates.size(), 0); for (;;) { @@ -1099,7 +1200,8 @@ void World::assign_production_tasks(bool weaving) { if (production_orders_.empty() || storages_.empty() || std::none_of(agents_.begin(), agents_.end(), [](const Agent& agent) { - return agent.state == AgentState::Idle && can_take_work(agent, Profession::Builder); + return agent.state == AgentState::Idle && + (can_take_work(agent, Profession::Builder) || agent.profession == Profession::Carpenter); })) return; for (std::size_t index = 0; index < production_orders_.size(); ++index) { ProductionOrder& order = production_orders_[index]; @@ -1107,15 +1209,18 @@ void World::assign_production_tasks(bool weaving) { const bool site_busy = std::any_of(production_orders_.begin(), production_orders_.end(), [&order](const ProductionOrder& other) { - return other.state == JobState::InProgress && - other.position.x == order.position.x && other.position.y == order.position.y; + return other.position == order.position && + (other.state == JobState::InProgress || + (order.recipe != RecipeId::BuildFloor && other.recipe == RecipeId::BuildFloor && + other.state != JobState::Completed)); }); if (site_busy) continue; const Recipe recipe = recipe_for(order); - const bool construction = is_construction(order.recipe); + const bool door_craft = order.recipe == RecipeId::CraftWoodenDoor; + const bool deliver_ingredients = delivers_materials(order.recipe); enum class Access { Unknown, Reachable, Unreachable }; - std::vector storage_access(construction || weaving ? storages_.size() : 0, Access::Unknown); + std::vector storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown); std::vector materials; bool supplied = true; for (const ItemStack& ingredient : recipe.ingredients) { @@ -1146,7 +1251,7 @@ void World::assign_production_tasks(bool weaving) { if (!supplied) continue; std::vector stops; - if (construction) { + if (deliver_ingredients) { for (std::size_t s = 0; s < storage_access.size(); ++s) { if (storage_access[s] == Access::Reachable) stops.push_back({s, {}}); } @@ -1160,12 +1265,18 @@ void World::assign_production_tasks(bool weaving) { stops[i].route_to_next = std::move(path.positions); } } - const GridPosition destination = construction + const GridPosition destination = deliver_ingredients ? storages_[stops.front().storage_index].position : order.position; for (Agent& agent : agents_) { - if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue; + const bool can_craft = agent.profession == Profession::Carpenter; + const bool eligible = door_craft ? can_craft : + can_take_work(agent, Profession::Builder) || (can_craft && order.recipe == RecipeId::SawPlank); + if (agent.state != AgentState::Idle || !eligible) continue; auto path = assignment_path(agent.position, destination); if (!path.reachable) continue; + if (door_craft) { + agent.haul_route = assignment_path(order.position, storages_[materials.front().storage_index].position).positions; + } for (const auto& material : materials) { stack_position(storages_[material.storage_index], material.type)->reserved += material.count; @@ -1177,7 +1288,7 @@ void World::assign_production_tasks(bool weaving) { agent.route = std::move(path.positions); agent.route_cursor = 0; agent.work_remaining = recipe.ticks; - agent.state = construction ? AgentState::FetchingMaterials : + agent.state = deliver_ingredients ? AgentState::FetchingMaterials : (agent.route.empty() ? AgentState::Working : AgentState::Travelling); break; } @@ -1326,6 +1437,10 @@ void World::advance_construction_delivery(Agent& agent) { agent.inventory.add(material.type, material.count); } } + if (order.recipe == RecipeId::CraftWoodenDoor && stop.storage_index == order.materials.front().storage_index) { + // The wood just collected frees a slot for the completed door. + ++storages_[stop.storage_index].reserved_slots; + } ++order.collected_stops; agent.route = std::move(stop.route_to_next); agent.route_cursor = 0; @@ -1336,6 +1451,18 @@ void World::finish_production(Agent& agent) { ProductionOrder& order = production_orders_[agent.production_index]; const Recipe recipe = recipe_for(order); assert(!order.materials.empty()); + if (order.recipe == RecipeId::CraftWoodenDoor) { + agent.inventory.add(recipe.output); + agent.storage_index = order.materials.front().storage_index; + agent.route = std::move(agent.haul_route); + agent.haul_route.clear(); + agent.route_cursor = 0; + agent.production_index = no_entity_index; + agent.state = AgentState::Hauling; + order.materials.clear(); + order.state = JobState::Completed; + return; + } if (recipe.output != ItemType::None) { for (const auto& material : order.materials) { take_reserved_material(storages_[material.storage_index], material); @@ -1348,6 +1475,9 @@ void World::finish_production(Agent& agent) { (order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) { order.bed_stage = order.bed_stage == BedStage::Foundation ? BedStage::Bedding : BedStage::Pillow; order.state = JobState::Available; + } else if (order.recipe == RecipeId::BuildLoom) { + order.recipe = RecipeId::WeaveCloth; + order.state = JobState::Available; } else if (order.recipe == RecipeId::WeaveCloth) { order.state = JobState::Available; } else { diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp index 26e9cdc..f723d46 100644 --- a/engine/src/world_save.cpp +++ b/engine/src/world_save.cpp @@ -13,7 +13,7 @@ namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; -constexpr std::uint32_t save_version = 10; +constexpr std::uint32_t save_version = 12; constexpr std::uint32_t last_legacy_footer_version = 8; constexpr std::size_t max_records = 1'000'000; constexpr std::size_t max_save_bytes = 128 * 1024 * 1024; @@ -174,7 +174,7 @@ void flag(Archive& archive, Flag& value) { struct WorldSaveCodec { template static void body(Archive& archive, State& world, std::uint32_t version) { - const auto max_item = version >= 7 ? ItemType::Flax : ItemType::Cloth; + const auto max_item = version >= 12 ? ItemType::WoodenDoor : (version >= 7 ? ItemType::Flax : ItemType::Cloth); const auto max_item_count = static_cast(max_item); archive.field(world.tick_); archive.field(world.path_searches_); @@ -214,6 +214,7 @@ struct WorldSaveCodec { if (version >= 4) archive.field(agent.fatigue); if (version >= 5) flag(archive, agent.resting_on_ground); if (version >= 6) archive.field(agent.profession); + require_save(version >= 12 || agent.profession <= Profession::Builder, "Unknown profession for save version."); }); sequence(archive, world.jobs_, max_records, [&](auto& job) { archive.field(job.id); @@ -256,6 +257,8 @@ struct WorldSaveCodec { require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); require_save(version >= 10 || order.recipe <= RecipeId::WeaveCloth, "Unknown recipe for save version."); + require_save(version >= 11 || order.recipe <= RecipeId::BuildDoorAlongY, "Unknown recipe for save version."); + require_save(version >= 12 || order.recipe <= RecipeId::BuildLoom, "Unknown recipe for save version."); archive.field(order.state); sequence(archive, order.materials, item_types, [&](auto& material) { index(archive, material.storage_index); @@ -362,9 +365,10 @@ void WorldSaveCodec::validate(const World& world) { std::vector bed_owners; for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { const auto& order = world.production_orders_[i]; - invalid(order.recipe <= RecipeId::BuildDoorAlongY && order.state <= JobState::Completed && + invalid(order.recipe <= RecipeId::CraftWoodenDoor && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); + invalid(order.recipe != RecipeId::CraftWoodenDoor || world.carpenter_workshop() == order.position); invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && (order.bed_stage == BedStage::Legacy || (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && @@ -382,8 +386,8 @@ void WorldSaveCodec::validate(const World& world) { continue; } - const bool construction = is_construction(order.recipe); - invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty())); + const bool delivery = delivers_materials(order.recipe); + invalid(order.collected_stops <= order.delivery_stops.size() && (delivery || order.delivery_stops.empty())); std::size_t last_storage = 0; bool first_stop = true; for (const auto& stop : order.delivery_stops) { @@ -401,7 +405,7 @@ void WorldSaveCodec::validate(const World& world) { invalid(material.storage_index < world.storages_.size() && material.count > 0 && world.storages_[material.storage_index].kind == StorageKind::Materials); ingredients[type] += material.count; - if (!construction) { + if (!delivery) { reserved_items[material.storage_index][type] += material.count; } else if (!order.delivery_stops.empty()) { const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), @@ -425,10 +429,16 @@ void WorldSaveCodec::validate(const World& world) { break; case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; + case RecipeId::CraftWoodenDoor: required[item_index(ItemType::Wood)] = 2; break; case RecipeId::BuildFloor: case RecipeId::BuildWall: case RecipeId::BuildDoorAlongX: case RecipeId::BuildDoorAlongY: + case RecipeId::BuildMedicineCabinet: + case RecipeId::BuildMiningRack: + case RecipeId::BuildLoom: + case RecipeId::InstallDoorAlongX: + case RecipeId::InstallDoorAlongY: for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { if (item.count) required[item_index(item.type)] = item.count; } @@ -450,7 +460,7 @@ void WorldSaveCodec::validate(const World& world) { (world.hunger_enabled_ || agent.hunger == 0) && agent.fatigue <= max_fatigue && (world.scenario_active_ || agent.fatigue == 0)); invalid(!agent.resting_on_ground || agent.state == Sleeping || agent.state == GoingToSleep); - invalid(agent.profession <= Profession::Builder); + invalid(agent.profession <= Profession::Carpenter); valid_route(agent.route); valid_route(agent.haul_route); const bool has_job = agent.current_job != 0; @@ -458,7 +468,9 @@ void WorldSaveCodec::validate(const World& world) { const bool has_source = agent.resource_node_index != no_entity_index; const bool has_storage = agent.storage_index != no_entity_index; invalid(!has_storage || agent.storage_index < world.storages_.size()); - invalid(agent.haul_route.empty() || has_source); + const bool door_craft = has_order && agent.production_index < world.production_orders_.size() && + world.production_orders_[agent.production_index].recipe == RecipeId::CraftWoodenDoor; + invalid(agent.haul_route.empty() || has_source || door_craft); if (has_job) { invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); @@ -477,7 +489,13 @@ void WorldSaveCodec::validate(const World& world) { if (!order.delivery_stops.empty()) { invalid(agent.state == (order.collected_stops == 0 ? FetchingMaterials : Hauling)); } else { - invalid(agent.state == Working || (agent.state == Travelling && !is_construction(order.recipe))); + invalid(agent.state == Working || (agent.state == Travelling && !delivers_materials(order.recipe))); + } + if (door_craft) { + const auto storage = order.materials.front().storage_index; + const auto destination = world.storages_[storage].position; + invalid(agent.haul_route.empty() ? destination == order.position : agent.haul_route.back() == destination); + if (order.delivery_stops.empty() || order.collected_stops > 0) ++reserved_slots[storage]; } for (std::size_t i = 0; i < item_types; ++i) { invalid(agent.inventory.item_count(static_cast(i + 1)) == expected_cargo[agent.production_index][i]); @@ -497,7 +515,7 @@ void WorldSaveCodec::validate(const World& world) { } else if (agent.state == Hauling) { const auto cargo = agent.inventory.first_item(); invalid(has_storage && (cargo == ItemType::Wood || cargo == ItemType::Stone || - cargo == ItemType::Berries || cargo == ItemType::Flax) && + cargo == ItemType::Berries || cargo == ItemType::Flax || cargo == ItemType::WoodenDoor) && agent.inventory.item_count(cargo) == 1 && agent.work_remaining == 0 && world.storages_[agent.storage_index].accepts(cargo)); for (std::size_t i = 1; i <= item_types; ++i) { diff --git a/setup-toolchain.ps1 b/setup-toolchain.ps1 index cdf0930..42d1039 100644 --- a/setup-toolchain.ps1 +++ b/setup-toolchain.ps1 @@ -1,111 +1,57 @@ -param() +param([string]$Msys2Root = $env:SETTLEMENT_MSYS2_ROOT) $ErrorActionPreference = 'Stop' -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - -$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path -$toolRoot = Join-Path $projectRoot '.tools\toolchain' -$downloadRoot = Join-Path $projectRoot '.tools\downloads' -$cmakeVersion = '4.5.1' -$llvmVersion = '20261117' -$cmakeArchiveName = "cmake-$cmakeVersion-windows-x86_64.zip" -$cmakeHashName = "cmake-$cmakeVersion-SHA-256.txt" -$llvmArchiveName = "llvm-mingw-$llvmVersion-ucrt-x86_64.zip" - if (-not [Environment]::Is64BitOperatingSystem) { - throw 'This portable toolchain setup requires 64-bit Windows.' + throw 'MSYS2 UCRT64 requires 64-bit Windows.' } - -New-Item -ItemType Directory -Path $downloadRoot -Force | Out-Null -New-Item -ItemType Directory -Path $toolRoot -Force | Out-Null - -function Get-Download { - param( - [Parameter(Mandatory = $true)][string]$Uri, - [Parameter(Mandatory = $true)][string]$Destination - ) - - if (-not (Test-Path -LiteralPath $Destination -PathType Leaf)) { - Write-Host "Downloading $([System.IO.Path]::GetFileName($Destination))" - Invoke-WebRequest -Uri $Uri -OutFile $Destination -UseBasicParsing +$toolRoot = Join-Path $PSScriptRoot '.tools\toolchain' +$portableRoot = Join-Path $toolRoot 'msys64' +if (-not $Msys2Root) { $Msys2Root = $portableRoot } +$bash = Join-Path $Msys2Root 'usr\bin\bash.exe' +$bin = Join-Path $Msys2Root 'ucrt64\bin' +$compiler = Join-Path $bin 'g++.exe' +if ((Test-Path -LiteralPath $compiler -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $bin 'cmake.exe') -PathType Leaf) -and + (Test-Path -LiteralPath (Join-Path $bin 'ninja.exe') -PathType Leaf)) { + $version = & $compiler -dumpfullversion + if ($LASTEXITCODE -eq 0 -and $version -match '^16(\.|$)') { + Write-Output "MSYS2 UCRT64 GCC $version is ready." + return } } - -function Expand-IfMissing { - param( - [Parameter(Mandatory = $true)][string]$Archive, - [Parameter(Mandatory = $true)][string]$Destination, - [Parameter(Mandatory = $true)][string]$ExpectedExecutable - ) - - $existingExecutable = Get-ChildItem -LiteralPath $Destination -Filter $ExpectedExecutable -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($null -eq $existingExecutable) { - New-Item -ItemType Directory -Path $Destination -Force | Out-Null - Expand-Archive -LiteralPath $Archive -DestinationPath $Destination -Force +if (-not (Test-Path -LiteralPath $bash -PathType Leaf)) { + if ([IO.Path]::GetFullPath($Msys2Root) -ne [IO.Path]::GetFullPath($portableRoot)) { + throw "MSYS2 was not found at $Msys2Root." } -} - -$cmakeArchive = Join-Path $downloadRoot $cmakeArchiveName -$cmakeHashFile = Join-Path $downloadRoot $cmakeHashName -$cmakeBase = "https://github.com/Kitware/CMake/releases/download/v$cmakeVersion" -Get-Download -Uri "$cmakeBase/$cmakeArchiveName" -Destination $cmakeArchive -Get-Download -Uri "$cmakeBase/$cmakeHashName" -Destination $cmakeHashFile - -$escapedCmakeName = [regex]::Escape($cmakeArchiveName) -$hashText = Get-Content -LiteralPath $cmakeHashFile -Raw -$hashPatterns = @( - "(?im)^\s*([0-9a-f]{64})\s+\*?$escapedCmakeName\s*$", - "(?im)^\s*SHA-?256\s*\(\s*$escapedCmakeName\s*\)\s*[:=]\s*([0-9a-f]{64})\s*$", - "(?im)^\s*$escapedCmakeName\s*[: ]+\s*([0-9a-f]{64})\s*$" -) -$expectedCmakeHash = $null -foreach ($pattern in $hashPatterns) { - $match = [regex]::Match($hashText, $pattern) - if ($match.Success) { - $expectedCmakeHash = $match.Groups[1].Value.ToLowerInvariant() - break + $downloadRoot = Join-Path $PSScriptRoot '.tools\downloads' + New-Item -ItemType Directory -Path $downloadRoot, $toolRoot -Force | Out-Null + $name = 'msys2-base-x86_64-20261120.tar.zst' + $archive = Join-Path $downloadRoot $name + $expected = 'adde59fcb53760bd0fd2aa3c3e8da516f03159b771dc62b77c340e4ac187fcdd' + if (-not (Test-Path -LiteralPath $archive -PathType Leaf) -or + (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) { + Invoke-WebRequest -Uri "https://repo.msys2.org/distrib/x86_64/$name" -OutFile $archive -UseBasicParsing } -} -if (-not $expectedCmakeHash) { - throw "Could not read the official SHA-256 for $cmakeArchiveName. The archive was not extracted." -} -$actualCmakeHash = (Get-FileHash -LiteralPath $cmakeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -if ($actualCmakeHash -ne $expectedCmakeHash) { - throw "CMake archive SHA-256 mismatch. Expected $expectedCmakeHash, got $actualCmakeHash." -} - -$llvmArchive = Join-Path $downloadRoot $llvmArchiveName -$llvmReleaseUri = "https://api.github.com/repos/mstorsjo/llvm-mingw/releases/tags/$llvmVersion" -$llvmRelease = Invoke-RestMethod -Uri $llvmReleaseUri -Headers @{ 'User-Agent' = 'stonehearth-sim-toolchain-setup' } -$llvmAsset = $llvmRelease.assets | Where-Object { $_.name -eq $llvmArchiveName } | Select-Object -First 1 -if ($null -eq $llvmAsset) { - throw "The official llvm-mingw release $llvmVersion does not contain $llvmArchiveName." -} -Get-Download -Uri $llvmAsset.browser_download_url -Destination $llvmArchive - -if ($llvmAsset.digest -and $llvmAsset.digest -match '^sha256:([0-9a-fA-F]{64})$') { - $expectedLlvmHash = $Matches[1].ToLowerInvariant() - $actualLlvmHash = (Get-FileHash -LiteralPath $llvmArchive -Algorithm SHA256).Hash.ToLowerInvariant() - if ($actualLlvmHash -ne $expectedLlvmHash) { - throw "LLVM-MinGW archive SHA-256 mismatch. Expected $expectedLlvmHash, got $actualLlvmHash." + if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $expected) { + throw 'MSYS2 archive hash does not match the release.' } -} else { - Write-Warning 'GitHub did not publish a SHA-256 digest for this LLVM-MinGW asset; download is from the official release over HTTPS.' + & tar.exe -xf $archive -C $toolRoot + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } -$cmakeInstall = Join-Path $toolRoot 'cmake' -$llvmInstall = Join-Path $toolRoot 'llvm-mingw' -Expand-IfMissing -Archive $cmakeArchive -Destination $cmakeInstall -ExpectedExecutable 'cmake.exe' -Expand-IfMissing -Archive $llvmArchive -Destination $llvmInstall -ExpectedExecutable 'clang++.exe' - -$cmakeExe = Get-ChildItem -LiteralPath $cmakeInstall -Filter 'cmake.exe' -File -Recurse | Select-Object -First 1 -$clangxxExe = Get-ChildItem -LiteralPath $llvmInstall -Filter 'clang++.exe' -File -Recurse | Select-Object -First 1 -if ($null -eq $cmakeExe -or $null -eq $clangxxExe) { - throw 'Extraction completed, but CMake or Clang++ was not found in the toolchain folders.' +$previousMsysSystem = $env:MSYSTEM +try { + $env:MSYSTEM = 'UCRT64' + # An MSYS2 runtime upgrade can close the first shell. Start a fresh shell for the remaining packages. + & $bash --login -c 'pacman -Syu --noconfirm' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $bash --login -c 'pacman -Syu --needed --noconfirm mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +} finally { + $env:MSYSTEM = $previousMsysSystem } - -Write-Host "CMake: $($cmakeExe.FullName)" -& $cmakeExe.FullName --version | Select-Object -First 1 -Write-Host "C++ compiler: $($clangxxExe.FullName)" -& $clangxxExe.FullName --version | Select-Object -First 1 -Write-Host 'Portable toolchain is ready. Run .\build.ps1 to configure, build, and run CTest.' +$version = & $compiler -dumpfullversion +if ($LASTEXITCODE -ne 0 -or $version -notmatch '^16(\.|$)') { + throw "Expected GCC 16 in MSYS2 UCRT64. Found: $version" +} +Write-Output "MSYS2 UCRT64 GCC $version is ready." diff --git a/tests/core_tests.cpp b/tests/core_tests.cpp index bffadee..3ef6b6c 100644 --- a/tests/core_tests.cpp +++ b/tests/core_tests.cpp @@ -1,6 +1,9 @@ +#include "testing.hpp" + #include "settlement/core/deterministic_rng.hpp" #include "settlement/core/world.hpp" +#include #include #include #include @@ -30,7 +33,36 @@ std::unique_ptr save_roundtrip(const settlement::World& world return restored; } -void test_parallel_pathfinding_completes_the_jobs() { +using Void::Testing::Test; + +struct CoreTests : Void::Testing::Suite { + Test test_parallel_pathfinding_completes_the_jobs(); + Test test_single_worker_configuration_is_rejected(); + Test test_rng_repeats_for_same_seed(); + Test test_work_jobs_complete(); + Test test_astar_route_uses_opening_in_wall(); + Test test_residents_gather_and_deliver_resources(); + [[= Void::Testing::tag("construction")]] Test test_production_reservations_and_construction(); + [[= Void::Testing::tag("construction")]] Test test_cabin_placement_queues_a_complete_order(); + Test test_hungry_resident_reserves_and_eats_a_berry(); + Test test_invalid_save_is_rejected(); + Test test_two_players_share_the_first_colony(); + Test test_bed_parts_are_delivered_separately(); + Test test_resident_uses_assigned_bed_and_sleep_survives_save(); + Test test_fatigue_slows_work_without_interrupting_it(); + Test test_ground_rest_never_uses_another_residents_bed(); + Test test_fields_mines_and_reindexing_active_hauls(); + Test test_specialists_take_their_own_jobs_and_finish_prior_assignments(); + Test test_flax_and_loom_supply_a_bed_without_starting_cloth(); + Test test_field_growth_requires_a_worker(); + Test test_opening_a_mine_invalidates_unreachable_routes(); + Test test_object_tools_work_in_an_older_demo_world(); + [[= Void::Testing::tag("construction")]] Test test_room_builds_and_saves_as_separate_parts(); + [[= Void::Testing::tag("construction")]] Test test_furnished_rooms_queue_and_build_their_contents(); + [[= Void::Testing::tag("construction")]] Test test_carpenter_delivers_the_door_before_installation(); +}; + +Test CoreTests::test_parallel_pathfinding_completes_the_jobs() { settlement::World world(123, 48, 48, 6); for (std::int32_t y = 0; y < 48; ++y) { if (y != 31) world.set_blocked({24, y}); @@ -42,26 +74,28 @@ void test_parallel_pathfinding_completes_the_jobs() { } for (int tick = 0; tick < 120; ++tick) world.step(); require(world.jobs_completed() == 24, "parallel pathfinding did not finish every job"); + return {}; } -void test_single_worker_configuration_is_rejected() { +Test CoreTests::test_single_worker_configuration_is_rejected() { try { settlement::World world(8, 8, 8, 1); } catch (const std::invalid_argument&) { - return; + return {}; } throw std::runtime_error("world accepted a single worker"); } -void test_rng_repeats_for_same_seed() { +Test CoreTests::test_rng_repeats_for_same_seed() { settlement::DeterministicRng left(12345); settlement::DeterministicRng right(12345); for (int index = 0; index < 1000; ++index) { - require(left.next_u64() == right.next_u64(), "RNG diverged for matching seeds"); + expect_eq(left.next_u64(), right.next_u64()); } + return {}; } -void test_work_jobs_complete() { +Test CoreTests::test_work_jobs_complete() { settlement::World world(1, 10, 10); const settlement::AgentId agent_id = world.spawn_agent({1, 1}); const settlement::JobId job_id = world.add_job({3, 1}, 2); @@ -81,9 +115,10 @@ void test_work_jobs_complete() { "completed job retained an active state"); require(world.agents().front().state == settlement::AgentState::Idle, "worker did not return to idle after completing a job"); + return {}; } -void test_astar_route_uses_opening_in_wall() { +Test CoreTests::test_astar_route_uses_opening_in_wall() { settlement::World world(2, 10, 10); for (std::int32_t y = 0; y < 10; ++y) { if (y != 8) { @@ -103,9 +138,10 @@ void test_astar_route_uses_opening_in_wall() { } require(world.path_searches() > 0, "path search counter was not updated"); require(world.path_nodes_visited() > 0, "A* did not report expanded nodes"); + return {}; } -void test_residents_gather_and_deliver_resources() { +Test CoreTests::test_residents_gather_and_deliver_resources() { settlement::World world(51, 16, 16, 4); static_cast(world.add_storage({1, 1}, 10)); static_cast(world.spawn_agent({1, 2})); @@ -126,9 +162,10 @@ void test_residents_gather_and_deliver_resources() { "storage retained reservations after deliveries completed"); require(world.resource_nodes()[0].quantity == 0 && world.resource_nodes()[1].quantity == 0, "resource nodes retained units after deliveries completed"); + return {}; } -void test_production_reservations_and_construction() { +Test CoreTests::test_production_reservations_and_construction() { using settlement::ItemType; using settlement::JobState; using settlement::RecipeId; @@ -207,9 +244,10 @@ void test_production_reservations_and_construction() { require(world.storages()[0].items.empty() && world.storages()[1].items.empty(), "building did not consume the crafted materials from both stores"); + return {}; } -void test_cabin_placement_queues_a_complete_order() { +Test CoreTests::test_cabin_placement_queues_a_complete_order() { using settlement::RecipeId; settlement::World world(1, 10, 10); world.set_blocked({1, 1}); @@ -229,9 +267,10 @@ void test_cabin_placement_queues_a_complete_order() { } catch (const std::invalid_argument&) { require(orders.size() == 6, "invalid placement partially queued new orders"); } + return {}; } -void test_hungry_resident_reserves_and_eats_a_berry() { +Test CoreTests::test_hungry_resident_reserves_and_eats_a_berry() { using settlement::AgentState; using settlement::ItemType; const settlement::GridPosition pantry{1, 1}; @@ -278,9 +317,10 @@ void test_hungry_resident_reserves_and_eats_a_berry() { static_cast(world.add_job(pantry, 1)); world.step(); require(world.jobs_completed() == 2, "the resident did not resume work after eating"); + return {}; } -void test_invalid_save_is_rejected() { +Test CoreTests::test_invalid_save_is_rejected() { const settlement::World world(5, 5, 5); auto bytes = save_contents(world); const auto rejected = [](const std::string& save) { @@ -296,9 +336,10 @@ void test_invalid_save_is_rejected() { require(rejected(bytes + 'x'), "save with trailing data was accepted"); bytes[8] = 127; require(rejected(bytes), "unknown save version was accepted"); + return {}; } -void test_two_players_share_the_first_colony() { +Test CoreTests::test_two_players_share_the_first_colony() { using settlement::CommandKind; using settlement::CommandStatus; auto world = settlement::make_first_colony(2); @@ -341,9 +382,10 @@ void test_two_players_share_the_first_colony() { "the shared colony could not feed its residents and complete the objective"); auto replay = save_roundtrip(*world); require(replay->scenario_progress().completed, "completion was lost after loading"); + return {}; } -void test_bed_parts_are_delivered_separately() { +Test CoreTests::test_bed_parts_are_delivered_separately() { using namespace settlement; auto world = make_first_colony(2); const GridPosition wood_bed{16, 18}; @@ -373,9 +415,10 @@ void test_bed_parts_are_delivered_separately() { "the beds were not completed through three separate deliveries"); require(world->storages().back().item_count(ItemType::Cloth) == 8, "two beds must consume four pieces of cloth"); + return {}; } -void test_resident_uses_assigned_bed_and_sleep_survives_save() { +Test CoreTests::test_resident_uses_assigned_bed_and_sleep_survives_save() { using namespace settlement; World world(4, 16, 16, 2); const auto owner = world.spawn_agent({1, 2}); @@ -423,9 +466,10 @@ void test_resident_uses_assigned_bed_and_sleep_survives_save() { } require(from_route && woke_rested && rested_on_ground, "sleep and recovery phases were not observed"); require(world.jobs_completed() == 2, "residents did not finish their existing work"); + return {}; } -void test_fatigue_slows_work_without_interrupting_it() { +Test CoreTests::test_fatigue_slows_work_without_interrupting_it() { using namespace settlement; World world(6, 10, 10); static_cast(world.spawn_agent({2, 2})); @@ -438,9 +482,10 @@ void test_fatigue_slows_work_without_interrupting_it() { const auto before = resident.work_remaining; for (int i = 0; i < 6; ++i) world.step(); require(before - resident.work_remaining == 2, "hunger and fatigue did not slow the ongoing work"); + return {}; } -void test_ground_rest_never_uses_another_residents_bed() { +Test CoreTests::test_ground_rest_never_uses_another_residents_bed() { using namespace settlement; World world(15, 14, 14); const GridPosition cell{7, 6}; @@ -479,9 +524,10 @@ void test_ground_rest_never_uses_another_residents_bed() { require(world.assigned_bed(owner)->position == new_cell, "moving a bed lost its owner"); require(world.apply_command({1, 3, CommandKind::DemolishObject, new_cell}).status == CommandStatus::Accepted && world.assigned_bed(owner) == nullptr, "demolishing a bed left a stale assignment"); + return {}; } -void test_fields_mines_and_reindexing_active_hauls() { +Test CoreTests::test_fields_mines_and_reindexing_active_hauls() { using namespace settlement; World world(22, 18, 18, 2); const GridPosition rock{9, 5}; @@ -532,9 +578,10 @@ void test_fields_mines_and_reindexing_active_hauls() { "growing, regrowing, or mining did not deliver resources"); require(apply(CommandKind::PlaceStorage, {11, 7}) == CommandStatus::Accepted, "a new storage could not be placed"); + return {}; } -void test_specialists_take_their_own_jobs_and_finish_prior_assignments() { +Test CoreTests::test_specialists_take_their_own_jobs_and_finish_prior_assignments() { using namespace settlement; World world(54, 14, 14, 2); const auto farmer = world.spawn_agent({2, 2}); @@ -588,9 +635,10 @@ void test_specialists_take_their_own_jobs_and_finish_prior_assignments() { } require(delivered_stone && later_cut_wood, "the reassigned miner did not finish mining and then cut wood"); require(world.scenario_progress().assigned_beds == 1, "the builder did not complete the bed"); + return {}; } -void test_flax_and_loom_supply_a_bed_without_starting_cloth() { +Test CoreTests::test_flax_and_loom_supply_a_bed_without_starting_cloth() { using namespace settlement; World world(92, 12, 12, 3); const auto farmer = world.spawn_agent({2, 3}); @@ -648,9 +696,10 @@ void test_flax_and_loom_supply_a_bed_without_starting_cloth() { require(world.scenario_progress().assigned_beds == 1 && world.storages().front().item_count(ItemType::Cloth) > 0, "the loom did not make enough cloth to finish and replenish a bed order"); + return {}; } -void test_field_growth_requires_a_worker() { +Test CoreTests::test_field_growth_requires_a_worker() { using namespace settlement; World world(58, 14, 14); const auto resident = world.spawn_agent({2, 2}); @@ -677,9 +726,10 @@ void test_field_growth_requires_a_worker() { require(save_contents(world) == save_contents(*restored), "sowing did not resume after loading"); } require(world.resource_nodes().front().quantity > 0, "planting without a storage did not grow flax"); + return {}; } -void test_opening_a_mine_invalidates_unreachable_routes() { +Test CoreTests::test_opening_a_mine_invalidates_unreachable_routes() { using namespace settlement; World world(44, 8, 8); const auto resident = world.spawn_agent({1, 4}); @@ -698,9 +748,10 @@ void test_opening_a_mine_invalidates_unreachable_routes() { world.step(); require(world.agents().front().resource_node_index == 0 && world.agents().front().state == AgentState::Travelling, "terrain edit left a stale route in the cache"); + return {}; } -void test_object_tools_work_in_an_older_demo_world() { +Test CoreTests::test_object_tools_work_in_an_older_demo_world() { using namespace settlement; World legacy(12, 12, 12); static_cast(legacy.spawn_agent({4, 4})); @@ -719,9 +770,10 @@ void test_object_tools_work_in_an_older_demo_world() { require(edit(CommandKind::DemolishObject, {4, 5}) == CommandStatus::Accepted, "a field in a demonstration could not be demolished"); static_cast(save_roundtrip(*world)); + return {}; } -void test_room_builds_and_saves_as_separate_parts() { +Test CoreTests::test_room_builds_and_saves_as_separate_parts() { using namespace settlement; World world(61, 16, 16); static_cast(world.spawn_agent({3, 3})); @@ -761,39 +813,176 @@ void test_room_builds_and_saves_as_separate_parts() { resumed->production_orders().size() == 16 && resumed->can_place_storage(floor), "demolition removed the floor instead of the furniture"); static_cast(save_roundtrip(*resumed)); + return {}; +} + +Test CoreTests::test_furnished_rooms_queue_and_build_their_contents() { + using namespace settlement; + using enum RecipeId; + const std::pair variants[] = {{RoomTemplate::Doctor, BuildMedicineCabinet}, + {RoomTemplate::Miner, BuildMiningRack}, {RoomTemplate::Weaver, BuildLoom}}; + for (const auto& [layout, fixture] : variants) { + World world(62, 16, 16); + static_cast(world.spawn_agent({3, 3})); + const auto carpenter = world.spawn_agent({4, 3}); + const auto storage = world.add_storage({3, 2}, 48); + world.stock_storage(storage, ItemType::Wood, 32); + world.stock_storage(storage, ItemType::Stone, 3); + world.stock_storage(storage, ItemType::Cloth, 2); + world.stock_storage(storage, ItemType::Flax, 1); + world.start_scenario({2, 3}); + require(world.apply_command({1, world.next_command_sequence(1), CommandKind::AssignProfession, + {}, static_cast(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted, + "could not assign a carpenter for the furnished room"); + RoomPlan plan{{6, 5}, {9, 8}, RoomSide::East, layout}; + for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) { + plan.entrance = side; + const auto decoded = RoomPlan::from_placement(plan.first, plan.last, plan.placement_value()); + const auto parts = decoded.furnishings(); + require(decoded.entrance == side && decoded.layout == layout && parts.has_value(), + "room command lost the direction or furnishings"); + require((*parts)[0].recipe == BuildBed && (*parts)[1].recipe == fixture && + (*parts)[0].position != (*parts)[1].position && + plan.recipe_at((*parts)[0].position) == BuildFloor && + plan.recipe_at((*parts)[1].position) == BuildFloor, + "the furnishings must occupy two distinct interior cells"); + } + const auto parts = *plan.furnishings(); + const auto place = [&](std::uint8_t player, std::uint8_t value) { + return world.apply_command({player, world.next_command_sequence(player), CommandKind::PlaceRoom, + plan.first, value, plan.last}).status; + }; + require(place(2, 255) == CommandStatus::InvalidTarget && world.production_orders().empty(), + "an unknown layout partially queued a room"); + require(place(2, plan.placement_value()) == CommandStatus::Accepted && + world.production_orders().size() == 19, "the furnished room did not queue construction and the door"); + require(place(1, plan.placement_value()) == CommandStatus::InvalidTarget && + world.production_orders().size() == 19, "an overlapping furnished room left duplicate orders"); + const auto floor_is_done = [&](const World& state, GridPosition cell) { + return std::any_of(state.production_orders().begin(), state.production_orders().end(), + [cell](const auto& order) { + return order.position == cell && order.recipe == BuildFloor && order.state == JobState::Completed; + }); + }; + world.step(); + auto resumed = save_roundtrip(world); + for (int tick = 0; tick < 850; ++tick) { + resumed->step(); + for (std::size_t i = 0; i < parts.size(); ++i) { + const auto& order = resumed->production_orders()[i]; + if (order.state != JobState::Available || order.recipe == WeaveCloth) { + require(floor_is_done(*resumed, parts[i].position), "a furnishing started before its floor"); + } + } + } + const auto& bed = resumed->production_orders()[0]; + const auto& furniture = resumed->production_orders()[1]; + require(bed.recipe == BuildBed && bed.position == parts[0].position && bed.state == JobState::Completed && + bed.bed_owner != 0 && bed.bed_base == (layout == RoomTemplate::Miner ? BedBase::Stone : BedBase::Wood), + "the room's bed did not become usable"); + require(furniture.position == parts[1].position, "the furnishing moved during construction"); + if (fixture == BuildLoom) { + require(furniture.recipe == WeaveCloth && resumed->storages().front().item_count(ItemType::Cloth) == 1, + "the built loom did not process flax"); + } else { + require(furniture.recipe == fixture && furniture.state == JobState::Completed, + "the themed furnishing did not finish"); + } + static_cast(save_roundtrip(*resumed)); + } + return {}; +} + +Test CoreTests::test_carpenter_delivers_the_door_before_installation() { + using namespace settlement; + auto world = std::make_unique(63, 16, 16); + const auto builder = world->spawn_agent({5, 3}); + const auto carpenter = world->spawn_agent({3, 3}); + const auto first_storage = world->add_storage({2, 3}, 9); + const auto second_storage = world->add_storage({3, 4}, 20); + world->stock_storage(first_storage, ItemType::Wood, 9); + world->stock_storage(second_storage, ItemType::Wood, 20); + constexpr GridPosition workshop{4, 3}; + world->start_scenario(workshop); + const auto assign = [&](AgentId resident, Profession role) { + return world->apply_command({1, world->next_command_sequence(1), CommandKind::AssignProfession, + {}, static_cast(role), {}, resident}).status; + }; + const auto place = [&](const RoomPlan& plan) { + return world->apply_command({1, world->next_command_sequence(1), CommandKind::PlaceRoom, + plan.first, plan.placement_value(), plan.last}).status; + }; + const auto order = [&](RecipeId recipe) -> const ProductionOrder& { + const auto& orders = world->production_orders(); + const auto found = std::find_if(orders.begin(), orders.end(), + [recipe](const auto& entry) { return entry.recipe == recipe; }); + require(found != orders.end(), "expected production order was missing"); + return *found; + }; + const auto crafted_orders = [&] { + return std::count_if(world->production_orders().begin(), world->production_orders().end(), + [](const auto& entry) { return entry.recipe == RecipeId::CraftWoodenDoor; }); + }; + require(assign(builder, Profession::Builder) == CommandStatus::Accepted && + place({{6, 5}, {8, 7}, RoomSide::South}) == CommandStatus::Accepted, + "could not place the room"); + for (int tick = 0; tick < 400; ++tick) world->step(); + require(order(RecipeId::CraftWoodenDoor).state == JobState::Available && + order(RecipeId::InstallDoorAlongX).state == JobState::Available && + world->storages()[0].item_count(ItemType::Wood) == 1, + "a builder or generalist bypassed the carpenter or failed to build the shell"); + require(assign(carpenter, Profession::Carpenter) == CommandStatus::Accepted, "could not promote the carpenter"); + + bool fetched_wood = false, crafted_at_bench = false, delivered_door = false, installed_from_cargo = false; + for (int tick = 0; tick < 400 && order(RecipeId::InstallDoorAlongX).state != JobState::Completed; ++tick) { + world->step(); + const auto& resident = world->agents()[1]; + if (!fetched_wood && resident.inventory.item_count(ItemType::Wood) == 1) { + fetched_wood = true; + require(world->storages()[0].reserved_slots == 1, "no space reserved for the product"); + world = save_roundtrip(*world); + continue; + } + if (!crafted_at_bench && order(RecipeId::CraftWoodenDoor).state == JobState::InProgress && + resident.state == AgentState::Working && resident.position == workshop) { + crafted_at_bench = true; + world = save_roundtrip(*world); + continue; + } + if (!delivered_door && resident.inventory.item_count(ItemType::WoodenDoor) == 1) { + delivered_door = true; + require(resident.state == AgentState::Hauling && resident.storage_index == 0 && + world->storages()[0].item_count(ItemType::WoodenDoor) == 0, + "the finished door appeared on the store before being delivered"); + world = save_roundtrip(*world); + continue; + } + if (!installed_from_cargo && world->agents()[0].inventory.item_count(ItemType::WoodenDoor) == 1) { + installed_from_cargo = true; + world = save_roundtrip(*world); + } + } + require(fetched_wood && crafted_at_bench && delivered_door && installed_from_cargo && + order(RecipeId::InstallDoorAlongX).state == JobState::Completed && crafted_orders() == 1 && + world->storages()[0].reserved_slots == 0 && world->storages()[1].item_count(ItemType::Wood) == 19, + "the complete carpenter and builder workflow did not run"); + + require(world->apply_command({1, world->next_command_sequence(1), CommandKind::CraftDoor}).status == + CommandStatus::Accepted, "an independent door order was rejected"); + for (int tick = 0; tick < 300 && world->storages()[1].item_count(ItemType::WoodenDoor) == 0; ++tick) world->step(); + require(world->storages()[1].item_count(ItemType::WoodenDoor) == 1 && crafted_orders() == 2, + "the independent order did not produce a spare door"); + require(place({{10, 5}, {12, 7}, RoomSide::South}) == CommandStatus::Accepted && crafted_orders() == 2, + "a new room did not use the spare door"); + require(world->apply_command({1, world->next_command_sequence(1), CommandKind::DemolishObject, + world->storages()[1].position}).status == CommandStatus::Accepted && crafted_orders() == 3, + "losing the stock did not queue a replacement for the waiting room"); + static_cast(save_roundtrip(*world)); + return {}; } } // namespace -int main() { - try { - test_rng_repeats_for_same_seed(); - test_work_jobs_complete(); - test_astar_route_uses_opening_in_wall(); - test_parallel_pathfinding_completes_the_jobs(); - test_single_worker_configuration_is_rejected(); - test_residents_gather_and_deliver_resources(); - test_production_reservations_and_construction(); - test_cabin_placement_queues_a_complete_order(); - test_hungry_resident_reserves_and_eats_a_berry(); - test_invalid_save_is_rejected(); - test_two_players_share_the_first_colony(); - test_bed_parts_are_delivered_separately(); - test_resident_uses_assigned_bed_and_sleep_survives_save(); - test_fatigue_slows_work_without_interrupting_it(); - test_ground_rest_never_uses_another_residents_bed(); - test_fields_mines_and_reindexing_active_hauls(); - test_specialists_take_their_own_jobs_and_finish_prior_assignments(); - test_flax_and_loom_supply_a_bed_without_starting_cloth(); - test_field_growth_requires_a_worker(); - test_opening_a_mine_invalidates_unreachable_routes(); - test_object_tools_work_in_an_older_demo_world(); - test_room_builds_and_saves_as_separate_parts(); - } catch (const std::exception& error) { - std::cerr << "Test failed: " << error.what() << '\n'; - return 1; - } - - std::cout << "All core checks passed.\n"; - return 0; +int main(int argc, char** argv) { + return CoreTests::run(argc, argv); } diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index da8b32d..d3e64a9 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -1,3 +1,5 @@ +#include "testing.hpp" + #include "lan_session.hpp" #include @@ -15,7 +17,13 @@ void require(bool condition, const char* message) { if (!condition) throw std::runtime_error(message); } -void test_shared_colony_over_loopback() { +using Void::Testing::Test; + +struct LanTests : Void::Testing::Suite { + [[= Void::Testing::tag("lan")]] Test test_shared_colony_over_loopback(); +}; + +Test LanTests::test_shared_colony_over_loopback() { auto authoritative = make_first_colony(4); auto client_view = make_first_colony(4); for (int i = 0; i < 25; ++i) authoritative->step(); @@ -149,8 +157,10 @@ void test_shared_colony_over_loopback() { const auto previous_size = authoritative->production_orders().size(); require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), "guest could not send the room"); - pump_until([&] { return client_view->production_orders().size() == previous_size + 9; }, - "snapshot did not carry all room components"); + pump_until([&] { + return client_view->production_orders().size() == previous_size + 10 && + client_view->production_orders().back().recipe == RecipeId::CraftWoodenDoor; + }, "snapshot did not carry the room and carpenter's order"); require(guest.submit(CommandKind::PlaceRoom, room.first, entrance, room.last), "guest could not send the conflicting room"); pump_until([&] { @@ -159,17 +169,13 @@ void test_shared_colony_over_loopback() { rejected->destination == room.last && rejected->value == entrance && rejected->status == CommandStatus::InvalidTarget; }, "room rejection lost the geometry needed to restore the draft"); - require(authoritative->production_orders().size() == previous_size + 9, "room conflict scheduled extra work"); + require(authoritative->production_orders().size() == previous_size + 10, "room conflict scheduled extra work"); std::cout << "Loopback LAN checks passed.\n"; + return {}; } } // namespace -int main() { - try { - test_shared_colony_over_loopback(); - } catch (const std::exception& error) { - std::cerr << error.what() << '\n'; - return 1; - } +int main(int argc, char** argv) { + return LanTests::run(argc, argv); } diff --git a/tests/testing.hpp b/tests/testing.hpp new file mode 100644 index 0000000..4805f03 --- /dev/null +++ b/tests/testing.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Testing { + +struct Test {}; + +struct AnnotationText { + char text[96]{}; + + consteval AnnotationText(std::string_view value) { + if (value.size() >= sizeof(text)) throw "Test annotation is too long"; + value.copy(text, value.size()); + } + + constexpr std::string_view view() const noexcept { return text; } +}; + +struct Tag { AnnotationText value; }; +struct Skip { AnnotationText value; }; + +consteval Tag tag(std::string_view value) { return {value}; } +consteval Skip skip(std::string_view reason) { return {reason}; } + +namespace detail { + +namespace meta = std::meta; + +template +std::vector annotation_values() { + std::vector values; + template for (constexpr auto a : std::define_static_array(meta::annotations_of_with_type(Member, ^^Annotation))) { + constexpr auto annotation = meta::extract(a); + values.emplace_back(annotation.value.view()); + } + return values; +} + +consteval bool is_test(meta::info member) { + return meta::is_function(member) && !meta::is_static_member(member) && + !meta::is_constructor(member) && !meta::is_destructor(member) && + meta::parameters_of(member).empty() && meta::return_type_of(member) == ^^Test; +} + +} // namespace detail + +template +struct Suite { + template + static void expect_eq(const Actual& actual, const Expected& expected, + std::source_location at = std::source_location::current()) { + if (!(actual == expected)) { + throw std::runtime_error(std::string(at.file_name()) + ":" + std::to_string(at.line()) + + ": expected equal values"); + } + } + + static int run(int argc, char** argv) { + std::string_view selected_tag; + if (argc == 3 && std::string_view(argv[1]) == "--tag" && argv[2][0] != '\0') { + selected_tag = argv[2]; + } else if (argc != 1) { + std::cerr << "Usage: " << argv[0] << " [--tag NAME]\n"; + return 1; + } + namespace meta = std::meta; + int matched = 0, failed = 0, skipped = 0; + template for (constexpr auto member : std::define_static_array(meta::members_of(^^Derived, + meta::access_context::current()))) { + if constexpr (detail::is_test(member)) { + const auto tags = detail::annotation_values(); + if (selected_tag.empty() || std::ranges::find(tags, selected_tag) != tags.end()) { + ++matched; + constexpr auto name = meta::identifier_of(member); + const auto reasons = detail::annotation_values(); + if (!reasons.empty()) { + ++skipped; + std::cout << "[SKIP] " << name << " (" << reasons.front() << ")\n"; + } else { + try { + Derived suite{}; + if constexpr (requires { suite.setup(); }) suite.setup(); + suite.[:member:](); + std::cout << "[PASS] " << name << '\n'; + } catch (const std::exception& error) { + ++failed; + std::cerr << "[FAIL] " << name << ": " << error.what() << '\n'; + } catch (...) { + ++failed; + std::cerr << "[FAIL] " << name << ": unexpected exception\n"; + } + } + } + } + } + if (matched == 0) { + std::cerr << "No tests matched"; + if (!selected_tag.empty()) std::cerr << " tag " << selected_tag; + std::cerr << '\n'; + return 1; + } + std::cout << matched - failed - skipped << " passed, " << failed << " failed, " << skipped << " skipped\n"; + return failed == 0 ? 0 : 1; + } +}; + +} // namespace Void::Testing