#include "settlement/core/world.hpp" #include #include #include #include #include #include #include #include #include #include #include #include namespace settlement { namespace { constexpr std::string_view signature = "SETTLERS"; constexpr std::uint32_t save_version = 13; 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 { std::array bytes; Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes})); require_save(writer.writeLittle(value).has_value(), "Could not encode a save field."); // Preserve the stream prefix if writing stops partway through a field. for (char byte : bytes) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; stream_.put(byte); require_save(static_cast(stream_), "Could not write the save."); } } } 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::array bytes; for (char& byte : bytes) { const int next = stream_.get(); require_save(next != std::char_traits::eof(), "Save is incomplete or unreadable."); byte = std::char_traits::to_char_type(next); if (payload) { require_save(bytes_ < max_save_bytes, "Save exceeds the 128 MiB limit."); ++bytes_; } } const auto wire = std::as_bytes(std::span{bytes}); if (payload && legacy_footer_) legacy_digest_ = Void::Hash::fnv1a64_update(legacy_digest_, wire); Void::Binary::Reader reader(wire); const auto decoded = reader.readLittle(); require_save(decoded.has_value(), "Could not decode a save field."); value = *decoded; } } 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; // Legacy footers cover the signature and version, which are read first. bool legacy_footer_ = true; std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis; }; 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 >= 13 ? ItemType::Loom : 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_); 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); 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); 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."); 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."); require_save(version >= 13 || order.recipe <= RecipeId::CraftWoodenDoor, "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::CraftLoom && order.state <= JobState::Completed && world.is_walkable(order.position) && (order.recipe != RecipeId::WeaveCloth || order.state != JobState::Completed)); invalid(!is_carpentry_recipe(order.recipe) || 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)) && (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 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) { 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 (!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(), [&](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; case RecipeId::CraftWoodenDoor: case RecipeId::CraftMedicineCabinet: case RecipeId::CraftMiningRack: case RecipeId::CraftLoom: for (const auto& item : world.carpentry_materials(order.recipe)) { if (item.count) required[item_index(item.type)] = item.count; } 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: case RecipeId::InstallMedicineCabinet: case RecipeId::InstallMiningRack: case RecipeId::InstallLoom: for (const auto& item : world.construction_materials(order.recipe, order.bed_base)) { if (item.count) required[item_index(item.type)] = item.count; } break; } invalid(ingredients == required); } 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::Carpenter); 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()); const bool carpentry = has_order && agent.production_index < world.production_orders_.size() && is_carpentry_recipe(world.production_orders_[agent.production_index].recipe); invalid(agent.haul_route.empty() || has_source || carpentry); 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 && !delivers_materials(order.recipe))); } if (carpentry) { 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); const auto& stops = order.delivery_stops; const auto output_stop = std::find_if(stops.begin(), stops.end(), [storage](const auto& stop) { return stop.storage_index == storage; }); const bool collected = stops.empty() || static_cast(output_stop - stops.begin()) < order.collected_stops; if (collected) ++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]); } } 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 || is_carpentry_item(cargo)) && 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, ExecutionMode mode, WorkerPoolOptions worker_options) { 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, mode, std::move(worker_options)); 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