From 65686db1a15de330c2757b9373fdee1e5fc01560 Mon Sep 17 00:00:00 2001 From: Lagg1ng <12+lagg1ng@noreply@faumaray.com> Date: Sat, 28 Nov 2026 16:39:23 +0000 Subject: [PATCH] Import multithreaded simulation core --- engine/src/first_colony.cpp | 35 + engine/src/worker_pool.cpp | 56 ++ engine/src/world.cpp | 1550 +++++++++++++++++++++++++++++++++++ engine/src/world_save.cpp | 598 ++++++++++++++ 4 files changed, 2239 insertions(+) create mode 100644 engine/src/first_colony.cpp create mode 100644 engine/src/worker_pool.cpp create mode 100644 engine/src/world.cpp create mode 100644 engine/src/world_save.cpp diff --git a/engine/src/first_colony.cpp b/engine/src/first_colony.cpp new file mode 100644 index 0000000..aff7e37 --- /dev/null +++ b/engine/src/first_colony.cpp @@ -0,0 +1,35 @@ +#include "settlement/core/deterministic_rng.hpp" +#include "settlement/core/world.hpp" + +#include + +namespace settlement { + +std::unique_ptr make_first_colony(std::size_t workers) { + constexpr auto size = first_colony_map_size; + auto world = std::make_unique(2026, size, size, workers); + DeterministicRng terrain_rng(0x534554544C454D45ULL); + for (int y = 2; y < size - 2; ++y) { + for (int x = 2; x < size - 2; ++x) { + const int distance = std::abs(x - size / 2) + std::abs(y - size / 2); + if (distance > 7 && terrain_rng.bounded(100) < 5) world->set_blocked({x, y}); + } + } + for (const auto position : {GridPosition{16, 16}, {17, 15}, {15, 15}}) { + static_cast(world->spawn_agent(position)); + } + static_cast(world->add_storage({15, 16}, 9)); + static_cast(world->add_storage({16, 13}, 15, StorageKind::Pantry)); + const auto provisions = world->add_storage({18, 16}, 18); + world->stock_storage(provisions, ItemType::Cloth, 12); + world->stock_storage(provisions, ItemType::Stone, 6); + static_cast(world->add_resource_node({12, 16}, ItemType::Wood, 12)); + static_cast(world->add_resource_node({13, 17}, ItemType::Wood, 12)); + for (const auto position : {GridPosition{13, 14}, {14, 12}, {18, 12}, {19, 14}}) { + static_cast(world->add_resource_node(position, ItemType::Berries, 16)); + } + world->start_scenario({15, 14}); + return world; +} + +} // namespace settlement diff --git a/engine/src/worker_pool.cpp b/engine/src/worker_pool.cpp new file mode 100644 index 0000000..5ed9177 --- /dev/null +++ b/engine/src/worker_pool.cpp @@ -0,0 +1,56 @@ +#include "settlement/core/worker_pool.hpp" + +#include + +namespace settlement { + +WorkerPool::WorkerPool(std::size_t thread_count) { + if (thread_count < 2) { + throw std::invalid_argument("worker pool needs at least two threads"); + } + workers_.reserve(thread_count); + try { + for (std::size_t index = 0; index < thread_count; ++index) { + workers_.emplace_back([this] { worker_loop(); }); + } + } catch (...) { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + work_available_.notify_all(); + for (std::thread& worker : workers_) { + if (worker.joinable()) worker.join(); + } + throw; + } +} + +WorkerPool::~WorkerPool() { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + work_available_.notify_all(); + for (std::thread& worker : workers_) { + if (worker.joinable()) worker.join(); + } +} + +std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); } + +void WorkerPool::worker_loop() { + for (;;) { + std::function task; + { + std::unique_lock lock(mutex_); + work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); }); + if (stopping_ && tasks_.empty()) return; + task = std::move(tasks_.front()); + tasks_.pop(); + } + task(); + } +} + +} // namespace settlement diff --git a/engine/src/world.cpp b/engine/src/world.cpp new file mode 100644 index 0000000..473365f --- /dev/null +++ b/engine/src/world.cpp @@ -0,0 +1,1550 @@ +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { +namespace { + +constexpr std::int32_t max_map_dimension = 512; +constexpr std::uint32_t meal_ticks = 5; +constexpr std::uint64_t berry_regrowth_ticks = 12; +constexpr std::uint16_t bed_recovery = 6; +constexpr std::uint16_t ground_recovery = 2; +constexpr std::uint16_t ground_wake_fatigue = fatigue_threshold / 2; +constexpr GridPosition adjacent_cells[] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; + +std::uint64_t growing_time(ResourceSite site) noexcept { + switch (site) { + case ResourceSite::BerryField: return 70; + case ResourceSite::TreePlot: return 140; + case ResourceSite::FlaxField: return 55; + default: return 0; + } +} + +bool is_production_object(RecipeId recipe) noexcept { + return is_construction(recipe) || recipe == RecipeId::WeaveCloth; +} + +bool can_take_work(const Agent& agent, Profession profession) noexcept { + return agent.profession == Profession::Generalist || agent.profession == profession; +} + +Profession gathering_profession(ItemType item) noexcept { + if (item == ItemType::Wood) return Profession::Woodcutter; + if (item == ItemType::Stone) return Profession::Miner; + return Profession::Farmer; +} + +std::uint16_t initial_hunger(AgentId id) { + return static_cast((id * 37) % (hunger_threshold / 2)); +} + +struct Recipe { + std::array ingredients; + ItemType output; + std::uint32_t ticks; +}; + +const Recipe& recipe_for(RecipeId id) { + static constexpr Recipe saw{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::Plank, 12}; + static constexpr Recipe cut{{ItemStack{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16}; + static constexpr Recipe cabin{{ItemStack{ItemType::Plank, 3}, ItemStack{ItemType::StoneBlock, 2}}, + ItemType::None, 28}; + static constexpr Recipe bed{{ItemStack{ItemType::Plank, 1}, {}}, ItemType::None, 14}; + static constexpr Recipe weave{{ItemStack{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12}; + switch (id) { + case RecipeId::SawPlank: return saw; + case RecipeId::CutStoneBlock: return cut; + case RecipeId::BuildCabin: return cabin; + case RecipeId::BuildBed: return bed; + case RecipeId::WeaveCloth: return weave; + } + throw std::invalid_argument("unknown production recipe"); +} + +Recipe recipe_for(const ProductionOrder& order) { + Recipe recipe = recipe_for(order.recipe); + if (order.recipe == RecipeId::BuildBed) recipe.ingredients[0].type = order.bed_material(); + return recipe; +} + +auto stack_position(Storage& storage, ItemType type) { + return std::lower_bound(storage.items.begin(), storage.items.end(), type, + [](const ItemStack& stack, ItemType target) { return stack.type < target; }); +} + +std::size_t checked_cell_count(std::int32_t width, std::int32_t height) { + if (width <= 0 || height <= 0 || width > max_map_dimension || height > max_map_dimension) { + throw std::invalid_argument("map dimensions must be in the range 1..512"); + } + return static_cast(width) * static_cast(height); +} + +std::size_t checked_worker_count(std::size_t workers) { + if (workers < min_worker_count || workers > max_worker_count) { + throw std::invalid_argument("worker count must be in the range 2..64"); + } + return workers; +} + +std::int32_t manhattan_distance(GridPosition left, GridPosition right) noexcept { + const std::int32_t dx = left.x > right.x ? left.x - right.x : right.x - left.x; + const std::int32_t dy = left.y > right.y ? left.y - right.y : right.y - left.y; + return dx + dy; +} + +struct OpenNode { + std::int32_t cell = 0; + std::int32_t distance_from_start = 0; + std::int32_t heuristic = 0; + std::int32_t estimated_total = 0; +}; + +struct OpenNodeLater { + [[nodiscard]] bool operator()(const OpenNode& left, const OpenNode& right) const noexcept { + if (left.estimated_total != right.estimated_total) { + return left.estimated_total > right.estimated_total; + } + if (left.heuristic != right.heuristic) { + return left.heuristic > right.heuristic; + } + return left.cell > right.cell; + } +}; + +} // namespace + +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; +} + +bool Inventory::empty() const noexcept { return first_item() == ItemType::None; } + +void Inventory::add(ItemType type, std::uint32_t count) noexcept { + const auto index = static_cast(type); + assert(index != 0 && index <= counts_.size()); + assert(count <= std::numeric_limits::max() - counts_[index - 1]); + counts_[index - 1] += count; +} + +void Inventory::remove(ItemType type, std::uint32_t count) noexcept { + const auto index = static_cast(type); + assert(index != 0 && index <= counts_.size() && count <= counts_[index - 1]); + counts_[index - 1] -= count; +} + +ItemType Inventory::first_item() const noexcept { + const auto found = std::find_if(counts_.begin(), counts_.end(), + [](std::uint32_t count) { return count != 0; }); + return found == counts_.end() ? ItemType::None : + static_cast(found - counts_.begin() + 1); +} + +void Storage::add_item(ItemType type) { + assert(accepts(type)); + auto stack = stack_position(*this, type); + if (stack != items.end() && stack->type == type) { + ++stack->count; + } else { + items.insert(stack, ItemStack{type, 1}); + } +} + +World::World(std::uint64_t seed, std::int32_t width, std::int32_t height, + std::size_t workers) + : seed_(seed), + width_(width), + height_(height), + worker_count_(checked_worker_count(workers)), + blocked_(checked_cell_count(width, height), 0) {} + +std::size_t World::cell_index(GridPosition position) const noexcept { + return static_cast(position.y) * static_cast(width_) + + static_cast(position.x); +} + +bool World::is_walkable(GridPosition position) const noexcept { + if (position.x < 0 || position.y < 0 || position.x >= width_ || position.y >= height_) { + return false; + } + return blocked_[cell_index(position)] == 0; +} + +void World::set_blocked(GridPosition position, bool blocked) { + if (position.x < 0 || position.y < 0 || position.x >= width_ || position.y >= height_) { + throw std::out_of_range("map cell is outside the world"); + } + if (blocked) { + if (scenario_active_ && position == scenario_sawmill_) { + throw std::logic_error("cannot block the scenario sawmill"); + } + for (const Agent& agent : agents_) { + if (agent.position.x == position.x && agent.position.y == position.y) { + throw std::logic_error("cannot block a cell occupied by an agent"); + } + } + for (const WorkJob& job : jobs_) { + if (job.position.x == position.x && job.position.y == position.y && + job.state != JobState::Completed) { + throw std::logic_error("cannot block a cell with an active work job"); + } + } + for (const ProductionOrder& order : production_orders_) { + if (order.position.x == position.x && order.position.y == position.y) { + throw std::logic_error("cannot block a production site"); + } + for (const ConstructionStop& stop : order.delivery_stops) { + if (std::find(stop.route_to_next.begin(), stop.route_to_next.end(), position) != + stop.route_to_next.end()) { + throw std::logic_error("cannot block a scheduled construction delivery"); + } + } + } + for (const Storage& storage : storages_) { + if (storage.position == position) throw std::logic_error("cannot block a storage cell"); + } + for (const auto& node : resource_nodes_) { + if (node.site != ResourceSite::Natural && node.position == position) { + throw std::logic_error("cannot block a planted field or mine"); + } + } + for (const Agent& agent : agents_) { + if (agent.production_index == no_entity_index && + agent.state != AgentState::GoingToEat && agent.state != AgentState::GoingToSleep) 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"); + } + } + } + auto& cell = blocked_[cell_index(position)]; + if ((cell != 0) != blocked) assignment_path_cache_.clear(); + cell = blocked ? 1 : 0; +} + +AgentId World::spawn_agent(GridPosition position) { + if (!is_walkable(position)) { + throw std::invalid_argument("agent spawn cell is not walkable"); + } + const AgentId id = next_agent_id_++; + Agent agent; + agent.id = id; + agent.position = position; + if (hunger_enabled_) agent.hunger = initial_hunger(id); + agents_.push_back(std::move(agent)); + return id; +} + +JobId World::add_job(GridPosition position, std::uint32_t work_required) { + if (!is_walkable(position)) { + throw std::invalid_argument("work job cell is not walkable"); + } + if (work_required == 0) { + throw std::invalid_argument("work duration must be greater than zero"); + } + const JobId id = next_job_id_++; + jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available}); + return id; +} + +std::uint64_t World::add_resource_node(GridPosition position, ItemType type, + std::uint32_t quantity) { + if (!is_walkable(position)) { + throw std::invalid_argument("resource node must be on a walkable cell"); + } + if ((type != ItemType::Wood && type != ItemType::Stone && type != ItemType::Berries) || quantity == 0) { + throw std::invalid_argument("resource node needs wood, stone, or berries and a positive quantity"); + } + const std::uint64_t id = next_resource_node_id_++; + const bool foraging = type != ItemType::Berries || !scenario_active_; + resource_nodes_.push_back(ResourceNode{id, position, type, quantity, quantity, 0, foraging}); + return id; +} + +std::uint64_t World::add_storage(GridPosition position, std::uint32_t capacity, StorageKind kind) { + if (!is_walkable(position)) { + throw std::invalid_argument("storage must be on a walkable cell"); + } + if (capacity == 0) { + throw std::invalid_argument("storage capacity must be positive"); + } + if (kind != StorageKind::Materials && kind != StorageKind::Pantry) { + throw std::invalid_argument("unknown storage kind"); + } + const std::uint64_t id = next_storage_id_; + Storage storage{id, position, capacity, 0, {}, kind}; + storage.items.reserve(kind == StorageKind::Pantry ? 1 : item_type_count - 1); + storages_.push_back(std::move(storage)); + ++next_storage_id_; + return id; +} + +void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count) { + const auto storage = std::find_if(storages_.begin(), storages_.end(), + [id](const Storage& entry) { return entry.id == id; }); + if (storage == storages_.end() || static_cast(type) > item_type_count || !storage->accepts(type) || + storage->total_items() + storage->reserved_slots + count > storage->capacity) { + throw std::invalid_argument("initial stock does not fit the selected storage"); + } + if (count == 0) return; + auto stack = stack_position(*storage, type); + if (stack != storage->items.end() && stack->type == type) stack->count += count; + else storage->items.insert(stack, ItemStack{type, count}); +} + +void World::enable_hunger() noexcept { + if (hunger_enabled_) return; + hunger_enabled_ = true; + for (Agent& agent : agents_) agent.hunger = initial_hunger(agent.id); +} + +void World::queue_production(GridPosition position, RecipeId recipe) { + static_cast(recipe_for(recipe)); + if (!is_walkable(position)) { + throw std::invalid_argument("production site must be on a walkable cell"); + } + if (is_production_object(recipe) && !can_place_storage(position)) { + throw std::invalid_argument("the production site is occupied"); + } + for (const ProductionOrder& order : production_orders_) { + if (is_production_object(order.recipe) && order.position == position) { + throw std::invalid_argument("a building occupies the production site"); + } + } + ProductionOrder order{}; + order.position = position; + order.recipe = recipe; + production_orders_.push_back(std::move(order)); +} + +bool World::can_place_cabin(GridPosition position) const noexcept { + if (!is_walkable(position)) return false; + const auto occupies_cell = [position](const auto& entity) { return entity.position == position; }; + return std::none_of(storages_.begin(), storages_.end(), occupies_cell) && + std::none_of(resource_nodes_.begin(), resource_nodes_.end(), occupies_cell) && + std::none_of(jobs_.begin(), jobs_.end(), occupies_cell) && + std::none_of(production_orders_.begin(), production_orders_.end(), occupies_cell); +} + +void World::queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter) { + if (!can_place_cabin(position) || position == sawmill || position == stonecutter || + (scenario_active_ && position == scenario_sawmill_)) { + throw std::invalid_argument("the cabin site is occupied or blocked"); + } + if (!is_walkable(sawmill) || !is_walkable(stonecutter) || + std::any_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) { + return is_production_object(order.recipe) && (order.position == sawmill || order.position == stonecutter); + })) { + throw std::invalid_argument("a workshop site is occupied or blocked"); + } + if (!find_path(sawmill, position).reachable || !find_path(stonecutter, position).reachable) { + throw std::invalid_argument("the cabin site is disconnected from the workshops"); + } + const Recipe& cabin = recipe_for(RecipeId::BuildCabin); + production_orders_.reserve(production_orders_.size() + 1 + + cabin.ingredients[0].count + cabin.ingredients[1].count); + for (std::uint32_t i = 0; i < cabin.ingredients[0].count; ++i) { + queue_production(sawmill, RecipeId::SawPlank); + } + for (std::uint32_t i = 0; i < cabin.ingredients[1].count; ++i) { + queue_production(stonecutter, RecipeId::CutStoneBlock); + } + queue_production(position, RecipeId::BuildCabin); +} + +void World::start_scenario(GridPosition sawmill) { + if (scenario_active_ || !can_place_cabin(sawmill)) { + throw std::invalid_argument("scenario needs a free sawmill cell"); + } + enable_hunger(); + scenario_active_ = true; + staged_beds_ = true; + scenario_sawmill_ = sawmill; + for (auto& node : resource_nodes_) { + if (node.type == ItemType::Berries) node.foraging_enabled = false; + } +} + +bool World::can_place_bed(GridPosition position) const noexcept { + return scenario_active_ && can_place_storage(position); +} + +bool World::can_place_storage(GridPosition position) const noexcept { + return (!scenario_active_ || position != scenario_sawmill_) && can_place_cabin(position) && + !resting_at(position); +} + +bool World::can_reach_object_cell(GridPosition position) const { + if (scenario_active_) return find_path(scenario_sawmill_, position).reachable; + return std::any_of(agents_.begin(), agents_.end(), [&](const auto& agent) { + return find_path(agent.position, position).reachable; + }); +} + +bool World::can_place_site(GridPosition position, ResourceSite site) const noexcept { + if (growing_time(site) != 0) return can_place_storage(position); + if (site != ResourceSite::Mine || position.x < 0 || position.y < 0 || + position.x >= width_ || position.y >= height_ || is_walkable(position)) return false; + if (std::any_of(resource_nodes_.begin(), resource_nodes_.end(), + [position](const auto& node) { return node.position == position; })) return false; + return std::any_of(std::begin(adjacent_cells), std::end(adjacent_cells), [&](GridPosition offset) { + return is_walkable({position.x + offset.x, position.y + offset.y}); + }); +} + +CommandStatus World::object_status(GridPosition position, bool moving) const noexcept { + constexpr auto busy = CommandStatus::Busy; + constexpr auto ready = CommandStatus::Accepted; + for (const auto& order : production_orders_) { + if (order.position != position || !is_production_object(order.recipe)) continue; + return order.state == JobState::InProgress || resting_at(position) ? busy : ready; + } + for (std::size_t i = 0; i < storages_.size(); ++i) { + const auto& storage = storages_[i]; + if (storage.position != position) continue; + if (storage.reserved_slots != 0 || std::any_of(storage.items.begin(), storage.items.end(), + [](const auto& item) { return item.reserved != 0; })) return busy; + for (const auto& order : production_orders_) { + if (std::any_of(order.materials.begin(), order.materials.end(), + [i](const auto& material) { return material.storage_index == i; })) return busy; + } + return ready; + } + for (const auto& node : resource_nodes_) { + if (node.position != position) continue; + if (moving && (node.site == ResourceSite::Mine || node.site == ResourceSite::Natural)) { + return CommandStatus::InvalidTarget; + } + return node.reserved_workers != 0 ? busy : ready; + } + return CommandStatus::InvalidTarget; +} + +CommandStatus World::edit_object(GridPosition position, const GridPosition* destination) { + const auto status = object_status(position, destination != nullptr); + if (status != CommandStatus::Accepted) return status; + if (destination && (!can_place_storage(*destination) || !can_reach_object_cell(*destination))) { + return CommandStatus::InvalidTarget; + } + const auto at_position = [position](const auto& item) { return item.position == position; }; + const auto shift_index = [](std::size_t& index, std::size_t removed) { + if (index != no_entity_index && index > removed) --index; + }; + const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), [&](const auto& entry) { + return is_production_object(entry.recipe) && at_position(entry); + }); + if (order != production_orders_.end()) { + if (destination) order->position = *destination; + else { + const auto removed = static_cast(order - production_orders_.begin()); + production_orders_.erase(order); + for (auto& agent : agents_) shift_index(agent.production_index, removed); + } + return CommandStatus::Accepted; + } + const auto storage = std::find_if(storages_.begin(), storages_.end(), at_position); + if (storage != storages_.end()) { + if (destination) storage->position = *destination; + else { + const auto removed = static_cast(storage - storages_.begin()); + storages_.erase(storage); + for (auto& agent : agents_) shift_index(agent.storage_index, removed); + for (auto& entry : production_orders_) { + for (auto& material : entry.materials) shift_index(material.storage_index, removed); + for (auto& stop : entry.delivery_stops) shift_index(stop.storage_index, removed); + } + } + return CommandStatus::Accepted; + } + const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), at_position); + if (source == resource_nodes_.end()) return CommandStatus::InvalidTarget; + if (destination) source->position = *destination; + else { + const auto removed = static_cast(source - resource_nodes_.begin()); + resource_nodes_.erase(source); + for (auto& agent : agents_) shift_index(agent.resource_node_index, removed); + } + return CommandStatus::Accepted; +} + +std::uint64_t World::next_command_sequence(std::uint8_t player) const noexcept { + if (player < colony_host || player > colony_player_slots || + command_revision_ == std::numeric_limits::max()) return 0; + return player_sequences_[player - colony_host] + 1; +} + +CommandReceipt World::apply_command(const PlayerCommand& command) { + const auto receipt = [&](CommandStatus status) { return CommandReceipt{status, tick_, command_revision_}; }; + const bool object_command = (command.kind >= CommandKind::PlaceBerryField && command.kind <= CommandKind::PlaceStorage) || + command.kind == CommandKind::PlaceFlaxField || command.kind == CommandKind::PlaceLoom; + if (!scenario_active_ && !object_command && command.kind != CommandKind::AssignProfession && + command.kind != CommandKind::SetForaging) return receipt(CommandStatus::Unavailable); + if (command.player < colony_host || command.player > colony_player_slots) { + return receipt(CommandStatus::Unauthorized); + } + if (command.sequence == 0 || command.sequence != next_command_sequence(command.player)) { + return receipt(CommandStatus::WrongSequence); + } + switch (command.kind) { + case CommandKind::PlaceBed: + if (command.value > static_cast(BedBase::Stone) || + !can_place_bed(command.cell) || !find_path(scenario_sawmill_, command.cell).reachable) { + return receipt(CommandStatus::InvalidTarget); + } + if (staged_beds_) { + queue_production(command.cell, RecipeId::BuildBed); + production_orders_.back().bed_base = static_cast(command.value); + production_orders_.back().bed_stage = BedStage::Foundation; + } else { + production_orders_.reserve(production_orders_.size() + 2); + queue_production(scenario_sawmill_, RecipeId::SawPlank); + queue_production(command.cell, RecipeId::BuildBed); + } + break; + case CommandKind::SetForaging: { + if (command.value > 1) return receipt(CommandStatus::InvalidTarget); + const auto source = std::find_if(resource_nodes_.begin(), resource_nodes_.end(), [&](const auto& node) { + return node.type == ItemType::Berries && node.position == command.cell; + }); + if (source == resource_nodes_.end()) return receipt(CommandStatus::InvalidTarget); + source->foraging_enabled = command.value != 0; + break; + } + case CommandKind::SetPriority: + if (command.value > static_cast(WorkPriority::BuildingFirst)) { + return receipt(CommandStatus::InvalidTarget); + } + work_priority_ = static_cast(command.value); + break; + case CommandKind::SetPaused: + if (command.player != colony_host) return receipt(CommandStatus::Unauthorized); + if (command.value > 1) return receipt(CommandStatus::InvalidTarget); + paused_ = command.value != 0; + break; + case CommandKind::PlaceBerryField: + case CommandKind::PlaceTreePlot: + case CommandKind::PlaceFlaxField: + case CommandKind::PlaceMine: { + const bool mine = command.kind == CommandKind::PlaceMine; + auto site = ResourceSite::TreePlot; + std::uint32_t yield = 6; + if (mine) { + site = ResourceSite::Mine; + yield = 24; + } else if (command.kind == CommandKind::PlaceBerryField) { + site = ResourceSite::BerryField; + yield = 8; + } else if (command.kind == CommandKind::PlaceFlaxField) { + site = ResourceSite::FlaxField; + } + if (!can_place_site(command.cell, site)) return receipt(CommandStatus::InvalidTarget); + if (mine) { + const bool reachable = std::any_of(std::begin(adjacent_cells), std::end(adjacent_cells), [&](GridPosition offset) { + return can_reach_object_cell({command.cell.x + offset.x, command.cell.y + offset.y}); + }); + if (!reachable) return receipt(CommandStatus::InvalidTarget); + } else if (!can_reach_object_cell(command.cell)) { + return receipt(CommandStatus::InvalidTarget); + } + resource_nodes_.push_back({next_resource_node_id_, command.cell, site_resource(site), mine ? yield : 0, + yield, 0, true, site}); + ++next_resource_node_id_; + if (mine) { + blocked_[cell_index(command.cell)] = 0; + assignment_path_cache_.clear(); + } + break; + } + case CommandKind::PlaceLoom: + if (!can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { + return receipt(CommandStatus::InvalidTarget); + } + queue_production(command.cell, RecipeId::WeaveCloth); + break; + case CommandKind::PlaceStorage: + if (command.value > static_cast(StorageKind::Pantry) || + !can_place_storage(command.cell) || !can_reach_object_cell(command.cell)) { + return receipt(CommandStatus::InvalidTarget); + } + static_cast(add_storage(command.cell, 18, static_cast(command.value))); + break; + case CommandKind::MoveObject: + case CommandKind::DemolishObject: { + const auto status = edit_object(command.cell, + command.kind == CommandKind::MoveObject ? &command.destination : nullptr); + if (status != CommandStatus::Accepted) return receipt(status); + break; + } + case CommandKind::AssignProfession: { + if (command.value > static_cast(Profession::Builder) || command.resident == 0) { + return receipt(CommandStatus::InvalidTarget); + } + const auto resident = std::lower_bound(agents_.begin(), agents_.end(), command.resident, + [](const Agent& agent, AgentId id) { return agent.id < id; }); + if (resident == agents_.end() || resident->id != command.resident) { + return receipt(CommandStatus::InvalidTarget); + } + resident->profession = static_cast(command.value); + break; + } + default: + return receipt(CommandStatus::InvalidTarget); + } + player_sequences_[command.player - colony_host] = command.sequence; + ++command_revision_; + return receipt(CommandStatus::Accepted); +} + +ScenarioProgress World::scenario_progress() const noexcept { + ScenarioProgress progress{0, agents_.size(), 0, 2 * agents_.size(), scenario_completed_}; + for (const auto& order : production_orders_) { + if (order.recipe == RecipeId::BuildBed && order.bed_owner != 0) ++progress.assigned_beds; + } + for (const auto& storage : storages_) { + for (const auto& stack : storage.items) { + if (stack.type == ItemType::Berries) progress.available_food += stack.count - stack.reserved; + } + } + return progress; +} + +void World::update_scenario() { + for (auto& bed : production_orders_) { + if (bed.recipe != RecipeId::BuildBed || bed.state != JobState::Completed || bed.bed_owner != 0) continue; + const auto resident = std::find_if(agents_.begin(), agents_.end(), [&](const auto& agent) { + return std::none_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) { + return order.bed_owner == agent.id; + }); + }); + if (resident == agents_.end()) break; + bed.bed_owner = resident->id; + } + if (!scenario_completed_) { + const auto progress = scenario_progress(); + scenario_completed_ = progress.residents > 0 && progress.assigned_beds == progress.residents && + progress.available_food >= progress.food_goal; + } +} + +const ProductionOrder* World::assigned_bed(AgentId agent) const noexcept { + if (agent == 0) return nullptr; + const auto order = std::find_if(production_orders_.begin(), production_orders_.end(), + [agent](const auto& bed) { return bed.bed_owner == agent; }); + return order == production_orders_.end() ? nullptr : &*order; +} + +bool World::is_bed_cell(GridPosition position) const noexcept { + return std::any_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) { + return order.recipe == RecipeId::BuildBed && order.state == JobState::Completed && + order.position == position; + }); +} + +bool World::resting_at(GridPosition position, AgentId except) const noexcept { + return std::any_of(agents_.begin(), agents_.end(), [&](const Agent& agent) { + if (agent.id == except) return false; + if (agent.state == AgentState::Sleeping) return agent.position == position; + return agent.state == AgentState::GoingToSleep && !agent.route.empty() && agent.route.back() == position; + }); +} + +bool World::ground_rest_cell(GridPosition position, AgentId agent) const noexcept { + return is_walkable(position) && !is_bed_cell(position) && !resting_at(position, agent) && + std::none_of(agents_.begin(), agents_.end(), [&](const Agent& other) { + return other.id != agent && other.position == position; + }) && + std::none_of(production_orders_.begin(), production_orders_.end(), [&](const auto& order) { + return order.position == position && is_construction(order.recipe); + }); +} + +World::PathResult World::find_path(GridPosition start, GridPosition goal) const { + PathResult result; + if (!is_walkable(start) || !is_walkable(goal)) { + return result; + } + + const std::size_t cell_count = blocked_.size(); + const auto start_index = static_cast(cell_index(start)); + const auto goal_index = static_cast(cell_index(goal)); + std::vector distance(cell_count, std::numeric_limits::max()); + std::vector parent(cell_count, -1); + std::priority_queue, OpenNodeLater> open; + + distance[static_cast(start_index)] = 0; + parent[static_cast(start_index)] = start_index; + const std::int32_t start_heuristic = manhattan_distance(start, goal); + open.push(OpenNode{start_index, 0, start_heuristic, start_heuristic}); + + constexpr GridPosition offsets[] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; + while (!open.empty()) { + const OpenNode current = open.top(); + open.pop(); + + if (current.distance_from_start != distance[static_cast(current.cell)]) { + continue; + } + ++result.nodes_visited; + if (current.cell == goal_index) { + result.reachable = true; + break; + } + + const GridPosition current_position{ + current.cell % width_, + current.cell / width_ + }; + for (const GridPosition offset : offsets) { + const GridPosition next{current_position.x + offset.x, current_position.y + offset.y}; + if (!is_walkable(next)) { + continue; + } + + const std::int32_t next_cell = static_cast(cell_index(next)); + const std::int32_t next_distance = current.distance_from_start + 1; + const std::size_t next_index = static_cast(next_cell); + if (next_distance >= distance[next_index]) { + continue; + } + + distance[next_index] = next_distance; + parent[next_index] = current.cell; + const std::int32_t heuristic = manhattan_distance(next, goal); + open.push(OpenNode{next_cell, next_distance, heuristic, next_distance + heuristic}); + } + } + + if (!result.reachable) { + return result; + } + + std::int32_t cursor = goal_index; + while (cursor != start_index) { + result.positions.push_back(GridPosition{cursor % width_, cursor / width_}); + cursor = parent[static_cast(cursor)]; + if (cursor < 0) { + result.positions.clear(); + result.reachable = false; + return result; + } + } + std::reverse(result.positions.begin(), result.positions.end()); + return result; +} + +void World::assign_idle_agents() { + if (jobs_.empty() || agents_.empty()) return; + struct Request { + std::size_t agent_index; + std::size_t job_index; + GridPosition start; + GridPosition goal; + }; + // Failed routes are rare, so keep their per-agent exclusions sparse instead of + // clearing an agents-by-jobs matrix on every tick. + std::vector> tried(agents_.size()); + std::vector pending(agents_.size(), 0); + + for (;;) { + std::vector requests; + const std::size_t chunk_count = std::min(worker_count_, agents_.size()); + const auto chunk_start = [this, chunk_count](std::size_t chunk) { + const auto size = agents_.size() / chunk_count; + const auto extra = agents_.size() % chunk_count; + return chunk * size + std::min(chunk, extra); + }; + const auto choose_jobs = [this, &tried, &pending](std::size_t begin, std::size_t end) { + std::vector choices(end - begin, jobs_.size()); + for (std::size_t agent_index = begin; agent_index < end; ++agent_index) { + const Agent& agent = agents_[agent_index]; + if (agent.state != AgentState::Idle || pending[agent_index] != 0 || + !can_take_work(agent, Profession::Builder)) continue; + std::size_t best_index = jobs_.size(); + std::int32_t best_distance = std::numeric_limits::max(); + for (std::size_t job_index = 0; job_index < jobs_.size(); ++job_index) { + const WorkJob& candidate = jobs_[job_index]; + if (candidate.state != JobState::Available || + std::find(tried[agent_index].begin(), tried[agent_index].end(), job_index) != + tried[agent_index].end()) continue; + const std::int32_t distance = manhattan_distance(agent.position, candidate.position); + if (distance < best_distance || (distance == best_distance && + (best_index == jobs_.size() || candidate.id < jobs_[best_index].id))) { + best_distance = distance; + best_index = job_index; + } + } + choices[agent_index - begin] = best_index; + } + return choices; + }; + + std::vector>> choice_futures; + choice_futures.reserve(chunk_count); + for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) { + const std::size_t begin = chunk_start(chunk); + const std::size_t end = chunk_start(chunk + 1); + choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] { + return choose_jobs(begin, end); + })); + } + + std::vector> choices; + choices.reserve(chunk_count); + for (auto& future : choice_futures) choices.push_back(future.get()); + for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) { + const std::size_t begin = chunk_start(chunk); + for (std::size_t offset = 0; offset < choices[chunk].size(); ++offset) { + const std::size_t agent_index = begin + offset; + const std::size_t job_index = choices[chunk][offset]; + if (job_index == jobs_.size() || jobs_[job_index].state != JobState::Available) continue; + Agent& agent = agents_[agent_index]; + WorkJob& job = jobs_[job_index]; + job.state = JobState::InProgress; + agent.current_job = job.id; + pending[agent_index] = 1; + requests.push_back(Request{agent_index, job_index, agent.position, job.position}); + } + } + if (requests.empty()) return; + + std::vector> futures; + futures.reserve(requests.size()); + for (const Request& request : requests) { + futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] { + return find_path(start, goal); + })); + } + for (std::size_t index = 0; index < requests.size(); ++index) { + auto path = futures[index].get(); + ++path_searches_; + path_nodes_visited_ += path.nodes_visited; + const Request& request = requests[index]; + Agent& agent = agents_[request.agent_index]; + WorkJob& job = jobs_[request.job_index]; + if (!path.reachable) { + job.state = JobState::Available; + agent.current_job = 0; + pending[request.agent_index] = 0; + tried[request.agent_index].push_back(request.job_index); + continue; + } + agent.route = std::move(path.positions); + agent.route_cursor = 0; + agent.work_remaining = job.work_required; + agent.state = agent.route.empty() ? AgentState::Working : AgentState::Travelling; + } + } +} + +World::PathResult World::assignment_path(GridPosition start, GridPosition goal) { + ++path_searches_; + if (!is_walkable(start) || !is_walkable(goal)) return {}; + const auto key = (static_cast(cell_index(start)) << 32) | cell_index(goal); + if (const auto found = assignment_path_cache_.find(key); found != assignment_path_cache_.end()) { + ++assignment_path_cache_hits_; + // Logical path counters stay identical after loading a save with an empty cache. + path_nodes_visited_ += found->second.nodes_visited; + return found->second; + } + auto path = find_path(start, goal); + path_nodes_visited_ += path.nodes_visited; + constexpr std::size_t cache_capacity = 8192; + constexpr std::size_t max_cached_route_length = 256; + if (path.positions.size() > max_cached_route_length) return path; + if (assignment_path_cache_.size() == cache_capacity) assignment_path_cache_.clear(); + assignment_path_cache_.emplace(key, path); + return path; +} + +void World::assign_resource_tasks(ResourceFocus focus) { + if (resource_nodes_.empty()) return; + constexpr std::uint32_t gather_ticks = 3; + constexpr std::uint32_t tending_ticks = 6; + const auto has_space = [](const Storage& storage) { + return storage.total_items() + storage.reserved_slots < storage.capacity; + }; + std::size_t open_pantry_count = 0; + std::size_t open_material_store_count = 0; + for (const Storage& storage : storages_) { + if (!has_space(storage)) continue; + if (storage.kind == StorageKind::Pantry) ++open_pantry_count; + else ++open_material_store_count; + } + std::array, static_cast(Profession::Builder)> available; + std::size_t untended_sites = 0; + for (std::size_t index = 0; index < resource_nodes_.size(); ++index) { + const auto& node = resource_nodes_[index]; + const bool food = node.type == ItemType::Berries; + if (!node.foraging_enabled || (focus != ResourceFocus::Any && food != (focus == ResourceFocus::Food))) continue; + const bool tending = node.needs_tending() && node.reserved_workers == 0; + if (!tending && (node.quantity <= node.reserved_workers || + (food ? open_pantry_count == 0 : open_material_store_count == 0))) continue; + if (tending) ++untended_sites; + available[static_cast(Profession::Generalist)].push_back(index); + available[static_cast(gathering_profession(node.type))].push_back(index); + } + 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 || + !agent.inventory.empty()) continue; + + const auto& candidates = available[static_cast(agent.profession)]; + if (candidates.empty()) continue; + std::vector tried_nodes(candidates.size(), 0); + for (;;) { + std::size_t chosen = candidates.size(); + std::int32_t best_distance = std::numeric_limits::max(); + for (std::size_t index = 0; index < candidates.size(); ++index) { + if (tried_nodes[index] != 0) continue; + const ResourceNode& node = resource_nodes_[candidates[index]]; + if (node.needs_tending()) { + if (node.reserved_workers != 0) continue; + } else if (node.quantity <= node.reserved_workers || + (node.type == ItemType::Berries ? open_pantry_count == 0 : open_material_store_count == 0)) { + continue; + } + const std::int32_t distance = manhattan_distance(agent.position, node.position); + // Candidate order follows the resource IDs, so the first wins ties. + if (distance < best_distance) { + best_distance = distance; + chosen = index; + } + } + if (chosen == candidates.size()) break; + + const auto node_index = candidates[chosen]; + const ResourceNode& node = resource_nodes_[node_index]; + auto path_to_node = assignment_path(agent.position, node.position); + if (!path_to_node.reachable) { + tried_nodes[chosen] = 1; + continue; + } + + if (node.needs_tending()) { + ++resource_nodes_[node_index].reserved_workers; + --untended_sites; + agent.resource_node_index = node_index; + agent.route = std::move(path_to_node.positions); + agent.route_cursor = 0; + agent.work_remaining = tending_ticks; + agent.state = agent.route.empty() ? AgentState::Gathering : AgentState::Travelling; + break; + } + + std::vector tried_storages(storages_.size(), 0); + std::size_t storage_index = storages_.size(); + PathResult path_to_storage; + for (;;) { + storage_index = storages_.size(); + std::int32_t storage_distance = std::numeric_limits::max(); + for (std::size_t index = 0; index < storages_.size(); ++index) { + const Storage& storage = storages_[index]; + if (tried_storages[index] != 0 || !storage.accepts(node.type) || !has_space(storage)) continue; + const std::int32_t distance = manhattan_distance(node.position, storage.position); + if (distance < storage_distance || (distance == storage_distance && + (storage_index == storages_.size() || storage.id < storages_[storage_index].id))) { + storage_distance = distance; + storage_index = index; + } + } + if (storage_index == storages_.size()) break; + path_to_storage = assignment_path(node.position, storages_[storage_index].position); + if (path_to_storage.reachable) break; + tried_storages[storage_index] = 1; + } + if (storage_index == storages_.size()) { + tried_nodes[chosen] = 1; + continue; + } + + ++resource_nodes_[node_index].reserved_workers; + Storage& storage = storages_[storage_index]; + ++storage.reserved_slots; + if (!has_space(storage)) { + if (storage.kind == StorageKind::Pantry) --open_pantry_count; + else --open_material_store_count; + } + agent.resource_node_index = node_index; + agent.storage_index = storage_index; + agent.haul_route = std::move(path_to_storage.positions); + agent.route = std::move(path_to_node.positions); + agent.route_cursor = 0; + agent.work_remaining = node.site == ResourceSite::Mine ? 12U : gather_ticks; + agent.state = agent.route.empty() ? AgentState::Gathering : AgentState::Travelling; + break; + } + } +} + +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; + for (std::size_t index = 0; index < production_orders_.size(); ++index) { + ProductionOrder& order = production_orders_[index]; + if (order.state != JobState::Available || (order.recipe == RecipeId::WeaveCloth) != weaving) continue; + + 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; + }); + if (site_busy) continue; + + const Recipe recipe = recipe_for(order); + const bool construction = is_construction(order.recipe); + enum class Access { Unknown, Reachable, Unreachable }; + std::vector storage_access(construction || weaving ? storages_.size() : 0, Access::Unknown); + std::vector materials; + bool supplied = true; + for (const ItemStack& ingredient : recipe.ingredients) { + std::uint32_t remaining = ingredient.count; + for (std::size_t storage_index = 0; storage_index < storages_.size() && remaining > 0; + ++storage_index) { + Storage& storage = storages_[storage_index]; + const auto stack = stack_position(storage, ingredient.type); + if (stack == storage.items.end() || stack->type != ingredient.type) continue; + const auto count = std::min(remaining, stack->count - stack->reserved); + if (count == 0) continue; + if (!storage_access.empty()) { + auto& access = storage_access[storage_index]; + if (access == Access::Unknown) { + access = assignment_path(storage.position, order.position).reachable + ? Access::Reachable : Access::Unreachable; + } + if (access == Access::Unreachable) continue; + } + materials.push_back({storage_index, ingredient.type, count}); + remaining -= count; + } + if (remaining != 0) { + supplied = false; + break; + } + } + if (!supplied) continue; + + std::vector stops; + if (construction) { + for (std::size_t s = 0; s < storage_access.size(); ++s) { + if (storage_access[s] == Access::Reachable) stops.push_back({s, {}}); + } + for (std::size_t i = 0; i < stops.size(); ++i) { + const auto from = storages_[stops[i].storage_index].position; + const auto to = i + 1 == stops.size() + ? order.position : storages_[stops[i + 1].storage_index].position; + auto path = assignment_path(from, to); + // Each stop can reach the site on the same undirected map. + assert(path.reachable); + stops[i].route_to_next = std::move(path.positions); + } + } + const GridPosition destination = construction + ? storages_[stops.front().storage_index].position : order.position; + for (Agent& agent : agents_) { + if (agent.state != AgentState::Idle || !can_take_work(agent, Profession::Builder)) continue; + auto path = assignment_path(agent.position, destination); + if (!path.reachable) continue; + + for (const auto& material : materials) { + stack_position(storages_[material.storage_index], material.type)->reserved += material.count; + } + order.materials = std::move(materials); + order.delivery_stops = std::move(stops); + order.state = JobState::InProgress; + agent.production_index = index; + agent.route = std::move(path.positions); + agent.route_cursor = 0; + agent.work_remaining = recipe.ticks; + agent.state = construction ? AgentState::FetchingMaterials : + (agent.route.empty() ? AgentState::Working : AgentState::Travelling); + break; + } + } +} + +namespace { + +void take_reserved_material(Storage& storage, const MaterialReservation& material) { + auto stack = stack_position(storage, material.type); + assert(stack != storage.items.end() && stack->type == material.type); + assert(stack->reserved >= material.count && stack->count >= stack->reserved); + stack->reserved -= material.count; + stack->count -= material.count; + if (stack->count == 0) storage.items.erase(stack); +} + +} // namespace + +void World::assign_meals() { + for (Agent& agent : agents_) { + if (agent.hunger < max_hunger) ++agent.hunger; + } + + std::vector stocked_pantries; + for (std::size_t i = 0; i < storages_.size(); ++i) { + Storage& storage = storages_[i]; + if (storage.kind != StorageKind::Pantry) continue; + const auto stack = stack_position(storage, ItemType::Berries); + if (stack != storage.items.end() && stack->count > stack->reserved) stocked_pantries.push_back(i); + } + for (Agent& agent : agents_) { + if (stocked_pantries.empty()) break; + if (agent.state != AgentState::Idle || !agent.hungry()) continue; + std::sort(stocked_pantries.begin(), stocked_pantries.end(), [&](std::size_t left, std::size_t right) { + const auto left_distance = manhattan_distance(agent.position, storages_[left].position); + const auto right_distance = manhattan_distance(agent.position, storages_[right].position); + return left_distance == right_distance ? left < right : left_distance < right_distance; + }); + for (auto pantry = stocked_pantries.begin(); pantry != stocked_pantries.end(); ++pantry) { + Storage& storage = storages_[*pantry]; + auto path = assignment_path(agent.position, storage.position); + if (!path.reachable) continue; + + auto stack = stack_position(storage, ItemType::Berries); + ++stack->reserved; + agent.storage_index = *pantry; + agent.state = AgentState::GoingToEat; + agent.route = std::move(path.positions); + agent.route_cursor = 0; + if (stack->count == stack->reserved) stocked_pantries.erase(pantry); + break; + } + } +} + +void World::finish_meal_step(Agent& agent) { + if (agent.state == AgentState::GoingToEat) { + if (agent.route_cursor != agent.route.size()) return; + take_reserved_material(storages_[agent.storage_index], {agent.storage_index, ItemType::Berries, 1}); + agent.inventory.add(ItemType::Berries); + agent.storage_index = no_entity_index; + agent.route.clear(); + agent.route_cursor = 0; + agent.work_remaining = meal_ticks; + agent.state = AgentState::Eating; + return; + } + if (--agent.work_remaining != 0) return; + agent.inventory.remove(ItemType::Berries); + agent.hunger = 0; + agent.state = AgentState::Idle; + ++meals_eaten_; +} + +void World::assign_rest() { + for (Agent& agent : agents_) { + if (agent.state != AgentState::Sleeping && agent.fatigue < max_fatigue) ++agent.fatigue; + if (agent.state != AgentState::Idle || !agent.tired()) continue; + + const auto* bed = assigned_bed(agent.id); + if (bed != nullptr && !resting_at(bed->position, agent.id)) { + auto path = assignment_path(agent.position, bed->position); + if (path.reachable) { + agent.route = std::move(path.positions); + agent.route_cursor = 0; + agent.state = AgentState::GoingToSleep; + agent.resting_on_ground = false; + continue; + } + } + if (agent.fatigue != max_fatigue) continue; + if (ground_rest_cell(agent.position, agent.id)) { + agent.resting_on_ground = true; + agent.state = AgentState::Sleeping; + continue; + } + for (const auto offset : adjacent_cells) { + const GridPosition nearby{agent.position.x + offset.x, agent.position.y + offset.y}; + if (!ground_rest_cell(nearby, agent.id)) continue; + agent.route = {nearby}; + agent.route_cursor = 0; + agent.resting_on_ground = true; + agent.state = AgentState::GoingToSleep; + break; + } + } +} + +void World::finish_rest_step(Agent& agent) { + if (agent.state == AgentState::GoingToSleep) { + if (agent.route_cursor != agent.route.size()) return; + agent.route.clear(); + agent.route_cursor = 0; + agent.state = AgentState::Sleeping; + return; + } + + const bool in_bed = !agent.resting_on_ground; + const auto recovery = in_bed ? bed_recovery : ground_recovery; + agent.fatigue -= std::min(agent.fatigue, recovery); + if (agent.fatigue <= (in_bed ? 0 : ground_wake_fatigue)) { + agent.resting_on_ground = false; + agent.state = AgentState::Idle; + } +} + +void World::advance_construction_delivery(Agent& agent) { + ProductionOrder& order = production_orders_[agent.production_index]; + if (order.collected_stops == order.delivery_stops.size()) { + for (const auto& material : order.materials) { + agent.inventory.remove(material.type, material.count); + } + order.delivery_stops.clear(); + order.collected_stops = 0; + agent.state = AgentState::Working; + agent.route.clear(); + agent.route_cursor = 0; + return; + } + + auto& stop = order.delivery_stops[order.collected_stops]; + for (const auto& material : order.materials) { + if (material.storage_index == stop.storage_index) { + take_reserved_material(storages_[stop.storage_index], material); + agent.inventory.add(material.type, material.count); + } + } + ++order.collected_stops; + agent.route = std::move(stop.route_to_next); + agent.route_cursor = 0; + agent.state = AgentState::Hauling; +} + +void World::finish_production(Agent& agent) { + ProductionOrder& order = production_orders_[agent.production_index]; + const Recipe recipe = recipe_for(order); + assert(!order.materials.empty()); + if (recipe.output != ItemType::None) { + for (const auto& material : order.materials) { + take_reserved_material(storages_[material.storage_index], material); + } + // Crafting replaces one raw item with one finished item in the same store. + storages_[order.materials.front().storage_index].add_item(recipe.output); + } + order.materials.clear(); + if (order.recipe == RecipeId::BuildBed && + (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::WeaveCloth) { + order.state = JobState::Available; + } else { + order.state = JobState::Completed; + } + agent.production_index = no_entity_index; + agent.state = AgentState::Idle; + agent.route.clear(); + agent.route_cursor = 0; +} + +void World::grow_sites() { + for (auto& node : resource_nodes_) { + if (node.site == ResourceSite::Natural) { + if (tick_ % berry_regrowth_ticks == 0 && node.type == ItemType::Berries && + node.quantity < node.initial_quantity) ++node.quantity; + } else if (node.growth_at != 0 && tick_ >= node.growth_at) { + node.quantity = node.initial_quantity; + node.growth_at = 0; + } + } +} + +void World::step(TickProfile* profile) { + if (paused_) return; + if (!worker_pool_ && !agents_.empty()) worker_pool_ = std::make_unique(worker_count_); + using Clock = std::chrono::steady_clock; + auto phase_start = profile ? Clock::now() : Clock::time_point{}; + const auto finish_phase = [&](std::chrono::nanoseconds TickProfile::*phase) { + if (!profile) return; + const auto now = Clock::now(); + profile->*phase += std::chrono::duration_cast(now - phase_start); + phase_start = now; + }; + + if (scenario_active_ || command_revision_ != 0 || tick_ % berry_regrowth_ticks == 0) grow_sites(); + if (hunger_enabled_) assign_meals(); + if (scenario_active_) assign_rest(); + finish_phase(&TickProfile::growth_and_needs); + if (work_priority_ == WorkPriority::FoodFirst) assign_resource_tasks(ResourceFocus::Food); + finish_phase(&TickProfile::resource_assignment); + assign_production_tasks(false); + if (std::any_of(production_orders_.begin(), production_orders_.end(), [](const auto& order) { + return order.recipe == RecipeId::WeaveCloth && order.state == JobState::Available; + })) assign_production_tasks(true); + finish_phase(&TickProfile::production_assignment); + assign_idle_agents(); + finish_phase(&TickProfile::generic_assignment); + if (work_priority_ == WorkPriority::BuildingFirst) assign_resource_tasks(ResourceFocus::Materials); + assign_resource_tasks(); + finish_phase(&TickProfile::resource_assignment); + + const auto can_work = [this](const Agent& agent) { + if (!scenario_active_) return true; + const auto interval = 1U + static_cast(agent.hungry()) + static_cast(agent.tired()); + return tick_ % interval == 0; + }; + const auto advance_agents = [this, can_work](std::size_t begin, std::size_t end) { + std::uint64_t completed = 0; + for (std::size_t index = begin; index < end; ++index) { + Agent& agent = agents_[index]; + if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling || + agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat || + agent.state == AgentState::GoingToSleep) && + agent.route_cursor < agent.route.size()) { + agent.position = agent.route[agent.route_cursor++]; + if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) { + agent.state = agent.resource_node_index == no_entity_index + ? AgentState::Working : AgentState::Gathering; + } + } + + if (agent.state == AgentState::Gathering) { + if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining; + continue; + } + if (agent.state != AgentState::Working) continue; + if (agent.work_remaining > 0 && can_work(agent)) --agent.work_remaining; + if (agent.work_remaining != 0) continue; + if (agent.production_index != no_entity_index) continue; + + const auto job = std::lower_bound( + jobs_.begin(), jobs_.end(), agent.current_job, + [](const WorkJob& candidate, JobId id) { return candidate.id < id; }); + if (job != jobs_.end() && job->id == agent.current_job) { + job->state = JobState::Completed; + ++completed; + } + agent.current_job = 0; + agent.state = AgentState::Idle; + agent.route.clear(); + agent.route_cursor = 0; + } + return completed; + }; + + if (!agents_.empty()) { + const auto chunk_count = std::min(worker_count_, agents_.size()); + std::vector> futures; + futures.reserve(chunk_count); + for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) { + const std::size_t begin = chunk * agents_.size() / chunk_count; + const std::size_t end = (chunk + 1) * agents_.size() / chunk_count; + futures.push_back(worker_pool_->submit([&advance_agents, begin, end] { + return advance_agents(begin, end); + })); + } + for (auto& future : futures) jobs_completed_ += future.get(); + } + + for (Agent& agent : agents_) { + if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) { + finish_meal_step(agent); + continue; + } + if (agent.state == AgentState::GoingToSleep || agent.state == AgentState::Sleeping) { + finish_rest_step(agent); + continue; + } + if (agent.production_index != no_entity_index && agent.route_cursor == agent.route.size() && + (agent.state == AgentState::FetchingMaterials || agent.state == AgentState::Hauling)) { + advance_construction_delivery(agent); + continue; + } + if (agent.state == AgentState::Working && agent.production_index != no_entity_index && + agent.work_remaining == 0) { + finish_production(agent); + } + if (agent.state == AgentState::Gathering) { + if (agent.work_remaining == 0 && agent.resource_node_index < resource_nodes_.size()) { + ResourceNode& node = resource_nodes_[agent.resource_node_index]; + if (agent.storage_index == no_entity_index) { + node.growth_at = tick_ + growing_time(node.site); + --node.reserved_workers; + agent.resource_node_index = no_entity_index; + agent.state = AgentState::Idle; + agent.route.clear(); + agent.route_cursor = 0; + continue; + } + if (node.quantity > 0) --node.quantity; + if (node.reserved_workers > 0) --node.reserved_workers; + agent.inventory.add(node.type); + agent.resource_node_index = no_entity_index; + agent.route = std::move(agent.haul_route); + agent.haul_route.clear(); + agent.route_cursor = 0; + agent.state = AgentState::Hauling; + } + } + + if (agent.state == AgentState::Hauling && agent.route_cursor == agent.route.size() && + agent.storage_index < storages_.size()) { + Storage& storage = storages_[agent.storage_index]; + const ItemType cargo = agent.inventory.first_item(); + if (storage.reserved_slots > 0) --storage.reserved_slots; + storage.add_item(cargo); + agent.inventory.remove(cargo); + agent.storage_index = no_entity_index; + agent.state = AgentState::Idle; + agent.route.clear(); + agent.route_cursor = 0; + } + } + + if (scenario_active_) update_scenario(); + ++tick_; + finish_phase(&TickProfile::advancement); +} + +void World::write_svg(const std::string& path) const { + std::ofstream output(path); + if (!output) { + throw std::runtime_error("could not open SVG output path"); + } + + constexpr std::int32_t cell_size = 10; + const std::int32_t pixel_width = width_ * cell_size; + const std::int32_t pixel_height = height_ * cell_size; + output << "\n" + << "\n" + << "\n"; + + output << "\n"; + + for (std::int32_t y = 0; y < height_; ++y) { + for (std::int32_t x = 0; x < width_; ++x) { + if (blocked_[cell_index(GridPosition{x, y})] != 0) { + output << "\n"; + } + } + } + + for (const WorkJob& job : jobs_) { + const std::int32_t cx = job.position.x * cell_size + cell_size / 2; + const std::int32_t cy = job.position.y * cell_size + cell_size / 2; + const char* fill = job.state == JobState::Available ? "#4b9b67" : + job.state == JobState::InProgress ? "#e6a23c" : "#a9adaf"; + output << "\n"; + } + + for (const ResourceNode& node : resource_nodes_) { + if (node.quantity == 0) continue; + const std::int32_t cx = node.position.x * cell_size + cell_size / 2; + const std::int32_t cy = node.position.y * cell_size + cell_size / 2; + const char* fill = node.type == ItemType::Berries ? "#ad507b" : + node.type == ItemType::Wood ? "#4b8f55" : "#78878b"; + output << "\n"; + } + for (const Storage& storage : storages_) { + const std::int32_t cx = storage.position.x * cell_size + cell_size / 2; + const std::int32_t cy = storage.position.y * cell_size + cell_size / 2; + const char* fill = storage.kind == StorageKind::Pantry ? "#ad507b" : "#a66e36"; + output << "\n"; + } + for (const ProductionOrder& order : production_orders_) { + if (!is_construction(order.recipe)) continue; + const auto cx = order.position.x * cell_size + cell_size / 2; + const auto cy = order.position.y * cell_size + cell_size / 2; + const char* fill = order.state == JobState::Completed ? "#ae694a" : + order.state == JobState::InProgress ? "#dfa54b" : "#93b8c8"; + output << "\n"; + } + + for (const Agent& agent : agents_) { + if ((agent.state == AgentState::Travelling || agent.state == AgentState::Hauling || + agent.state == AgentState::FetchingMaterials || agent.state == AgentState::GoingToEat || + agent.state == AgentState::GoingToSleep) && + agent.route_cursor < agent.route.size()) { + const std::uint32_t hue = static_cast((agent.id * 67ULL) % 360ULL); + output << "\n"; + } + } + + for (const Agent& agent : agents_) { + const std::int32_t cx = agent.position.x * cell_size + cell_size / 2; + const std::int32_t cy = agent.position.y * cell_size + cell_size / 2; + const char* fill = agent.state == AgentState::Idle ? "#3f6fba" : + (agent.state == AgentState::Travelling || + agent.state == AgentState::FetchingMaterials) ? "#7b4cc2" : + agent.state == AgentState::Working ? "#cf5746" : + agent.state == AgentState::Gathering ? "#b98034" : + agent.state == AgentState::Hauling ? "#328e89" : + (agent.state == AgentState::GoingToSleep || agent.state == AgentState::Sleeping) + ? "#536690" : "#ad507b"; + output << "\n"; + } + + output << "" + << "Residents: " << agents_.size() << " | Jobs completed: " << jobs_completed_ + << " | Stored wood: " << std::accumulate(storages_.begin(), storages_.end(), std::uint64_t{0}, + [](std::uint64_t total, const Storage& storage) { return total + storage.item_count(ItemType::Wood); }) + << " | Stone: " << std::accumulate(storages_.begin(), storages_.end(), std::uint64_t{0}, + [](std::uint64_t total, const Storage& storage) { return total + storage.item_count(ItemType::Stone); }) + << " | Tick: " << tick_ << "\n" + << "" + << "Residents: blue idle, purple travelling, red working, gold gathering, teal hauling" + << " | Resources: green wood, gray stone, brown storage" + << " | Routes: colored lines\n\n"; +} + +std::uint64_t World::tick() const noexcept { return tick_; } +std::uint64_t World::seed() const noexcept { return seed_; } +std::int32_t World::width() const noexcept { return width_; } +std::int32_t World::height() const noexcept { return height_; } +const std::vector& World::agents() const noexcept { return agents_; } +const std::vector& World::jobs() const noexcept { return jobs_; } +const std::vector& World::resource_nodes() const noexcept { return resource_nodes_; } +const std::vector& World::storages() const noexcept { return storages_; } +const std::vector& World::production_orders() const noexcept { return production_orders_; } +std::uint64_t World::path_searches() const noexcept { return path_searches_; } +std::uint64_t World::path_nodes_visited() const noexcept { return path_nodes_visited_; } +std::uint64_t World::jobs_completed() const noexcept { return jobs_completed_; } +std::uint64_t World::meals_eaten() const noexcept { return meals_eaten_; } +std::size_t World::worker_count() const noexcept { return worker_count_; } + +} // namespace settlement diff --git a/engine/src/world_save.cpp b/engine/src/world_save.cpp new file mode 100644 index 0000000..8a73b39 --- /dev/null +++ b/engine/src/world_save.cpp @@ -0,0 +1,598 @@ +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { +namespace { + +constexpr std::string_view signature = "SETTLERS"; +constexpr std::uint32_t save_version = 9; +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; + +void require_save(bool condition, const char* error) { + if (!condition) throw std::runtime_error(error); +} + +class SaveWriter { +public: + static constexpr bool reading = false; + explicit SaveWriter(std::ostream& stream) : stream_(stream) {} + + template + void field(T value) { + if constexpr (std::is_enum_v) { + field(static_cast>(value)); + } else { + using Bits = std::make_unsigned_t; + std::uint64_t bits = std::bit_cast(value); + for (std::size_t i = 0; i < sizeof(T); ++i) { + const auto byte = static_cast(bits); + require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); + ++bytes_; + stream_.put(std::bit_cast(byte)); + require_save(static_cast(stream_), "Could not write the save."); + bits >>= 8; + } + } + } + +private: + std::ostream& stream_; + std::size_t bytes_ = 0; +}; + +class SaveReader { +public: + static constexpr bool reading = true; + explicit SaveReader(std::istream& stream) : stream_(stream) {} + + template + void field(T& value, bool payload = true) { + if constexpr (std::is_enum_v) { + std::underlying_type_t bits = 0; + field(bits, payload); + value = static_cast(bits); + } else { + std::uint64_t bits = 0; + for (std::size_t i = 0; i < sizeof(T); ++i) { + const int next = stream_.get(); + require_save(next != std::char_traits::eof(), "Save is incomplete or unreadable."); + const auto byte = static_cast(next); + if (payload) { + require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); + ++bytes_; + if (legacy_footer_) legacy_digest_ = (legacy_digest_ ^ byte) * 1099511628211ULL; + } + bits |= static_cast(byte) << (8 * i); + } + value = std::bit_cast(static_cast>(bits)); + } + } + + void set_version(std::uint32_t version) { + legacy_footer_ = version <= last_legacy_footer_version; + } + + void finish() { + if (legacy_footer_) { + std::uint64_t expected = 0; + field(expected, false); + require_save(legacy_digest_ == expected, "Legacy save integrity footer does not match."); + } + require_save(stream_.peek() == std::char_traits::eof() && !stream_.bad(), + "Save contains unexpected trailing data."); + } + +private: + std::istream& stream_; + std::size_t bytes_ = 0; + bool legacy_footer_ = true; + std::uint64_t legacy_digest_ = 14695981039346656037ULL; +}; + +template +void sequence(Archive& archive, Vector& values, std::size_t limit, Visit visit) { + require_save(values.size() <= limit, "Save contains too many records."); + auto length = static_cast(values.size()); + archive.field(length); + require_save(length <= limit, "Save contains too many records."); + if constexpr (Archive::reading) { + for (std::uint32_t i = 0; i < length; ++i) { + values.emplace_back(); + visit(values.back()); + } + } else { + for (const auto& value : values) visit(value); + } +} + +template +void position(Archive& archive, Position& value) { + archive.field(value.x); + archive.field(value.y); +} + +template +void route(Archive& archive, Route& points, std::size_t cells) { + sequence(archive, points, cells, [&](auto& point) { position(archive, point); }); +} + +template +void index(Archive& archive, Index& value) { + // Store zero for missing links and one-based indices for present links on all platforms. + std::uint64_t wire = value == no_entity_index ? 0 : static_cast(value) + 1; + archive.field(wire); + if constexpr (Archive::reading) { + require_save(wire <= max_records, "Save contains an invalid index."); + value = wire == 0 ? no_entity_index : static_cast(wire - 1); + } +} + +template +void offset(Archive& archive, Size& value) { + auto wire = static_cast(value); + archive.field(wire); + require_save(wire <= max_records, "Save contains an invalid offset."); + if constexpr (Archive::reading) value = static_cast(wire); +} + +constexpr std::size_t item_types = item_type_count; +using ItemCounts = std::array; + +std::size_t item_index(ItemType type) { + const auto raw = static_cast(type); + require_save(raw > 0 && raw <= item_types, "Save contains an unknown item."); + return raw - 1; +} + +template +void stack_fields(auto& archive, Stack& stack) { + archive.field(stack.type); + archive.field(stack.count); + archive.field(stack.reserved); +} + +template +void flag(Archive& archive, Flag& value) { + auto wire = static_cast(value); + archive.field(wire); + require_save(wire <= 1, "Save contains an invalid flag."); + if constexpr (Archive::reading) value = wire != 0; +} + +} // namespace + +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_count = static_cast(max_item); + archive.field(world.tick_); + archive.field(world.path_searches_); + archive.field(world.path_nodes_visited_); + archive.field(world.jobs_completed_); + archive.field(world.meals_eaten_); + flag(archive, world.hunger_enabled_); + archive.field(world.next_agent_id_); + archive.field(world.next_job_id_); + archive.field(world.next_resource_node_id_); + archive.field(world.next_storage_id_); + const auto cells = world.blocked_.size(); + for (auto& cell : world.blocked_) archive.field(cell); + + sequence(archive, world.agents_, max_records, [&](auto& agent) { + archive.field(agent.id); + position(archive, agent.position); + archive.field(agent.state); + archive.field(agent.current_job); + route(archive, agent.route, cells); + offset(archive, agent.route_cursor); + archive.field(agent.work_remaining); + index(archive, agent.resource_node_index); + index(archive, agent.storage_index); + const auto inventory_types = version >= 3 ? max_item_count : static_cast(ItemType::Berries); + for (std::size_t i = 1; i <= inventory_types; ++i) { + const auto type = static_cast(i); + auto count = agent.inventory.item_count(type); + archive.field(count); + if constexpr (Archive::reading) { + if (count != 0) agent.inventory.add(type, count); + } + } + route(archive, agent.haul_route, cells); + index(archive, agent.production_index); + archive.field(agent.hunger); + if (version >= 4) archive.field(agent.fatigue); + if (version >= 5) flag(archive, agent.resting_on_ground); + if (version >= 6) archive.field(agent.profession); + }); + sequence(archive, world.jobs_, max_records, [&](auto& job) { + archive.field(job.id); + position(archive, job.position); + archive.field(job.work_required); + archive.field(job.work_remaining); + archive.field(job.state); + }); + sequence(archive, world.resource_nodes_, max_records, [&](auto& node) { + archive.field(node.id); + position(archive, node.position); + archive.field(node.type); + archive.field(node.quantity); + archive.field(node.initial_quantity); + archive.field(node.reserved_workers); + if (version >= 2) flag(archive, node.foraging_enabled); + if (version >= 5) { + archive.field(node.site); + require_save(version >= 7 || node.site <= ResourceSite::Mine, "Unknown site for save version."); + archive.field(node.growth_at); + } + }); + sequence(archive, world.storages_, max_records, [&](auto& storage) { + archive.field(storage.id); + position(archive, storage.position); + archive.field(storage.capacity); + archive.field(storage.reserved_slots); + archive.field(storage.kind); + sequence(archive, storage.items, max_item_count, [&](auto& stack) { + stack_fields(archive, stack); + require_save(stack.type <= max_item, "Unknown item for save version."); + }); + if constexpr (Archive::reading) { + storage.items.reserve(storage.kind == StorageKind::Pantry ? 1 : item_types - 1); + } + }); + sequence(archive, world.production_orders_, max_records, [&](auto& order) { + position(archive, order.position); + archive.field(order.recipe); + require_save(version >= 2 || order.recipe <= RecipeId::BuildCabin, "Unknown recipe for save version."); + require_save(version >= 7 || order.recipe <= RecipeId::BuildBed, "Unknown recipe for save version."); + archive.field(order.state); + sequence(archive, order.materials, item_types, [&](auto& material) { + index(archive, material.storage_index); + archive.field(material.type); + require_save(material.type <= max_item, "Unknown material for save version."); + archive.field(material.count); + }); + sequence(archive, order.delivery_stops, item_types, [&](auto& stop) { + index(archive, stop.storage_index); + route(archive, stop.route_to_next, cells); + }); + offset(archive, order.collected_stops); + if (version >= 2) archive.field(order.bed_owner); + if (version >= 3) { + archive.field(order.bed_base); + archive.field(order.bed_stage); + } + }); + if (version >= 2) { + flag(archive, world.scenario_active_); + flag(archive, world.paused_); + flag(archive, world.scenario_completed_); + archive.field(world.work_priority_); + position(archive, world.scenario_sawmill_); + for (auto& sequence : world.player_sequences_) archive.field(sequence); + archive.field(world.command_revision_); + if (version >= 3) flag(archive, world.staged_beds_); + } + } + + static void validate(const World& world); +}; + +void WorldSaveCodec::validate(const World& world) { + const auto invalid = [](bool good) { require_save(good, "Save contains inconsistent simulation state."); }; + const auto inside = [&](GridPosition p) { + return p.x >= 0 && p.x < world.width_ && p.y >= 0 && p.y < world.height_; + }; + const auto valid_route = [&](const auto& points) { + invalid(std::all_of(points.begin(), points.end(), inside)); + }; + const auto check_ids = [&](const auto& records, std::uint64_t next_id) { + std::uint64_t previous = 0; + for (const auto& record : records) { + invalid(record.id > previous && inside(record.position)); + previous = record.id; + } + invalid(next_id > previous); + }; + check_ids(world.agents_, world.next_agent_id_); + check_ids(world.jobs_, world.next_job_id_); + check_ids(world.resource_nodes_, world.next_resource_node_id_); + check_ids(world.storages_, world.next_storage_id_); + invalid(world.work_priority_ <= WorkPriority::BuildingFirst); + std::uint64_t revision = 0; + for (const auto sequence : world.player_sequences_) { + invalid(sequence <= std::numeric_limits::max() - revision); + revision += sequence; + } + invalid(revision == world.command_revision_); + if (world.scenario_active_) { + invalid(world.hunger_enabled_ && world.is_walkable(world.scenario_sawmill_)); + } else { + invalid(!world.paused_ && !world.scenario_completed_ && !world.staged_beds_ && + world.work_priority_ == WorkPriority::Balanced); + } + invalid(std::all_of(world.blocked_.begin(), world.blocked_.end(), + [](std::uint8_t cell) { return cell <= 1; })); + + std::uint64_t completed = 0; + for (const auto& job : world.jobs_) { + invalid(job.state <= JobState::Completed && job.work_required > 0 && job.work_remaining <= job.work_required); + if (job.state == JobState::Completed) ++completed; + } + invalid(completed == world.jobs_completed_); + for (const auto& node : world.resource_nodes_) { + invalid(node.initial_quantity > 0 && node.quantity <= node.initial_quantity && + node.reserved_workers <= (node.needs_tending() ? 1U : node.quantity) && + (node.foraging_enabled || node.type == ItemType::Berries)); + invalid(node.site <= ResourceSite::FlaxField); + if (node.site == ResourceSite::Natural) { + invalid(node.growth_at == 0 && + (node.type == ItemType::Wood || node.type == ItemType::Stone || node.type == ItemType::Berries)); + } else { + invalid(node.type == site_resource(node.site) && world.is_walkable(node.position)); + invalid(node.site == ResourceSite::Mine ? node.growth_at == 0 : + (node.growth_at == 0 || node.quantity == 0)); + } + } + for (const auto& storage : world.storages_) { + invalid(storage.kind <= StorageKind::Pantry && world.is_walkable(storage.position) && + storage.capacity > 0 && storage.total_items() + storage.reserved_slots <= storage.capacity); + auto previous = ItemType::None; + for (const auto& stack : storage.items) { + static_cast(item_index(stack.type)); + invalid(stack.type > previous && storage.accepts(stack.type) && stack.count > 0 && + stack.reserved <= stack.count); + previous = stack.type; + } + } + + std::vector reserved_items(world.storages_.size()); + std::vector expected_cargo(world.production_orders_.size()); + std::vector bed_owners; + for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { + const auto& order = world.production_orders_[i]; + invalid(order.recipe <= RecipeId::WeaveCloth && order.state <= JobState::Completed && + world.is_walkable(order.position) && + (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); + invalid(order.bed_base <= BedBase::Stone && order.bed_stage <= BedStage::Pillow && + (order.bed_stage == BedStage::Legacy || + (world.staged_beds_ && order.recipe == RecipeId::BuildBed)) && + (order.state != JobState::Completed || order.bed_stage == BedStage::Legacy || + order.bed_stage == BedStage::Pillow)); + if (order.bed_owner != 0) { + invalid(world.scenario_active_ && order.recipe == RecipeId::BuildBed && order.state == JobState::Completed); + const auto resident = std::lower_bound(world.agents_.begin(), world.agents_.end(), order.bed_owner, + [](const Agent& agent, AgentId id) { return agent.id < id; }); + invalid(resident != world.agents_.end() && resident->id == order.bed_owner); + bed_owners.push_back(order.bed_owner); + } + if (order.state != JobState::InProgress) { + invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0); + continue; + } + + const bool construction = is_construction(order.recipe); + invalid(order.collected_stops <= order.delivery_stops.size() && (construction || order.delivery_stops.empty())); + std::size_t last_storage = 0; + bool first_stop = true; + for (const auto& stop : order.delivery_stops) { + invalid(stop.storage_index < world.storages_.size() && (first_stop || last_storage < stop.storage_index)); + invalid(std::any_of(order.materials.begin(), order.materials.end(), + [&](const auto& material) { return material.storage_index == stop.storage_index; })); + valid_route(stop.route_to_next); + first_stop = false; + last_storage = stop.storage_index; + } + + ItemCounts ingredients{}; + for (const auto& material : order.materials) { + const auto type = item_index(material.type); + invalid(material.storage_index < world.storages_.size() && material.count > 0 && + world.storages_[material.storage_index].kind == StorageKind::Materials); + ingredients[type] += material.count; + if (!construction) { + 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(), + [&](const auto& entry) { return entry.storage_index == material.storage_index; }); + invalid(stop != order.delivery_stops.end()); + if (static_cast(stop - order.delivery_stops.begin()) < order.collected_stops) { + expected_cargo[i][type] += material.count; + } else { + reserved_items[material.storage_index][type] += material.count; + } + } + } + // These are the ingredient requirements associated with the saved recipe IDs. + ItemCounts required{}; + switch (order.recipe) { + case RecipeId::SawPlank: required[item_index(ItemType::Wood)] = 1; break; + case RecipeId::CutStoneBlock: required[item_index(ItemType::Stone)] = 1; break; + case RecipeId::BuildCabin: + required[item_index(ItemType::Plank)] = 3; + required[item_index(ItemType::StoneBlock)] = 2; + break; + case RecipeId::BuildBed: required[item_index(order.bed_material())] = 1; break; + case RecipeId::WeaveCloth: required[item_index(ItemType::Flax)] = 1; break; + } + invalid(ingredients == required); + } + std::sort(bed_owners.begin(), bed_owners.end()); + invalid(std::adjacent_find(bed_owners.begin(), bed_owners.end()) == bed_owners.end()); + + std::vector reserved_nodes(world.resource_nodes_.size()); + std::vector reserved_slots(world.storages_.size()); + std::vector job_claims(world.jobs_.size()); + std::vector order_claims(world.production_orders_.size()); + std::vector rest_destinations; + for (const auto& agent : world.agents_) { + using enum AgentState; + invalid(agent.state <= Sleeping && agent.route_cursor <= agent.route.size() && agent.hunger <= max_hunger && + (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); + valid_route(agent.route); + valid_route(agent.haul_route); + const bool has_job = agent.current_job != 0; + const bool has_order = agent.production_index != no_entity_index; + 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); + if (has_job) { + invalid(!has_order && !has_storage && !has_source && agent.inventory.empty() && + (agent.state == Travelling || agent.state == Working) && agent.work_remaining > 0); + const auto job = std::lower_bound(world.jobs_.begin(), world.jobs_.end(), agent.current_job, + [](const WorkJob& entry, JobId id) { return entry.id < id; }); + invalid(job != world.jobs_.end() && job->id == agent.current_job && job->state == JobState::InProgress); + auto& claimed = job_claims[static_cast(job - world.jobs_.begin())]; + invalid(claimed == 0); + claimed = 1; + } else if (has_order) { + invalid(!has_storage && !has_source && agent.production_index < world.production_orders_.size() && + agent.work_remaining > 0); + const auto& order = world.production_orders_[agent.production_index]; + invalid(order.state == JobState::InProgress && order_claims[agent.production_index] == 0); + order_claims[agent.production_index] = 1; + 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))); + } + 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]); + } + } else if (has_source) { + invalid(agent.resource_node_index < world.resource_nodes_.size() && + (agent.state == Travelling || agent.state == Gathering) && agent.inventory.empty() && + agent.work_remaining > 0); + const auto& source = world.resource_nodes_[agent.resource_node_index]; + if (has_storage) { + invalid(source.quantity > 0 && world.storages_[agent.storage_index].accepts(source.type)); + ++reserved_slots[agent.storage_index]; + } else { + invalid(source.needs_tending() && agent.haul_route.empty()); + } + ++reserved_nodes[agent.resource_node_index]; + } 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) && + 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) { + const auto type = static_cast(i); + invalid(type == cargo || agent.inventory.item_count(type) == 0); + } + ++reserved_slots[agent.storage_index]; + } else if (agent.state == GoingToEat) { + invalid(world.hunger_enabled_ && has_storage && agent.inventory.empty() && + world.storages_[agent.storage_index].kind == StorageKind::Pantry); + ++reserved_items[agent.storage_index][item_index(ItemType::Berries)]; + } else if (agent.state == Eating) { + invalid(world.hunger_enabled_ && !has_storage && agent.work_remaining > 0 && + agent.inventory.item_count(ItemType::Berries) == 1 && + agent.inventory.first_item() == ItemType::Berries); + } else if (agent.state == GoingToSleep) { + invalid(world.scenario_active_ && !has_storage && agent.inventory.empty() && + agent.work_remaining == 0 && agent.tired() && agent.route_cursor < agent.route.size()); + rest_destinations.push_back(agent.route.back()); + } else if (agent.state == Sleeping) { + invalid(world.scenario_active_ && !has_storage && agent.inventory.empty() && + agent.fatigue > 0 && agent.work_remaining == 0 && agent.route.empty()); + rest_destinations.push_back(agent.position); + } else { + invalid(agent.state == Idle && !has_storage && agent.inventory.empty() && agent.work_remaining == 0); + } + if (agent.state == Sleeping || agent.state == GoingToSleep) { + const auto target = rest_destinations.back(); + const auto* bed = world.assigned_bed(agent.id); + invalid(agent.resting_on_ground ? !world.is_bed_cell(target) : + (bed != nullptr && bed->position == target)); + } + } + std::sort(rest_destinations.begin(), rest_destinations.end(), [](GridPosition left, GridPosition right) { + return left.y < right.y || (left.y == right.y && left.x < right.x); + }); + invalid(std::adjacent_find(rest_destinations.begin(), rest_destinations.end()) == rest_destinations.end()); + for (std::size_t i = 0; i < world.jobs_.size(); ++i) { + invalid((job_claims[i] != 0) == (world.jobs_[i].state == JobState::InProgress)); + } + for (std::size_t i = 0; i < world.production_orders_.size(); ++i) { + invalid((order_claims[i] != 0) == (world.production_orders_[i].state == JobState::InProgress)); + } + for (std::size_t i = 0; i < world.resource_nodes_.size(); ++i) { + invalid(reserved_nodes[i] == world.resource_nodes_[i].reserved_workers); + } + for (std::size_t i = 0; i < world.storages_.size(); ++i) { + invalid(reserved_slots[i] == world.storages_[i].reserved_slots); + for (const auto& stack : world.storages_[i].items) { + const auto type = item_index(stack.type); + invalid(reserved_items[i][type] == stack.reserved); + reserved_items[i][type] = 0; + } + invalid(reserved_items[i] == ItemCounts{}); + } +} + +void World::write_save(std::ostream& stream) const { + SaveWriter archive(stream); + for (char letter : signature) archive.field(letter); + archive.field(save_version); + archive.field(seed_); + archive.field(width_); + archive.field(height_); + WorldSaveCodec::body(archive, *this, save_version); +} + +std::unique_ptr World::read_save(std::istream& stream, std::size_t workers) { + SaveReader archive(stream); + for (char letter : signature) { + char actual = 0; + archive.field(actual); + require_save(actual == letter, "This file is not a settlement save."); + } + std::uint32_t version = 0; + archive.field(version); + require_save(version >= 1 && version <= save_version, "Save file version is not supported."); + archive.set_version(version); + std::uint64_t seed = 0; + std::int32_t width = 0; + std::int32_t height = 0; + archive.field(seed); + archive.field(width); + archive.field(height); + auto world = std::make_unique(seed, width, height, workers); + WorldSaveCodec::body(archive, *world, version); + archive.finish(); + if (version < 5) { + std::vector occupied_ground; + for (auto& agent : world->agents_) { + if (agent.state != AgentState::Sleeping) continue; + const auto* bed = world->assigned_bed(agent.id); + if (bed != nullptr && bed->position == agent.position) continue; + if (world->is_bed_cell(agent.position) || + std::find(occupied_ground.begin(), occupied_ground.end(), agent.position) != occupied_ground.end()) { + agent.state = AgentState::Idle; + } else { + agent.resting_on_ground = true; + occupied_ground.push_back(agent.position); + } + } + } + WorldSaveCodec::validate(*world); + return world; +} + +} // namespace settlement