Exercise order controls with persisted physical cargo
This commit is contained in:
commit
a1c65119a2
13 files changed
+2198
-88
No files matched your search
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace settlement {
|
||||
|
||||
inline constexpr std::uint32_t checkpoint_version = 2;
|
||||
inline constexpr std::uint32_t checkpoint_version = 3;
|
||||
inline constexpr std::string_view checkpoint_signature = "STHCHKPT";
|
||||
inline constexpr std::size_t max_checkpoint_body_bytes = 128 * 1024 * 1024;
|
||||
inline constexpr std::size_t max_checkpoint_metadata_bytes = 64 * 1024;
|
||||
@@ -47,10 +47,10 @@ struct WorldCheckpoint {
|
||||
RulesManifest rules;
|
||||
};
|
||||
|
||||
// Both schemas store magic, schema, metadata length and body length, then world UUID,
|
||||
// All schemas store magic, schema, metadata length and body length, then world UUID,
|
||||
// city, tick, rules fingerprint and the sorted complete package closure. Each
|
||||
// package stores its ID, exact version and SHA-256. The body uses World's save
|
||||
// codec: schema 1 accepts legacy bodies 1–13; schema 2 requires body 14.
|
||||
// codec: schema 1 accepts bodies 1–13; schema 2 requires 14; schema 3 requires 15.
|
||||
// A final SHA-256 covers every preceding byte. Integers are little-endian.
|
||||
// The caller holds a stable World for the entire synchronous encode operation.
|
||||
[[nodiscard]] std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
|
||||
@@ -165,7 +165,7 @@ std::expected<std::string, CheckpointDiagnostic> encode_checkpoint(
|
||||
fail(CheckpointError::LimitExceeded, "metadata_length", "Checkpoint metadata exceeds 64 KiB.");
|
||||
}
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream, WorldSaveFormat::Current14);
|
||||
world.write_save(stream, WorldSaveFormat::Current15);
|
||||
auto body = std::move(stream).str();
|
||||
if (body.size() > max_checkpoint_body_bytes) {
|
||||
fail(CheckpointError::LimitExceeded, "body_length", "Checkpoint world exceeds 128 MiB.");
|
||||
@@ -213,7 +213,7 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
fail(CheckpointError::InvalidFrame, "magic", "Checkpoint signature does not match.");
|
||||
}
|
||||
const auto schema = get<std::uint32_t>(header, "version");
|
||||
if (schema != 1 && schema != checkpoint_version) {
|
||||
if (schema != 1 && schema != 2 && schema != 3) {
|
||||
fail(CheckpointError::UnsupportedVersion, "version", "Checkpoint schema is not supported.");
|
||||
}
|
||||
const auto metadata_size = get<std::uint32_t>(header, "metadata_length");
|
||||
@@ -270,7 +270,8 @@ std::expected<WorldCheckpoint, CheckpointDiagnostic> decode_checkpoint(
|
||||
Void::Binary::Reader body_header(wire_bytes(body).subspan(8, 4));
|
||||
const auto body_version = get<std::uint32_t>(body_header, "world.version");
|
||||
if ((schema == 1 && (body_version < 1 || body_version > 13)) ||
|
||||
(schema == 2 && body_version != 14)) {
|
||||
(schema == 2 && body_version != 14) ||
|
||||
(schema == 3 && body_version != 15)) {
|
||||
fail(CheckpointError::InvalidWorld, "world.version", "Checkpoint schema and world version do not match.");
|
||||
}
|
||||
std::ispanstream stream(std::span<const char>{body.data(), body.size()});
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "settlement/core/inventory_transaction.hpp"
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <tuple>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
||||
bool room(std::uint64_t next, std::uint64_t count) noexcept {
|
||||
return next != 0 && count <= maximum - next;
|
||||
}
|
||||
auto stock(Storage& storage, ItemType item) {
|
||||
return std::find_if(storage.items.begin(), storage.items.end(), [item](const auto& s) { return s.type == item; });
|
||||
}
|
||||
void retarget(TransferExecution& execution, StockOwner from, StackId old_id,
|
||||
StockOwner to, StackId new_id) noexcept {
|
||||
for (auto& claim : execution.reservations) {
|
||||
if (claim.id && claim.kind == ReservationKind::Item && claim.owner == from && claim.stack == old_id) {
|
||||
claim.owner = to;
|
||||
claim.stack = new_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
CustodyRequest operation_request(const Agent& agent, CustodyOperation operation,
|
||||
StorageId source, StorageId destination) {
|
||||
CustodyRequest request;
|
||||
request.key = {CustodyKeyKind::Operation, agent.execution->id, agent.execution->next_operation};
|
||||
request.operation = operation;
|
||||
request.kind = agent.execution->kind;
|
||||
request.production = agent.execution->production;
|
||||
request.source = source;
|
||||
request.destination = destination;
|
||||
return request;
|
||||
}
|
||||
void effects(CustodyResult& result, const Inventory& inventory, StockOwner owner) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto item = static_cast<ItemType>(i);
|
||||
if (inventory.item_count(item)) result.effects[result.effect_count++] =
|
||||
{owner, inventory.stack_id(item), item, inventory.item_count(item)};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StackId Inventory::stack_id(ItemType type) const noexcept {
|
||||
const auto i = static_cast<std::size_t>(type);
|
||||
return i > 0 && i <= stack_ids_.size() ? stack_ids_[i - 1] : 0;
|
||||
}
|
||||
void Inventory::set_stack_id(ItemType type, StackId id) noexcept {
|
||||
const auto i = static_cast<std::size_t>(type);
|
||||
if (i > 0 && i <= stack_ids_.size()) stack_ids_[i - 1] = id;
|
||||
}
|
||||
|
||||
void World::record_custody(std::shared_ptr<const CustodyReceipt> receipt) noexcept {
|
||||
if (custody_receipts_.size() < custody_receipt_limit) custody_receipts_.push_back(std::move(receipt));
|
||||
else {
|
||||
custody_receipts_[custody_receipt_cursor_] = std::move(receipt);
|
||||
custody_receipt_cursor_ = (custody_receipt_cursor_ + 1) % custody_receipt_limit;
|
||||
}
|
||||
}
|
||||
std::shared_ptr<const CustodyReceipt> World::prepare_custody(Agent& agent, CustodyOperation operation,
|
||||
CustodyStatus status, StorageId source, StorageId destination) {
|
||||
if (!agent.execution || !room(agent.execution->next_operation, 1)) return {};
|
||||
custody_receipts_.reserve(custody_receipt_limit);
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
receipt->request = operation_request(agent, operation, source, destination);
|
||||
receipt->result.status = status;
|
||||
receipt->result.transfer = agent.execution->id;
|
||||
return receipt;
|
||||
}
|
||||
void World::commit_custody(Agent& agent, std::shared_ptr<const CustodyReceipt> receipt) noexcept {
|
||||
agent.execution->blocked = receipt->result.status;
|
||||
++agent.execution->next_operation;
|
||||
record_custody(std::move(receipt));
|
||||
}
|
||||
CustodyResult World::custody_request(const CustodyRequest& request) {
|
||||
// The scheduler issues operations. This endpoint recovers their exact result;
|
||||
// it never admits unissued work through an out-of-order retry.
|
||||
for (const auto& receipt : custody_receipts_) {
|
||||
if (receipt->request.key == request.key) {
|
||||
return receipt->request == request ? receipt->result : CustodyResult{CustodyStatus::Conflict};
|
||||
}
|
||||
}
|
||||
if (request.key.id == 0 || request.key.ordinal == 0) return {CustodyStatus::Invalid};
|
||||
if (request.key.kind == CustodyKeyKind::Admission) {
|
||||
const auto actor = std::find_if(agents_.begin(), agents_.end(), [&](const auto& a) { return a.id == request.key.id; });
|
||||
if (actor == agents_.end()) return {CustodyStatus::Invalid};
|
||||
return {request.key.ordinal < actor->next_admission ? CustodyStatus::Stale : CustodyStatus::Future};
|
||||
}
|
||||
if (request.key.kind != CustodyKeyKind::Operation) return {CustodyStatus::Invalid};
|
||||
for (const auto& agent : agents_) {
|
||||
if (agent.execution && agent.execution->id == request.key.id) {
|
||||
return {request.key.ordinal < agent.execution->next_operation ? CustodyStatus::Stale : CustodyStatus::Future};
|
||||
}
|
||||
}
|
||||
return {request.key.id < next_transfer_id_ ? CustodyStatus::Stale : CustodyStatus::Future};
|
||||
}
|
||||
|
||||
bool World::admit_custody(Agent& agent, TransferKind kind, ProductionId production,
|
||||
ResourceNodeId source, StorageId destination, const std::vector<MaterialReservation>& materials) {
|
||||
if (agent.execution || !room(next_transfer_id_, 1) || !room(agent.next_admission, 1) ||
|
||||
materials.size() > custody_material_limit) return false;
|
||||
TransferExecution execution;
|
||||
execution.id = next_transfer_id_;
|
||||
execution.kind = kind;
|
||||
execution.production = production;
|
||||
execution.source = source;
|
||||
execution.destination = destination;
|
||||
auto next = next_reservation_id_;
|
||||
const auto add = [&](Reservation claim) {
|
||||
if (!room(next, 1) || execution.reservation_count == custody_reservation_limit) return false;
|
||||
claim.id = next++;
|
||||
execution.reservations[execution.reservation_count++] = claim;
|
||||
return true;
|
||||
};
|
||||
CustodyRequest request;
|
||||
request.key = {CustodyKeyKind::Admission, agent.id, agent.next_admission};
|
||||
request.kind = kind;
|
||||
request.production = production;
|
||||
request.source = source;
|
||||
request.destination = destination;
|
||||
for (const auto& material : materials) {
|
||||
auto& store = storage_by_id(material.storage_id);
|
||||
const auto stack = stock(store, material.type);
|
||||
if (material.count == 0 || stack == store.items.end() || stack->id == 0 ||
|
||||
stack->reserved > stack->count || material.count > stack->count - stack->reserved) return false;
|
||||
if (!add({0, ReservationKind::Item, {OwnerKind::Storage, store.id}, stack->id,
|
||||
material.type, material.count, 0, store.id})) return false;
|
||||
request.lines[request.line_count++] = {store.id, material.type, material.count};
|
||||
}
|
||||
if (production && !add({0, ReservationKind::Worksite, {OwnerKind::Production, production}, 0, {}, 1})) return false;
|
||||
if (source && !add({0, kind == TransferKind::Tending ? ReservationKind::Tending : ReservationKind::Harvest,
|
||||
{}, 0, {}, 1})) return false;
|
||||
if (destination) {
|
||||
auto& store = storage_by_id(destination);
|
||||
ReservationId backing = 0;
|
||||
if (production) {
|
||||
// Every production output replaces claimed input in this exact store.
|
||||
for (const auto& claim : execution.reservations) {
|
||||
if (claim.id && claim.kind == ReservationKind::Item && claim.origin_storage == destination) {
|
||||
backing = claim.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!backing && store.total_items() + store.reserved_slots >= store.capacity) return false;
|
||||
if (!add({0, ReservationKind::Capacity, {OwnerKind::Storage, destination}, 0, {}, 1, backing})) return false;
|
||||
}
|
||||
custody_receipts_.reserve(custody_receipt_limit);
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
receipt->request = request;
|
||||
receipt->result = {CustodyStatus::Accepted, execution.id};
|
||||
receipt->result.reservation_count = execution.reservation_count;
|
||||
for (std::size_t i = 0; i < execution.reservation_count; ++i) receipt->result.reservations[i] = execution.reservations[i].id;
|
||||
// The caller has already allocated routes and material vectors. No operation
|
||||
// below can throw; its existing cache increments follow immediately.
|
||||
agent.execution = execution;
|
||||
++agent.next_admission;
|
||||
++next_transfer_id_;
|
||||
next_reservation_id_ = next;
|
||||
record_custody(std::move(receipt));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool World::pickup_custody(Agent& agent, Storage& source,
|
||||
const std::vector<MaterialReservation>& materials, bool reserve_output) {
|
||||
Storage planned_source = source;
|
||||
Inventory planned_inventory = agent.inventory;
|
||||
auto execution = *agent.execution;
|
||||
auto next = next_stack_id_;
|
||||
custody_receipts_.reserve(custody_receipt_limit);
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
receipt->request = operation_request(agent, CustodyOperation::Pickup, source.id, 0);
|
||||
receipt->result = {CustodyStatus::Accepted, execution.id};
|
||||
const auto fail = [&](CustodyStatus status) {
|
||||
receipt->result.status = status;
|
||||
commit_custody(agent, receipt);
|
||||
return false;
|
||||
};
|
||||
if (!room(execution.next_operation, 1)) return false;
|
||||
if (!withdraw_reserved_materials(planned_source, planned_inventory, materials, reserve_output)) return fail(CustodyStatus::Invalid);
|
||||
for (const auto& stack : source.items) {
|
||||
const auto remaining = planned_source.item_count(stack.type);
|
||||
if (remaining == stack.count) continue;
|
||||
auto id = agent.inventory.stack_id(stack.type);
|
||||
if (!id) {
|
||||
if (remaining) {
|
||||
if (!room(next, 1)) return fail(CustodyStatus::Exhausted);
|
||||
id = next++;
|
||||
} else id = stack.id;
|
||||
}
|
||||
if (!id) return fail(CustodyStatus::Invalid);
|
||||
planned_inventory.set_stack_id(stack.type, id);
|
||||
retarget(execution, {OwnerKind::Storage, source.id}, stack.id, {OwnerKind::Resident, agent.id}, id);
|
||||
if (execution.kind == TransferKind::Meal) for (auto& claim : execution.reservations) {
|
||||
if (claim.kind == ReservationKind::Item) claim.origin_storage = 0;
|
||||
}
|
||||
}
|
||||
if (reserve_output) {
|
||||
for (auto& claim : execution.reservations) {
|
||||
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == source.id) claim.backing = 0;
|
||||
}
|
||||
}
|
||||
effects(receipt->result, planned_inventory, {OwnerKind::Resident, agent.id});
|
||||
source.items.swap(planned_source.items);
|
||||
source.reserved_slots = planned_source.reserved_slots;
|
||||
agent.inventory = planned_inventory;
|
||||
agent.execution = execution;
|
||||
next_stack_id_ = next;
|
||||
commit_custody(agent, receipt);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool World::deliver_custody(Agent& agent, Inventory& destination, StockOwner owner) {
|
||||
auto planned = destination;
|
||||
auto execution = *agent.execution;
|
||||
custody_receipts_.reserve(custody_receipt_limit);
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
receipt->request = operation_request(agent, CustodyOperation::Deliver, 0, 0);
|
||||
receipt->result = {CustodyStatus::Accepted, execution.id};
|
||||
if (!room(execution.next_operation, 1)) return false;
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto type = static_cast<ItemType>(i);
|
||||
const auto count = agent.inventory.item_count(type);
|
||||
if (!count) continue;
|
||||
if (!Void::Numeric::checked_add(planned.item_count(type), count)) {
|
||||
receipt->result.status = CustodyStatus::Overflow;
|
||||
commit_custody(agent, receipt);
|
||||
return false;
|
||||
}
|
||||
auto id = planned.stack_id(type);
|
||||
if (!id) id = agent.inventory.stack_id(type);
|
||||
planned.add(type, count);
|
||||
planned.set_stack_id(type, id);
|
||||
retarget(execution, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(type), owner, id);
|
||||
}
|
||||
effects(receipt->result, planned, owner);
|
||||
destination = planned;
|
||||
agent.inventory = {};
|
||||
agent.execution = execution;
|
||||
commit_custody(agent, receipt);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool World::deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count) {
|
||||
if (!count || count > agent.inventory.item_count(type) || !destination.accepts(type)) return false;
|
||||
auto planned = destination;
|
||||
auto inventory = agent.inventory;
|
||||
auto next = next_stack_id_;
|
||||
auto execution = *agent.execution;
|
||||
custody_receipts_.reserve(custody_receipt_limit);
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
receipt->request = operation_request(agent, execution.kind == TransferKind::Return ? CustodyOperation::Return : CustodyOperation::Deliver, 0, destination.id);
|
||||
receipt->request.lines[0] = {destination.id, type, count};
|
||||
receipt->request.line_count = 1;
|
||||
receipt->result = {CustodyStatus::Accepted, execution.id};
|
||||
if (!room(execution.next_operation, 1)) return false;
|
||||
auto slots = planned.reserved_slots;
|
||||
for (auto& claim : execution.reservations) {
|
||||
if (claim.id && claim.kind == ReservationKind::Capacity && claim.owner.id == destination.id && !claim.backing) {
|
||||
if (slots < claim.count) return false;
|
||||
slots -= claim.count;
|
||||
claim = {};
|
||||
}
|
||||
}
|
||||
if (planned.total_items() + slots + count > planned.capacity) return false;
|
||||
auto target = stock(planned, type);
|
||||
StackId id = 0;
|
||||
if (target != planned.items.end()) {
|
||||
const auto amount = Void::Numeric::checked_add(target->count, count);
|
||||
if (!amount) return false;
|
||||
target->count = *amount;
|
||||
id = target->id;
|
||||
} else {
|
||||
id = inventory.stack_id(type);
|
||||
if (count < inventory.item_count(type)) {
|
||||
if (!room(next, 1)) return false;
|
||||
id = next++;
|
||||
}
|
||||
planned.items.push_back({type, count, 0, id});
|
||||
std::sort(planned.items.begin(), planned.items.end(), [](const auto& a, const auto& b) { return a.type < b.type; });
|
||||
}
|
||||
inventory.remove(type, count);
|
||||
receipt->result.effects[0] = {{OwnerKind::Storage, destination.id}, id, type, planned.item_count(type)};
|
||||
receipt->result.effect_count = 1;
|
||||
receipt->result.terminal = inventory.empty();
|
||||
for (auto& claim : execution.reservations) {
|
||||
if (claim.id && claim.kind == ReservationKind::Item && claim.owner == StockOwner{OwnerKind::Resident, agent.id} && claim.item == type) {
|
||||
if (claim.count <= count) claim = {};
|
||||
else claim.count -= count;
|
||||
}
|
||||
}
|
||||
destination.items.swap(planned.items);
|
||||
destination.reserved_slots = slots;
|
||||
agent.inventory = inventory;
|
||||
agent.execution = execution;
|
||||
next_stack_id_ = next;
|
||||
commit_custody(agent, receipt);
|
||||
return true;
|
||||
}
|
||||
|
||||
void World::finish_custody(Agent& agent) noexcept { agent.execution.reset(); }
|
||||
|
||||
bool World::legacy_representable() const noexcept {
|
||||
for (const auto& order : production_orders_) if (order.suspended) return false;
|
||||
for (const auto& agent : agents_) {
|
||||
if (agent.state == AgentState::Returning || (agent.execution && agent.execution->kind == TransferKind::Return && agent.state != AgentState::Hauling)) return false;
|
||||
if ((agent.state == AgentState::Working || agent.state == AgentState::Gathering || agent.state == AgentState::Eating) && agent.work_remaining == 0) return false;
|
||||
if (agent.production_id == 0 && !agent.inventory.empty()) {
|
||||
const auto type = agent.inventory.first_item();
|
||||
if (agent.state == AgentState::Eating) {
|
||||
if (type != ItemType::Berries || agent.inventory.item_count(type) != 1) return false;
|
||||
} else if (agent.state != AgentState::Hauling || agent.storage_id == 0 ||
|
||||
type == ItemType::Plank || type == ItemType::StoneBlock || type == ItemType::Cloth ||
|
||||
agent.inventory.item_count(type) != 1) return false;
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
if (static_cast<ItemType>(i) != type && agent.inventory.item_count(static_cast<ItemType>(i))) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
CommandStatus World::cancel_production(ProductionId id) {
|
||||
auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; });
|
||||
if (it == production_orders_.end()) return CommandStatus::InvalidTarget;
|
||||
if (it->state == JobState::Completed || it->suspended) return CommandStatus::Busy;
|
||||
auto actor = std::find_if(agents_.begin(), agents_.end(), [id](const auto& a) { return a.production_id == id; });
|
||||
const bool retain = it->recipe == RecipeId::WeaveCloth ||
|
||||
(it->recipe == RecipeId::BuildBed && (it->bed_stage == BedStage::Bedding || it->bed_stage == BedStage::Pillow));
|
||||
if (actor != agents_.end()) {
|
||||
if (!actor->execution) return CommandStatus::Busy;
|
||||
auto inventory = actor->inventory;
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto item = static_cast<ItemType>(i);
|
||||
const auto count = it->input.item_count(item);
|
||||
if (!Void::Numeric::checked_add(inventory.item_count(item), count)) return CommandStatus::Busy;
|
||||
if (count) {
|
||||
if (!inventory.stack_id(item)) inventory.set_stack_id(item, it->input.stack_id(item));
|
||||
inventory.add(item, count);
|
||||
}
|
||||
}
|
||||
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(*actor, CustodyOperation::Cancel));
|
||||
if (!receipt) return CommandStatus::Busy;
|
||||
effects(receipt->result, inventory, {OwnerKind::Resident, actor->id});
|
||||
receipt->result.terminal = inventory.empty();
|
||||
for (auto& claim : actor->execution->reservations) {
|
||||
if (!claim.id) continue;
|
||||
if (claim.kind == ReservationKind::Item && claim.owner.kind == OwnerKind::Storage) {
|
||||
auto& store = storage_by_id(claim.owner.id);
|
||||
stock(store, claim.item)->reserved -= claim.count;
|
||||
} else if (claim.kind == ReservationKind::Capacity && !claim.backing) {
|
||||
storage_by_id(claim.owner.id).reserved_slots -= claim.count;
|
||||
}
|
||||
claim = {};
|
||||
}
|
||||
actor->execution->reservation_count = 0;
|
||||
actor->execution->kind = TransferKind::Return;
|
||||
actor->execution->production = 0;
|
||||
actor->execution->source = 0;
|
||||
actor->execution->destination = 0;
|
||||
actor->inventory = inventory;
|
||||
actor->production_id = 0;
|
||||
actor->storage_id = 0;
|
||||
actor->work_remaining = 0;
|
||||
actor->route.clear();
|
||||
actor->route_cursor = 0;
|
||||
actor->haul_route.clear();
|
||||
actor->state = inventory.empty() ? AgentState::Idle : AgentState::Returning;
|
||||
commit_custody(*actor, receipt);
|
||||
if (inventory.empty()) finish_custody(*actor);
|
||||
}
|
||||
if (retain) {
|
||||
it->input = {};
|
||||
it->materials.clear();
|
||||
it->delivery_stops.clear();
|
||||
it->collected_stops = 0;
|
||||
it->state = JobState::Available;
|
||||
it->suspended = true;
|
||||
} else production_orders_.erase(it);
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
CommandStatus World::resume_production(ProductionId id) {
|
||||
auto it = std::find_if(production_orders_.begin(), production_orders_.end(), [id](const auto& p) { return p.id == id; });
|
||||
if (it == production_orders_.end()) return CommandStatus::InvalidTarget;
|
||||
if (!it->suspended || it->state != JobState::Available) return CommandStatus::Busy;
|
||||
it->suspended = false;
|
||||
return CommandStatus::Accepted;
|
||||
}
|
||||
void World::advance_return(Agent& agent) {
|
||||
if (agent.route_cursor < agent.route.size()) return;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
const auto type = agent.inventory.first_item();
|
||||
if (type == ItemType::None) { agent.state = AgentState::Idle; finish_custody(agent); return; }
|
||||
for (auto& store : storages_) {
|
||||
if (!store.accepts(type) || store.total_items() + store.reserved_slots >= store.capacity) continue;
|
||||
auto path = assignment_path(agent.position, store.position);
|
||||
if (!path.reachable) continue;
|
||||
if (!path.positions.empty()) {
|
||||
agent.route = std::move(path.positions);
|
||||
agent.execution->blocked = CustodyStatus::Accepted;
|
||||
return;
|
||||
}
|
||||
const auto free = store.capacity - store.total_items() - store.reserved_slots;
|
||||
const auto count = static_cast<std::uint32_t>(std::min<std::uint64_t>(free, agent.inventory.item_count(type)));
|
||||
if (!deposit_custody(agent, store, type, count)) return;
|
||||
if (agent.inventory.empty()) { agent.state = AgentState::Idle; finish_custody(agent); }
|
||||
return;
|
||||
}
|
||||
agent.execution->blocked = CustodyStatus::NoDestination;
|
||||
}
|
||||
|
||||
void World::validate_custody() const {
|
||||
const auto require = [](bool condition) { if (!condition) throw std::runtime_error("inconsistent custody state"); };
|
||||
require(next_stack_id_ && next_reservation_id_ && next_transfer_id_);
|
||||
struct Physical { StockOwner owner; ItemType item; std::uint32_t count; std::uint64_t claimed = 0; };
|
||||
std::unordered_map<StackId, Physical> physical;
|
||||
std::unordered_map<StorageId, std::array<std::uint64_t, item_type_count>> reserved;
|
||||
std::unordered_map<StorageId, std::uint64_t> slots;
|
||||
std::unordered_map<ResourceNodeId, std::uint64_t> workers;
|
||||
std::array<std::uint64_t, item_type_count> live{};
|
||||
const auto add = [&](StockOwner owner, ItemType item, std::uint32_t count, StackId id) {
|
||||
require((count == 0) == (id == 0));
|
||||
if (!count) return;
|
||||
require(item > ItemType::None && item <= ItemType::Loom && id < next_stack_id_);
|
||||
require(physical.emplace(id, Physical{owner, item, count}).second);
|
||||
auto& total = live[static_cast<std::size_t>(item) - 1];
|
||||
const auto amount = Void::Numeric::checked_add(total, std::uint64_t{count});
|
||||
require(amount.has_value()); total = *amount;
|
||||
};
|
||||
const auto add_inventory = [&](const Inventory& inventory, StockOwner owner) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto item = static_cast<ItemType>(i);
|
||||
add(owner, item, inventory.item_count(item), inventory.stack_id(item));
|
||||
}
|
||||
};
|
||||
for (const auto& store : storages_) {
|
||||
auto previous = ItemType::None;
|
||||
for (const auto& stack : store.items) {
|
||||
require(stack.type > previous && stack.count && store.accepts(stack.type) && stack.reserved <= stack.count);
|
||||
previous = stack.type;
|
||||
add({OwnerKind::Storage, store.id}, stack.type, stack.count, stack.id);
|
||||
}
|
||||
require(store.total_items() + store.reserved_slots <= store.capacity);
|
||||
}
|
||||
for (const auto& actor : agents_) add_inventory(actor.inventory, {OwnerKind::Resident, actor.id});
|
||||
for (const auto& order : production_orders_) add_inventory(order.input, {OwnerKind::Production, order.id});
|
||||
std::unordered_map<AgentId, const Agent*> actors;
|
||||
std::unordered_map<ProductionId, const Agent*> producers;
|
||||
for (const auto& actor : agents_) {
|
||||
require(actors.emplace(actor.id, &actor).second);
|
||||
if (actor.production_id) require(producers.emplace(actor.production_id, &actor).second);
|
||||
}
|
||||
std::set<TransferId> transfers;
|
||||
std::set<ReservationId> reservation_ids;
|
||||
std::set<ProductionId> work_sites;
|
||||
std::set<ReservationId> backed;
|
||||
for (const auto& actor : agents_) {
|
||||
require(actor.next_admission != 0 && actor.route_cursor <= actor.route.size());
|
||||
if (!actor.execution) {
|
||||
require(actor.inventory.empty() && actor.production_id == 0 && actor.resource_node_id == 0 &&
|
||||
actor.state != AgentState::Returning && actor.state != AgentState::Hauling &&
|
||||
actor.state != AgentState::Eating && actor.state != AgentState::GoingToEat);
|
||||
continue;
|
||||
}
|
||||
const auto& execution = *actor.execution;
|
||||
require(execution.id && execution.id < next_transfer_id_ && transfers.insert(execution.id).second &&
|
||||
execution.kind <= TransferKind::Return && execution.next_operation && actor.next_admission >= 2 &&
|
||||
execution.reservation_count <= custody_reservation_limit && execution.blocked <= CustodyStatus::NoDestination);
|
||||
require(execution.production == actor.production_id && execution.source == actor.resource_node_id);
|
||||
if (execution.kind == TransferKind::Return) {
|
||||
require(!actor.inventory.empty() && !actor.production_id && !actor.resource_node_id && actor.work_remaining == 0);
|
||||
require((actor.state == AgentState::Returning && !actor.storage_id) ||
|
||||
(actor.state == AgentState::Hauling && actor.storage_id && find_storage(actor.storage_id) &&
|
||||
execution.destination == actor.storage_id));
|
||||
} else if (execution.kind == TransferKind::Meal) {
|
||||
require(actor.state == AgentState::GoingToEat || actor.state == AgentState::Eating);
|
||||
require(execution.production == 0 && execution.source == 0 && execution.destination == 0);
|
||||
} else if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending) {
|
||||
require(actor.state == AgentState::Travelling || actor.state == AgentState::Gathering || actor.state == AgentState::Hauling);
|
||||
require(execution.production == 0 && (execution.kind != TransferKind::Tending || actor.storage_id == 0));
|
||||
} else {
|
||||
require(actor.state == AgentState::Travelling || actor.state == AgentState::Working ||
|
||||
actor.state == AgentState::FetchingMaterials || actor.state == AgentState::Hauling);
|
||||
if (execution.production) require(find_production(execution.production) != nullptr);
|
||||
else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item()));
|
||||
}
|
||||
for (std::size_t index = 0; index < custody_reservation_limit; ++index) {
|
||||
const auto& claim = execution.reservations[index];
|
||||
if (claim.id == 0) { require(claim == Reservation{}); continue; }
|
||||
require(index < execution.reservation_count && claim.id < next_reservation_id_ &&
|
||||
reservation_ids.insert(claim.id).second && claim.kind <= ReservationKind::Tending && claim.count);
|
||||
if (claim.kind == ReservationKind::Item) {
|
||||
auto entry = physical.find(claim.stack);
|
||||
require(entry != physical.end() && entry->second.owner == claim.owner && entry->second.item == claim.item);
|
||||
require(!claim.backing);
|
||||
if (claim.origin_storage) require(find_storage(claim.origin_storage) != nullptr);
|
||||
else require(claim.owner.kind == OwnerKind::Resident &&
|
||||
(execution.kind == TransferKind::Meal || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)));
|
||||
require(claim.owner.kind != OwnerKind::Resident || claim.owner.id == actor.id);
|
||||
require(claim.owner.kind != OwnerKind::Production || claim.owner.id == actor.production_id);
|
||||
auto& amount = entry->second.claimed;
|
||||
require(claim.count <= entry->second.count - amount);
|
||||
amount += claim.count;
|
||||
if (claim.owner.kind == OwnerKind::Storage) {
|
||||
require(claim.owner.id == claim.origin_storage);
|
||||
reserved[claim.owner.id][static_cast<std::size_t>(claim.item) - 1] += claim.count;
|
||||
}
|
||||
} else if (claim.kind == ReservationKind::Capacity) {
|
||||
require(claim.owner.kind == OwnerKind::Storage && claim.owner.id == execution.destination &&
|
||||
find_storage(claim.owner.id) && !claim.stack && claim.item == ItemType::None && !claim.origin_storage && claim.count == 1);
|
||||
if (claim.backing) {
|
||||
const auto input = std::find_if(execution.reservations.begin(), execution.reservations.end(),
|
||||
[&](const auto& c) { return c.id == claim.backing; });
|
||||
require(input != execution.reservations.end() && input->kind == ReservationKind::Item &&
|
||||
input->owner == claim.owner && input->count >= claim.count && backed.insert(claim.backing).second);
|
||||
} else slots[claim.owner.id] += claim.count;
|
||||
} else if (claim.kind == ReservationKind::Worksite) {
|
||||
require(claim.owner == StockOwner{OwnerKind::Production, execution.production} && execution.production &&
|
||||
!claim.stack && claim.item == ItemType::None && claim.count == 1 && !claim.backing && !claim.origin_storage);
|
||||
require(work_sites.insert(execution.production).second);
|
||||
} else {
|
||||
require(claim.owner == StockOwner{} && !claim.stack && claim.item == ItemType::None &&
|
||||
claim.count == 1 && !claim.backing && !claim.origin_storage && execution.source && find_resource_node(execution.source));
|
||||
workers[execution.source] += claim.count;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& store : storages_) {
|
||||
require(slots[store.id] == store.reserved_slots);
|
||||
for (const auto& stack : store.items) require(reserved[store.id][static_cast<std::size_t>(stack.type) - 1] == stack.reserved);
|
||||
}
|
||||
for (const auto& node : resource_nodes_) require(workers[node.id] == node.reserved_workers);
|
||||
for (const auto& order : production_orders_) {
|
||||
require(order.state <= JobState::Completed);
|
||||
if (order.state == JobState::InProgress) {
|
||||
require(!order.suspended && work_sites.contains(order.id) && !order.materials.empty());
|
||||
const auto found_actor = producers.find(order.id);
|
||||
require(found_actor != producers.end());
|
||||
const auto actor = found_actor->second;
|
||||
if (delivers_materials(order.recipe) && actor->state == AgentState::Working) {
|
||||
std::array<std::uint32_t, item_type_count> expected{};
|
||||
for (const auto& line : order.materials) {
|
||||
require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count);
|
||||
const auto i = static_cast<std::size_t>(line.type) - 1;
|
||||
const auto amount = Void::Numeric::checked_add(expected[i], line.count);
|
||||
require(amount.has_value()); expected[i] = *amount;
|
||||
}
|
||||
for (std::size_t i = 0; i < item_type_count; ++i) require(order.input.item_count(static_cast<ItemType>(i + 1)) == expected[i]);
|
||||
require(actor->inventory.empty());
|
||||
} else require(order.input.empty());
|
||||
} else require(order.input.empty() && order.materials.empty() && order.delivery_stops.empty());
|
||||
if (order.suspended) require(order.state == JobState::Available &&
|
||||
(order.recipe == RecipeId::WeaveCloth || (order.recipe == RecipeId::BuildBed &&
|
||||
(order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow))));
|
||||
}
|
||||
for (std::size_t i = 0; i < item_type_count; ++i) {
|
||||
const auto& b = item_balances_[i];
|
||||
std::uint64_t in = 0, out = live[i];
|
||||
for (const auto value : {b.opening, b.grant, b.harvest, b.recipe_output}) {
|
||||
const auto amount = Void::Numeric::checked_add(in, value); require(amount.has_value()); in = *amount;
|
||||
}
|
||||
for (const auto value : {b.recipe_input, b.meal, b.installation, b.demolition}) {
|
||||
const auto amount = Void::Numeric::checked_add(out, value); require(amount.has_value()); out = *amount;
|
||||
}
|
||||
require(in == out);
|
||||
}
|
||||
require(custody_receipts_.size() <= custody_receipt_limit &&
|
||||
(custody_receipts_.size() == custody_receipt_limit ? custody_receipt_cursor_ < custody_receipt_limit : custody_receipt_cursor_ == 0));
|
||||
std::set<std::tuple<CustodyKeyKind, std::uint64_t, std::uint64_t>> keys;
|
||||
for (const auto& receipt : custody_receipts_) {
|
||||
require(static_cast<bool>(receipt));
|
||||
const auto& request = receipt->request;
|
||||
const auto& result = receipt->result;
|
||||
require(request.key.kind <= CustodyKeyKind::Operation && request.key.id && request.key.ordinal &&
|
||||
request.kind <= TransferKind::Return && request.operation <= CustodyOperation::Tend &&
|
||||
request.line_count <= custody_material_limit && request.production < next_production_id_ &&
|
||||
request.destination < next_storage_id_ && keys.emplace(request.key.kind, request.key.id, request.key.ordinal).second);
|
||||
if (request.key.kind == CustodyKeyKind::Admission) {
|
||||
require(request.key.id < next_agent_id_ && request.operation == CustodyOperation::Admit);
|
||||
const auto actor = actors.find(request.key.id);
|
||||
if (actor != actors.end()) require(request.key.ordinal < actor->second->next_admission);
|
||||
} else require(request.key.id < next_transfer_id_ && request.operation != CustodyOperation::Admit);
|
||||
for (std::size_t i = 0; i < custody_material_limit; ++i) {
|
||||
const auto& line = request.lines[i];
|
||||
if (i >= request.line_count) require(line == CustodyLine{});
|
||||
else require(line.storage && line.storage < next_storage_id_ && line.item > ItemType::None && line.item <= ItemType::Loom && line.count);
|
||||
}
|
||||
require(result.status <= CustodyStatus::NoDestination && result.transfer && result.transfer < next_transfer_id_ &&
|
||||
result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count);
|
||||
for (std::size_t i = 0; i < custody_reservation_limit; ++i) require(i < result.reservation_count ?
|
||||
result.reservations[i] > 0 && result.reservations[i] < next_reservation_id_ : result.reservations[i] == 0);
|
||||
for (std::size_t i = 0; i < item_type_count; ++i) {
|
||||
const auto& effect = result.effects[i];
|
||||
if (i >= result.effect_count) { require(effect == CustodyEffect{}); continue; }
|
||||
require(effect.stack && effect.stack < next_stack_id_ && effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.owner.id);
|
||||
if (effect.owner.kind == OwnerKind::Storage) require(effect.owner.id < next_storage_id_);
|
||||
else if (effect.owner.kind == OwnerKind::Resident) require(effect.owner.id < next_agent_id_);
|
||||
else { require(effect.owner.kind == OwnerKind::Production); require(effect.owner.id < next_production_id_); }
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace settlement
|
||||
+177
-72
@@ -58,33 +58,33 @@ std::uint16_t initial_hunger(AgentId id) {
|
||||
}
|
||||
|
||||
struct Recipe {
|
||||
std::array<ItemStack, 2> ingredients;
|
||||
std::array<ItemAmount, 2> 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}},
|
||||
static constexpr Recipe saw{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::Plank, 12};
|
||||
static constexpr Recipe cut{{ItemAmount{ItemType::Stone, 1}, {}}, ItemType::StoneBlock, 16};
|
||||
static constexpr Recipe cabin{{ItemAmount{ItemType::Plank, 3}, ItemAmount{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};
|
||||
static constexpr Recipe floor{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 6};
|
||||
static constexpr Recipe wall{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 9};
|
||||
static constexpr Recipe door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
||||
static constexpr Recipe cabinet{{ItemStack{ItemType::Wood, 1}, {}}, ItemType::None, 10};
|
||||
static constexpr Recipe mining_rack{{ItemStack{ItemType::Wood, 1}, ItemStack{ItemType::Stone, 1}},
|
||||
static constexpr Recipe bed{{ItemAmount{ItemType::Plank, 1}, {}}, ItemType::None, 14};
|
||||
static constexpr Recipe weave{{ItemAmount{ItemType::Flax, 1}, {}}, ItemType::Cloth, 12};
|
||||
static constexpr Recipe floor{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 6};
|
||||
static constexpr Recipe wall{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 9};
|
||||
static constexpr Recipe door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
||||
static constexpr Recipe cabinet{{ItemAmount{ItemType::Wood, 1}, {}}, ItemType::None, 10};
|
||||
static constexpr Recipe mining_rack{{ItemAmount{ItemType::Wood, 1}, ItemAmount{ItemType::Stone, 1}},
|
||||
ItemType::None, 10};
|
||||
static constexpr Recipe loom{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
||||
static constexpr Recipe install_door{{ItemStack{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe craft_door{{ItemStack{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
|
||||
static constexpr Recipe loom{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::None, 12};
|
||||
static constexpr Recipe install_door{{ItemAmount{ItemType::WoodenDoor, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe craft_door{{ItemAmount{ItemType::Wood, 2}, {}}, ItemType::WoodenDoor, 14};
|
||||
static constexpr Recipe craft_cabinet{cabinet.ingredients, ItemType::MedicineCabinet, 14};
|
||||
static constexpr Recipe craft_rack{mining_rack.ingredients, ItemType::MiningRack, 14};
|
||||
static constexpr Recipe craft_loom{loom.ingredients, ItemType::Loom, 16};
|
||||
static constexpr Recipe install_cabinet{{ItemStack{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe install_rack{{ItemStack{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe install_loom{{ItemStack{ItemType::Loom, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe install_cabinet{{ItemAmount{ItemType::MedicineCabinet, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe install_rack{{ItemAmount{ItemType::MiningRack, 1}, {}}, ItemType::None, 8};
|
||||
static constexpr Recipe install_loom{{ItemAmount{ItemType::Loom, 1}, {}}, ItemType::None, 8};
|
||||
switch (id) {
|
||||
case RecipeId::SawPlank: return saw;
|
||||
case RecipeId::CutStoneBlock: return cut;
|
||||
@@ -276,6 +276,7 @@ void Inventory::remove(ItemType type, std::uint32_t count) noexcept {
|
||||
const auto index = static_cast<std::size_t>(type);
|
||||
assert(index != 0 && index <= counts_.size() && count <= counts_[index - 1]);
|
||||
counts_[index - 1] -= count;
|
||||
if (counts_[index - 1] == 0) stack_ids_[index - 1] = 0;
|
||||
}
|
||||
|
||||
ItemType Inventory::first_item() const noexcept {
|
||||
@@ -497,8 +498,20 @@ void World::stock_storage(std::uint64_t id, ItemType type, std::uint32_t count)
|
||||
}
|
||||
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});
|
||||
auto& balance = item_balances_[static_cast<std::size_t>(type) - 1];
|
||||
const auto grant = Void::Numeric::checked_add(balance.grant, std::uint64_t{count});
|
||||
if (!grant) throw std::overflow_error("stock grant balance exhausted");
|
||||
if (stack != storage->items.end() && stack->type == type) {
|
||||
const auto amount = Void::Numeric::checked_add(stack->count, count);
|
||||
if (!amount) throw std::overflow_error("stock quantity exhausted");
|
||||
stack->count = *amount;
|
||||
} else {
|
||||
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
||||
if (next_stack_id_ == 0 || !next) throw std::overflow_error("stack identities exhausted");
|
||||
storage->items.insert(stack, ItemStack{type, count, 0, next_stack_id_});
|
||||
next_stack_id_ = *next;
|
||||
}
|
||||
balance.grant = *grant;
|
||||
}
|
||||
|
||||
void World::enable_hunger() noexcept {
|
||||
@@ -565,12 +578,12 @@ bool World::can_place_room(const RoomPlan& plan) const noexcept {
|
||||
});
|
||||
}
|
||||
|
||||
std::array<ItemStack, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
|
||||
std::array<ItemAmount, 2> World::construction_materials(RecipeId recipe, BedBase base) const {
|
||||
if (recipe == RecipeId::BuildBed && staged_beds_) {
|
||||
return {ItemStack{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
|
||||
ItemStack{ItemType::Cloth, 2}};
|
||||
return {ItemAmount{base == BedBase::Stone ? ItemType::Stone : ItemType::Wood, 1},
|
||||
ItemAmount{ItemType::Cloth, 2}};
|
||||
}
|
||||
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
|
||||
return is_construction(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
|
||||
}
|
||||
|
||||
RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
|
||||
@@ -584,8 +597,8 @@ RecipeId World::room_construction_recipe(RecipeId part) const noexcept {
|
||||
return part;
|
||||
}
|
||||
|
||||
std::array<ItemStack, 2> World::carpentry_materials(RecipeId recipe) const {
|
||||
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemStack, 2>{};
|
||||
std::array<ItemAmount, 2> World::carpentry_materials(RecipeId recipe) const {
|
||||
return is_carpentry_recipe(recipe) ? recipe_for(recipe).ingredients : std::array<ItemAmount, 2>{};
|
||||
}
|
||||
|
||||
std::size_t World::missing_carpentry_orders(ItemType product, std::size_t new_installations,
|
||||
@@ -746,6 +759,14 @@ CommandStatus World::edit_object(GridPosition position, const GridPosition* dest
|
||||
// Demand is evaluated against the post-removal inventory, without
|
||||
// losing stock or issuing any order until the entire batch fits.
|
||||
if (!reserve_production(total)) return CommandStatus::Busy;
|
||||
auto balances = item_balances_;
|
||||
for (const auto& stack : storage->items) {
|
||||
auto& sink = balances[static_cast<std::size_t>(stack.type) - 1].demolition;
|
||||
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{stack.count});
|
||||
if (!amount) return CommandStatus::Busy;
|
||||
sink = *amount;
|
||||
}
|
||||
item_balances_ = balances;
|
||||
storages_.erase(storage);
|
||||
for (std::size_t i = 0; i < replacements.size(); ++i) {
|
||||
for (std::size_t j = 0; j < replacements[i]; ++j) {
|
||||
@@ -1305,6 +1326,7 @@ void World::assign_resource_tasks(ResourceFocus focus) {
|
||||
}
|
||||
|
||||
if (node.needs_tending()) {
|
||||
if (!admit_custody(agent, TransferKind::Tending, 0, node.id, 0, {})) break;
|
||||
++resource_nodes_[node_index].reserved_workers;
|
||||
--untended_sites;
|
||||
agent.resource_node_id = node.id;
|
||||
@@ -1341,8 +1363,9 @@ void World::assign_resource_tasks(ResourceFocus focus) {
|
||||
continue;
|
||||
}
|
||||
|
||||
++resource_nodes_[node_index].reserved_workers;
|
||||
Storage& storage = storages_[storage_index];
|
||||
if (!admit_custody(agent, TransferKind::Harvest, 0, node.id, storage.id, {})) break;
|
||||
++resource_nodes_[node_index].reserved_workers;
|
||||
++storage.reserved_slots;
|
||||
if (!has_space(storage)) {
|
||||
if (storage.kind == StorageKind::Pantry) --open_pantry_count;
|
||||
@@ -1369,7 +1392,7 @@ void World::assign_production_tasks(bool weaving) {
|
||||
})) 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;
|
||||
if (order.suspended || 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) {
|
||||
@@ -1387,7 +1410,7 @@ void World::assign_production_tasks(bool weaving) {
|
||||
std::vector<Access> storage_access(deliver_ingredients || weaving ? storages_.size() : 0, Access::Unknown);
|
||||
std::vector<MaterialReservation> materials;
|
||||
bool supplied = true;
|
||||
for (const ItemStack& ingredient : recipe.ingredients) {
|
||||
for (const ItemAmount& ingredient : recipe.ingredients) {
|
||||
std::uint32_t remaining = ingredient.count;
|
||||
for (std::size_t storage_index = 0; storage_index < storages_.size() && remaining > 0;
|
||||
++storage_index) {
|
||||
@@ -1438,10 +1461,13 @@ void World::assign_production_tasks(bool weaving) {
|
||||
if (agent.state != AgentState::Idle || !eligible) continue;
|
||||
auto path = assignment_path(agent.position, destination);
|
||||
if (!path.reachable) continue;
|
||||
std::vector<GridPosition> haul_route;
|
||||
if (carpentry) {
|
||||
agent.haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
|
||||
haul_route = assignment_path(order.position, storage_by_id(materials.front().storage_id).position).positions;
|
||||
}
|
||||
|
||||
const auto output_storage = recipe.output == ItemType::None ? 0 : materials.front().storage_id;
|
||||
if (!admit_custody(agent, TransferKind::Production, order.id, 0, output_storage, materials)) break;
|
||||
if (carpentry) agent.haul_route = std::move(haul_route);
|
||||
for (const auto& material : materials) {
|
||||
stack_position(storage_by_id(material.storage_id), material.type)->reserved += material.count;
|
||||
}
|
||||
@@ -1459,19 +1485,6 @@ void World::assign_production_tasks(bool weaving) {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -1497,6 +1510,8 @@ void World::assign_meals() {
|
||||
auto path = assignment_path(agent.position, storage.position);
|
||||
if (!path.reachable) continue;
|
||||
|
||||
const std::vector meal{MaterialReservation{storage.id, ItemType::Berries, 1}};
|
||||
if (!admit_custody(agent, TransferKind::Meal, 0, 0, 0, meal)) break;
|
||||
auto stack = stack_position(storage, ItemType::Berries);
|
||||
++stack->reserved;
|
||||
agent.storage_id = storage.id;
|
||||
@@ -1512,9 +1527,10 @@ void World::assign_meals() {
|
||||
void World::finish_meal_step(Agent& agent) {
|
||||
if (agent.state == AgentState::GoingToEat) {
|
||||
if (agent.route_cursor != agent.route.size()) return;
|
||||
const std::array meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
|
||||
if (!withdraw_reserved_materials(storage_by_id(agent.storage_id), agent.inventory, meal)) {
|
||||
throw std::logic_error("invalid reserved meal pickup");
|
||||
const std::vector meal{MaterialReservation{agent.storage_id, ItemType::Berries, 1}};
|
||||
if (!pickup_custody(agent, storage_by_id(agent.storage_id), meal, false)) {
|
||||
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved meal pickup");
|
||||
return;
|
||||
}
|
||||
agent.storage_id = 0;
|
||||
agent.route.clear();
|
||||
@@ -1523,8 +1539,19 @@ void World::finish_meal_step(Agent& agent) {
|
||||
agent.state = AgentState::Eating;
|
||||
return;
|
||||
}
|
||||
if (--agent.work_remaining != 0) return;
|
||||
if (agent.work_remaining > 0) --agent.work_remaining;
|
||||
if (agent.work_remaining != 0) return;
|
||||
auto& sink = item_balances_[static_cast<std::size_t>(ItemType::Berries) - 1].meal;
|
||||
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{1});
|
||||
const auto meals = Void::Numeric::checked_add(meals_eaten_, std::uint64_t{1});
|
||||
auto receipt = prepare_custody(agent, CustodyOperation::Eat,
|
||||
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow);
|
||||
if (!receipt) return;
|
||||
commit_custody(agent, receipt);
|
||||
if (!amount || !meals) return;
|
||||
sink = *amount;
|
||||
agent.inventory.remove(ItemType::Berries);
|
||||
finish_custody(agent);
|
||||
agent.hunger = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
++meals_eaten_;
|
||||
@@ -1585,9 +1612,7 @@ void World::finish_rest_step(Agent& agent) {
|
||||
void World::advance_construction_delivery(Agent& agent) {
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
if (order.collected_stops == order.delivery_stops.size()) {
|
||||
for (const auto& material : order.materials) {
|
||||
agent.inventory.remove(material.type, material.count);
|
||||
}
|
||||
if (!deliver_custody(agent, order.input, {OwnerKind::Production, order.id})) return;
|
||||
order.delivery_stops.clear();
|
||||
order.collected_stops = 0;
|
||||
agent.state = AgentState::Working;
|
||||
@@ -1602,8 +1627,9 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
auto& stop = order.delivery_stops[order.collected_stops];
|
||||
const bool reserve_output = is_carpentry_recipe(order.recipe) &&
|
||||
stop.storage_id == order.materials.front().storage_id;
|
||||
if (!withdraw_reserved_materials(storage_by_id(stop.storage_id), agent.inventory, order.materials, reserve_output)) {
|
||||
throw std::logic_error("invalid reserved construction pickup");
|
||||
if (!pickup_custody(agent, storage_by_id(stop.storage_id), order.materials, reserve_output)) {
|
||||
if (agent.execution->blocked == CustodyStatus::Invalid) throw std::logic_error("invalid reserved construction pickup");
|
||||
return;
|
||||
}
|
||||
++order.collected_stops;
|
||||
agent.route = std::move(stop.route_to_next);
|
||||
@@ -1614,26 +1640,83 @@ void World::advance_construction_delivery(Agent& agent) {
|
||||
void World::finish_production(Agent& agent) {
|
||||
ProductionOrder& order = production_by_id(agent.production_id);
|
||||
const Recipe recipe = recipe_for(order);
|
||||
assert(!order.materials.empty());
|
||||
if (is_carpentry_recipe(order.recipe)) {
|
||||
agent.inventory.add(recipe.output);
|
||||
auto balances = item_balances_;
|
||||
auto input = order.input;
|
||||
auto inventory = agent.inventory;
|
||||
auto next = next_stack_id_;
|
||||
std::vector<Storage> stores;
|
||||
const bool delivered = delivers_materials(order.recipe);
|
||||
const bool carpentry = is_carpentry_recipe(order.recipe);
|
||||
auto status = CustodyStatus::Accepted;
|
||||
for (const auto& material : order.materials) {
|
||||
auto& balance = balances[static_cast<std::size_t>(material.type) - 1];
|
||||
auto& sink = recipe.output == ItemType::None ? balance.installation : balance.recipe_input;
|
||||
const auto amount = Void::Numeric::checked_add(sink, std::uint64_t{material.count});
|
||||
if (!amount) { status = CustodyStatus::Overflow; break; }
|
||||
sink = *amount;
|
||||
if (delivered) {
|
||||
if (input.item_count(material.type) < material.count) { status = CustodyStatus::Invalid; break; }
|
||||
input.remove(material.type, material.count);
|
||||
} else {
|
||||
auto store = std::find_if(stores.begin(), stores.end(), [&](const auto& s) { return s.id == material.storage_id; });
|
||||
if (store == stores.end()) { stores.push_back(storage_by_id(material.storage_id)); store = std::prev(stores.end()); }
|
||||
const auto stack = stack_position(*store, material.type);
|
||||
if (stack == store->items.end() || stack->type != material.type || stack->reserved < material.count || stack->count < material.count) {
|
||||
status = CustodyStatus::Invalid; break;
|
||||
}
|
||||
stack->count -= material.count;
|
||||
stack->reserved -= material.count;
|
||||
if (stack->count == 0) store->items.erase(stack);
|
||||
}
|
||||
}
|
||||
StackId output_id = 0;
|
||||
if (status == CustodyStatus::Accepted && recipe.output != ItemType::None) {
|
||||
auto& balance = balances[static_cast<std::size_t>(recipe.output) - 1].recipe_output;
|
||||
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
||||
if (!amount) status = CustodyStatus::Overflow;
|
||||
else balance = *amount;
|
||||
if (carpentry) {
|
||||
if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
|
||||
else { output_id = next++; inventory.add(recipe.output); inventory.set_stack_id(recipe.output, output_id); }
|
||||
} else {
|
||||
auto& store = stores.front();
|
||||
auto stack = stack_position(store, recipe.output);
|
||||
if (stack != store.items.end() && stack->type == recipe.output) { ++stack->count; output_id = stack->id; }
|
||||
else if (next == 0 || next == std::numeric_limits<StackId>::max()) status = CustodyStatus::Exhausted;
|
||||
else { output_id = next++; store.items.insert(stack, {recipe.output, 1, 0, output_id}); }
|
||||
}
|
||||
}
|
||||
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Complete, status));
|
||||
if (!receipt) return;
|
||||
if (status == CustodyStatus::Accepted) {
|
||||
receipt->result.terminal = !carpentry;
|
||||
if (output_id) {
|
||||
receipt->result.effects[0] = {carpentry ? StockOwner{OwnerKind::Resident, agent.id} :
|
||||
StockOwner{OwnerKind::Storage, stores.front().id}, output_id, recipe.output,
|
||||
carpentry ? inventory.item_count(recipe.output) : stores.front().item_count(recipe.output)};
|
||||
receipt->result.effect_count = 1;
|
||||
}
|
||||
}
|
||||
commit_custody(agent, receipt);
|
||||
if (status != CustodyStatus::Accepted) return;
|
||||
for (auto& store : stores) storage_by_id(store.id).items.swap(store.items);
|
||||
item_balances_ = balances;
|
||||
next_stack_id_ = next;
|
||||
order.input = input;
|
||||
agent.inventory = inventory;
|
||||
for (auto& claim : agent.execution->reservations) if (claim.kind != ReservationKind::Capacity) claim = {};
|
||||
if (carpentry) {
|
||||
agent.storage_id = order.materials.front().storage_id;
|
||||
agent.route = std::move(agent.haul_route);
|
||||
agent.haul_route.clear();
|
||||
agent.route_cursor = 0;
|
||||
agent.production_id = 0;
|
||||
agent.execution->production = 0;
|
||||
agent.state = AgentState::Hauling;
|
||||
order.materials.clear();
|
||||
order.state = JobState::Completed;
|
||||
return;
|
||||
}
|
||||
if (recipe.output != ItemType::None) {
|
||||
for (const auto& material : order.materials) {
|
||||
take_reserved_material(storage_by_id(material.storage_id), material);
|
||||
}
|
||||
// Crafting replaces one raw item with one finished item in the same store.
|
||||
storage_by_id(order.materials.front().storage_id).add_item(recipe.output);
|
||||
}
|
||||
order.materials.clear();
|
||||
if (order.recipe == RecipeId::BuildBed &&
|
||||
(order.bed_stage == BedStage::Foundation || order.bed_stage == BedStage::Bedding)) {
|
||||
@@ -1644,13 +1727,12 @@ void World::finish_production(Agent& agent) {
|
||||
order.state = JobState::Available;
|
||||
} else if (order.recipe == RecipeId::WeaveCloth) {
|
||||
order.state = JobState::Available;
|
||||
} else {
|
||||
order.state = JobState::Completed;
|
||||
}
|
||||
} else order.state = JobState::Completed;
|
||||
agent.production_id = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
agent.route.clear();
|
||||
agent.route_cursor = 0;
|
||||
finish_custody(agent);
|
||||
}
|
||||
|
||||
void World::grow_sites() {
|
||||
@@ -1707,7 +1789,7 @@ void World::step(TickProfile* profile) {
|
||||
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.state == AgentState::GoingToSleep || agent.state == AgentState::Returning) &&
|
||||
agent.route_cursor < agent.route.size()) {
|
||||
agent.position = agent.route[agent.route_cursor++];
|
||||
if (agent.state == AgentState::Travelling && agent.route_cursor == agent.route.size()) {
|
||||
@@ -1762,6 +1844,7 @@ void World::step(TickProfile* profile) {
|
||||
}
|
||||
|
||||
for (Agent& agent : agents_) {
|
||||
if (agent.state == AgentState::Returning) { advance_return(agent); continue; }
|
||||
if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) {
|
||||
finish_meal_step(agent);
|
||||
continue;
|
||||
@@ -1783,7 +1866,13 @@ void World::step(TickProfile* profile) {
|
||||
if (agent.work_remaining == 0 && agent.resource_node_id != 0) {
|
||||
ResourceNode& node = resource_node_by_id(agent.resource_node_id);
|
||||
if (agent.storage_id == 0) {
|
||||
node.growth_at = tick_ + growing_time(node.site);
|
||||
const auto growth = Void::Numeric::checked_add(tick_, growing_time(node.site));
|
||||
auto receipt = prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow);
|
||||
if (!receipt) continue;
|
||||
commit_custody(agent, receipt);
|
||||
if (!growth) continue;
|
||||
node.growth_at = *growth;
|
||||
finish_custody(agent);
|
||||
--node.reserved_workers;
|
||||
agent.resource_node_id = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
@@ -1791,9 +1880,26 @@ void World::step(TickProfile* profile) {
|
||||
agent.route_cursor = 0;
|
||||
continue;
|
||||
}
|
||||
if (node.quantity > 0) --node.quantity;
|
||||
if (node.reserved_workers > 0) --node.reserved_workers;
|
||||
auto& balance = item_balances_[static_cast<std::size_t>(node.type) - 1].harvest;
|
||||
const auto amount = Void::Numeric::checked_add(balance, std::uint64_t{1});
|
||||
const auto next = Void::Numeric::checked_add(next_stack_id_, std::uint64_t{1});
|
||||
auto receipt = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Harvest,
|
||||
!next ? CustodyStatus::Exhausted : !amount ? CustodyStatus::Overflow : CustodyStatus::Accepted));
|
||||
if (!receipt) continue;
|
||||
if (next && amount) {
|
||||
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, next_stack_id_, node.type, 1};
|
||||
receipt->result.effect_count = 1;
|
||||
}
|
||||
commit_custody(agent, receipt);
|
||||
if (!next || !amount) continue;
|
||||
--node.quantity;
|
||||
--node.reserved_workers;
|
||||
balance = *amount;
|
||||
agent.inventory.add(node.type);
|
||||
agent.inventory.set_stack_id(node.type, next_stack_id_);
|
||||
next_stack_id_ = *next;
|
||||
for (auto& claim : agent.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {};
|
||||
agent.execution->source = 0;
|
||||
agent.resource_node_id = 0;
|
||||
agent.route = std::move(agent.haul_route);
|
||||
agent.haul_route.clear();
|
||||
@@ -1806,9 +1912,8 @@ void World::step(TickProfile* profile) {
|
||||
agent.storage_id != 0) {
|
||||
Storage& storage = storage_by_id(agent.storage_id);
|
||||
const ItemType cargo = agent.inventory.first_item();
|
||||
if (storage.reserved_slots > 0) --storage.reserved_slots;
|
||||
storage.add_item(cargo);
|
||||
agent.inventory.remove(cargo);
|
||||
if (!deposit_custody(agent, storage, cargo, 1)) continue;
|
||||
finish_custody(agent);
|
||||
agent.storage_id = 0;
|
||||
agent.state = AgentState::Idle;
|
||||
agent.route.clear();
|
||||
|
||||
+346
-7
@@ -18,7 +18,7 @@ namespace settlement {
|
||||
namespace {
|
||||
|
||||
constexpr std::string_view signature = "SETTLERS";
|
||||
constexpr std::uint32_t save_version = 14;
|
||||
constexpr std::uint32_t save_version = 15;
|
||||
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;
|
||||
@@ -86,6 +86,11 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void allocate(std::size_t count, std::size_t size) {
|
||||
require_save(count <= max_save_bytes / size &&
|
||||
allocations_.consume_field(count * size).has_value(), "Save allocation budget exceeded.");
|
||||
}
|
||||
|
||||
void set_version(std::uint32_t version) {
|
||||
legacy_footer_ = version <= last_legacy_footer_version;
|
||||
}
|
||||
@@ -104,6 +109,7 @@ private:
|
||||
std::istream& stream_;
|
||||
std::size_t bytes_ = 0;
|
||||
// Legacy footers cover the signature and version, which are read first.
|
||||
Void::Binary::DecodeBudget allocations_{{max_save_bytes, max_save_bytes, 64}};
|
||||
bool legacy_footer_ = true;
|
||||
std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis;
|
||||
};
|
||||
@@ -115,6 +121,7 @@ void sequence(Archive& archive, Vector& values, std::size_t limit, Visit visit)
|
||||
archive.field(length);
|
||||
require_save(length <= limit, "Save contains too many records.");
|
||||
if constexpr (Archive::reading) {
|
||||
archive.allocate(length, sizeof(typename Vector::value_type));
|
||||
for (std::uint32_t i = 0; i < length; ++i) {
|
||||
values.emplace_back();
|
||||
visit(values.back());
|
||||
@@ -371,10 +378,192 @@ struct WorldSaveCodec {
|
||||
}
|
||||
}
|
||||
|
||||
static void validate(const World& world);
|
||||
template<class Archive, class State>
|
||||
static void custody(Archive& archive, State& world);
|
||||
static void validate(const World& world, bool modern = false);
|
||||
};
|
||||
|
||||
void WorldSaveCodec::validate(const World& world) {
|
||||
namespace {
|
||||
|
||||
template<class Archive, class Owner>
|
||||
void owner_fields(Archive& archive, Owner& owner) {
|
||||
archive.field(owner.kind);
|
||||
archive.field(owner.id);
|
||||
require_save(owner.kind <= OwnerKind::Production, "Unknown custody owner.");
|
||||
require_save((owner.kind == OwnerKind::None) == (owner.id == 0), "Invalid custody owner identity.");
|
||||
}
|
||||
|
||||
template<class Archive, class Claim>
|
||||
void claim_fields(Archive& archive, Claim& claim) {
|
||||
archive.field(claim.id);
|
||||
archive.field(claim.kind);
|
||||
owner_fields(archive, claim.owner);
|
||||
archive.field(claim.stack);
|
||||
archive.field(claim.item);
|
||||
archive.field(claim.count);
|
||||
archive.field(claim.backing);
|
||||
archive.field(claim.origin_storage);
|
||||
require_save(claim.kind <= ReservationKind::Tending && claim.item <= ItemType::Loom,
|
||||
"Unknown reservation kind or item.");
|
||||
require_save(claim.id != 0 || claim == Reservation{}, "Noncanonical released reservation.");
|
||||
}
|
||||
|
||||
template<class Archive, class Request>
|
||||
void request_fields(Archive& archive, Request& request) {
|
||||
// These are exact tagged little-endian fields, never an object image or hash.
|
||||
std::uint16_t size = static_cast<std::uint16_t>(44 + 13 * request.line_count);
|
||||
archive.field(size);
|
||||
require_save(size <= 1024, "Custody request exceeds 1024 bytes.");
|
||||
archive.field(request.key.kind);
|
||||
archive.field(request.key.id);
|
||||
archive.field(request.key.ordinal);
|
||||
archive.field(request.operation);
|
||||
archive.field(request.kind);
|
||||
archive.field(request.production);
|
||||
archive.field(request.source);
|
||||
archive.field(request.destination);
|
||||
archive.field(request.line_count);
|
||||
require_save(request.line_count <= custody_material_limit && size == 44 + 13 * request.line_count,
|
||||
"Noncanonical custody request length.");
|
||||
require_save(request.key.kind <= CustodyKeyKind::Operation && request.operation <= CustodyOperation::Tend &&
|
||||
request.kind <= TransferKind::Return && request.key.id != 0 && request.key.ordinal != 0 &&
|
||||
((request.key.kind == CustodyKeyKind::Admission) == (request.operation == CustodyOperation::Admit)),
|
||||
"Invalid custody request tag or key.");
|
||||
for (std::size_t i = 0; i < request.line_count; ++i) {
|
||||
auto& line = request.lines[i];
|
||||
archive.field(line.storage);
|
||||
archive.field(line.item);
|
||||
archive.field(line.count);
|
||||
require_save(line.storage != 0 && line.item > ItemType::None && line.item <= ItemType::Loom && line.count != 0,
|
||||
"Invalid custody request line.");
|
||||
}
|
||||
for (std::size_t i = request.line_count; i < request.lines.size(); ++i) {
|
||||
require_save(request.lines[i] == CustodyLine{}, "Noncanonical unused request line.");
|
||||
}
|
||||
}
|
||||
|
||||
template<class Archive, class Result>
|
||||
void result_fields(Archive& archive, Result& result) {
|
||||
std::uint16_t size = static_cast<std::uint16_t>(12 + 8 * result.reservation_count + 22 * result.effect_count);
|
||||
archive.field(size);
|
||||
require_save(size <= 1024, "Custody result exceeds 1024 bytes.");
|
||||
archive.field(result.status);
|
||||
archive.field(result.transfer);
|
||||
archive.field(result.reservation_count);
|
||||
archive.field(result.effect_count);
|
||||
flag(archive, result.terminal);
|
||||
require_save(result.status <= CustodyStatus::NoDestination &&
|
||||
result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count &&
|
||||
size == 12 + 8 * result.reservation_count + 22 * result.effect_count,
|
||||
"Noncanonical custody result length or tag.");
|
||||
for (std::size_t i = 0; i < result.reservation_count; ++i) archive.field(result.reservations[i]);
|
||||
for (std::size_t i = result.reservation_count; i < result.reservations.size(); ++i) {
|
||||
require_save(result.reservations[i] == 0, "Noncanonical unused result reservation.");
|
||||
}
|
||||
for (std::size_t i = 0; i < result.effect_count; ++i) {
|
||||
auto& effect = result.effects[i];
|
||||
owner_fields(archive, effect.owner);
|
||||
archive.field(effect.stack);
|
||||
archive.field(effect.item);
|
||||
archive.field(effect.count);
|
||||
require_save(effect.owner.kind != OwnerKind::None && effect.stack != 0 &&
|
||||
effect.item > ItemType::None && effect.item <= ItemType::Loom && effect.count != 0,
|
||||
"Invalid custody result effect.");
|
||||
}
|
||||
for (std::size_t i = result.effect_count; i < result.effects.size(); ++i) {
|
||||
require_save(result.effects[i] == CustodyEffect{}, "Noncanonical unused result effect.");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
template<class Archive, class State>
|
||||
void WorldSaveCodec::custody(Archive& archive, State& world) {
|
||||
archive.field(world.next_stack_id_);
|
||||
archive.field(world.next_reservation_id_);
|
||||
archive.field(world.next_transfer_id_);
|
||||
const auto inventory = [&](auto& value, bool quantities) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto type = static_cast<ItemType>(i);
|
||||
auto count = value.item_count(type);
|
||||
if (quantities) archive.field(count);
|
||||
auto id = value.stack_id(type);
|
||||
archive.field(id);
|
||||
require_save((id == 0) == (count == 0), "Noncanonical custody stack identity.");
|
||||
if constexpr (Archive::reading) {
|
||||
if (quantities && count != 0) value.add(type, count);
|
||||
value.set_stack_id(type, id);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (auto& storage : world.storages_) {
|
||||
for (auto& stack : storage.items) archive.field(stack.id);
|
||||
}
|
||||
for (auto& agent : world.agents_) {
|
||||
inventory(agent.inventory, false);
|
||||
archive.field(agent.next_admission);
|
||||
bool present = agent.execution.has_value();
|
||||
flag(archive, present);
|
||||
if constexpr (Archive::reading) { if (present) agent.execution.emplace(); }
|
||||
if (!present) continue;
|
||||
auto& execution = *agent.execution;
|
||||
archive.field(execution.id);
|
||||
archive.field(execution.kind);
|
||||
archive.field(execution.production);
|
||||
archive.field(execution.source);
|
||||
archive.field(execution.destination);
|
||||
archive.field(execution.next_operation);
|
||||
archive.field(execution.blocked);
|
||||
archive.field(execution.reservation_count);
|
||||
require_save(execution.kind <= TransferKind::Return && execution.blocked <= CustodyStatus::NoDestination &&
|
||||
execution.reservation_count <= custody_reservation_limit, "Invalid custody execution fields.");
|
||||
for (std::size_t i = 0; i < execution.reservation_count; ++i) claim_fields(archive, execution.reservations[i]);
|
||||
for (std::size_t i = execution.reservation_count; i < execution.reservations.size(); ++i) {
|
||||
require_save(execution.reservations[i] == Reservation{}, "Noncanonical unused reservation.");
|
||||
}
|
||||
}
|
||||
for (auto& order : world.production_orders_) {
|
||||
inventory(order.input, true);
|
||||
flag(archive, order.suspended);
|
||||
}
|
||||
for (auto& balance : world.item_balances_) {
|
||||
archive.field(balance.opening);
|
||||
archive.field(balance.grant);
|
||||
archive.field(balance.harvest);
|
||||
archive.field(balance.recipe_output);
|
||||
archive.field(balance.recipe_input);
|
||||
archive.field(balance.meal);
|
||||
archive.field(balance.installation);
|
||||
archive.field(balance.demolition);
|
||||
}
|
||||
auto count = static_cast<std::uint32_t>(world.custody_receipts_.size());
|
||||
require_save(world.custody_receipts_.size() <= custody_receipt_limit, "Too many custody receipts.");
|
||||
archive.field(count);
|
||||
require_save(count <= custody_receipt_limit, "Too many custody receipts.");
|
||||
if constexpr (Archive::reading) {
|
||||
archive.allocate(count, sizeof(CustodyReceipt) + sizeof(std::shared_ptr<const CustodyReceipt>));
|
||||
world.custody_receipts_.reserve(count);
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
auto receipt = std::make_shared<CustodyReceipt>();
|
||||
request_fields(archive, receipt->request);
|
||||
result_fields(archive, receipt->result);
|
||||
world.custody_receipts_.push_back(std::move(receipt));
|
||||
}
|
||||
world.custody_receipt_cursor_ = 0;
|
||||
} else {
|
||||
require_save(count == custody_receipt_limit ? world.custody_receipt_cursor_ < count :
|
||||
world.custody_receipt_cursor_ == 0, "Invalid custody receipt cursor.");
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
const auto index = (i + world.custody_receipt_cursor_) % count;
|
||||
const auto& receipt = world.custody_receipts_[index];
|
||||
require_save(receipt != nullptr, "Missing custody receipt.");
|
||||
request_fields(archive, receipt->request);
|
||||
result_fields(archive, receipt->result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WorldSaveCodec::validate(const World& world, bool modern) {
|
||||
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_;
|
||||
@@ -466,6 +655,21 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
invalid(resident != world.agents_.end() && resident->id == order.bed_owner);
|
||||
bed_owners.push_back(order.bed_owner);
|
||||
}
|
||||
if (modern) {
|
||||
invalid(order.materials.size() <= custody_material_limit &&
|
||||
order.collected_stops <= order.delivery_stops.size());
|
||||
for (const auto& material : order.materials) {
|
||||
static_cast<void>(item_index(material.type));
|
||||
invalid(material.count > 0 && world.find_storage(material.storage_id) != nullptr);
|
||||
}
|
||||
StorageId previous_stop = 0;
|
||||
for (const auto& stop : order.delivery_stops) {
|
||||
invalid(stop.storage_id > previous_stop && world.find_storage(stop.storage_id) != nullptr);
|
||||
previous_stop = stop.storage_id;
|
||||
valid_route(stop.route_to_next);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (order.state != JobState::InProgress) {
|
||||
invalid(order.materials.empty() && order.delivery_stops.empty() && order.collected_stops == 0);
|
||||
continue;
|
||||
@@ -551,7 +755,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
std::vector<GridPosition> 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 &&
|
||||
invalid(agent.state <= (modern ? Returning : 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);
|
||||
@@ -566,7 +770,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
const bool has_storage = agent.storage_id != 0;
|
||||
invalid(!has_storage || world.find_storage(agent.storage_id) != nullptr);
|
||||
const bool carpentry = has_order && is_carpentry_recipe(production->recipe);
|
||||
invalid(agent.haul_route.empty() || has_source || carpentry);
|
||||
invalid(modern || 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);
|
||||
@@ -576,6 +780,11 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
auto& claimed = job_claims[static_cast<std::size_t>(job - world.jobs_.begin())];
|
||||
invalid(claimed == 0);
|
||||
claimed = 1;
|
||||
} else if (modern && agent.state != GoingToSleep && agent.state != Sleeping) {
|
||||
invalid(!has_source || world.find_resource_node(agent.resource_node_id) != nullptr);
|
||||
// Live property, claims, execution phase and zero-time pending work
|
||||
// are checked together by the authoritative custody validator.
|
||||
continue;
|
||||
} else if (has_order) {
|
||||
invalid(!has_storage && !has_source && agent.work_remaining > 0);
|
||||
const auto order_index = static_cast<std::size_t>(production - world.production_orders_.data());
|
||||
@@ -657,6 +866,7 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
for (std::size_t i = 0; i < world.jobs_.size(); ++i) {
|
||||
invalid((job_claims[i] != 0) == (world.jobs_[i].state == JobState::InProgress));
|
||||
}
|
||||
if (modern) { world.validate_custody(); return; }
|
||||
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
|
||||
invalid((order_claims[i] != 0) == (world.production_orders_[i].state == JobState::InProgress));
|
||||
}
|
||||
@@ -674,10 +884,133 @@ void WorldSaveCodec::validate(const World& world) {
|
||||
}
|
||||
}
|
||||
|
||||
void World::migrate_legacy_custody() {
|
||||
// This function runs only after historical fields, phases, reservations and
|
||||
// (for versions 1–8) the historical footer have all passed validation.
|
||||
next_stack_id_ = next_reservation_id_ = next_transfer_id_ = 1;
|
||||
item_balances_ = {};
|
||||
custody_receipts_.clear();
|
||||
custody_receipt_cursor_ = 0;
|
||||
for (auto& order : production_orders_) {
|
||||
if (order.state == JobState::InProgress && delivers_materials(order.recipe) && order.delivery_stops.empty()) {
|
||||
for (const auto& material : order.materials) order.input.add(material.type, material.count);
|
||||
}
|
||||
}
|
||||
const auto identity = [&](ItemType item, std::uint32_t count) {
|
||||
require_save(next_stack_id_ != std::numeric_limits<StackId>::max(), "Migrated stack identities exhausted.");
|
||||
auto& opening = item_balances_[item_index(item)].opening;
|
||||
require_save(count <= std::numeric_limits<std::uint64_t>::max() - opening, "Migrated opening balance overflow.");
|
||||
opening += count;
|
||||
return next_stack_id_++;
|
||||
};
|
||||
// Stable owner-kind / owner-ID / item order, independent of worker count.
|
||||
for (auto& storage : storages_) {
|
||||
for (auto& stack : storage.items) stack.id = identity(stack.type, stack.count);
|
||||
}
|
||||
const auto identify_inventory = [&](Inventory& inventory) {
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto item = static_cast<ItemType>(i);
|
||||
if (const auto count = inventory.item_count(item)) inventory.set_stack_id(item, identity(item, count));
|
||||
}
|
||||
};
|
||||
for (auto& agent : agents_) identify_inventory(agent.inventory);
|
||||
for (auto& order : production_orders_) identify_inventory(order.input);
|
||||
|
||||
for (auto& agent : agents_) {
|
||||
agent.next_admission = 1;
|
||||
agent.execution.reset();
|
||||
const bool active = agent.production_id != 0 || agent.resource_node_id != 0 ||
|
||||
agent.state == AgentState::Hauling || agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating;
|
||||
if (!active) continue;
|
||||
TransferExecution execution;
|
||||
execution.id = next_transfer_id_++;
|
||||
execution.production = agent.production_id;
|
||||
execution.source = agent.resource_node_id;
|
||||
execution.destination = agent.storage_id;
|
||||
const auto add = [&](Reservation claim) -> ReservationId {
|
||||
require_save(execution.reservation_count < custody_reservation_limit &&
|
||||
next_reservation_id_ != std::numeric_limits<ReservationId>::max(),
|
||||
"Migrated reservation limit exceeded.");
|
||||
claim.id = next_reservation_id_++;
|
||||
execution.reservations[execution.reservation_count++] = claim;
|
||||
return claim.id;
|
||||
};
|
||||
const auto storage_stack = [&](StorageId storage, ItemType item) -> StackId {
|
||||
const auto& items = storages_[record_index(storages_, storage)].items;
|
||||
const auto found = std::lower_bound(items.begin(), items.end(), item,
|
||||
[](const auto& stack, ItemType target) { return stack.type < target; });
|
||||
require_save(found != items.end() && found->type == item, "Missing migrated reserved stock.");
|
||||
return found->id;
|
||||
};
|
||||
ReservationId capacity_backing = 0;
|
||||
if (agent.production_id != 0) {
|
||||
execution.kind = TransferKind::Production;
|
||||
const auto& order = production_orders_[record_index(production_orders_, agent.production_id)];
|
||||
const bool delivery = delivers_materials(order.recipe);
|
||||
const bool at_site = delivery && order.delivery_stops.empty();
|
||||
if (!is_construction(order.recipe) || is_carpentry_recipe(order.recipe)) {
|
||||
execution.destination = order.materials.front().storage_id;
|
||||
}
|
||||
for (const auto& material : order.materials) {
|
||||
StockOwner owner{OwnerKind::Storage, material.storage_id};
|
||||
StackId stack = 0;
|
||||
if (at_site) {
|
||||
owner = {OwnerKind::Production, order.id};
|
||||
stack = order.input.stack_id(material.type);
|
||||
} else if (delivery) {
|
||||
const auto stop = std::lower_bound(order.delivery_stops.begin(), order.delivery_stops.end(), material.storage_id,
|
||||
[](const auto& entry, StorageId id) { return entry.storage_id < id; });
|
||||
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) {
|
||||
owner = {OwnerKind::Resident, agent.id};
|
||||
stack = agent.inventory.stack_id(material.type);
|
||||
}
|
||||
}
|
||||
if (owner.kind == OwnerKind::Storage) stack = storage_stack(material.storage_id, material.type);
|
||||
const auto claim = add({0, ReservationKind::Item, owner, stack, material.type, material.count, 0, material.storage_id});
|
||||
if (!capacity_backing && execution.destination == material.storage_id && owner.kind == OwnerKind::Storage) {
|
||||
capacity_backing = claim;
|
||||
}
|
||||
}
|
||||
add({0, ReservationKind::Worksite, {OwnerKind::Production, order.id}, 0, {}, 1});
|
||||
} else if (agent.resource_node_id != 0) {
|
||||
execution.kind = agent.storage_id ? TransferKind::Harvest : TransferKind::Tending;
|
||||
add({0, agent.storage_id ? ReservationKind::Harvest : ReservationKind::Tending, {}, 0, {}, 1});
|
||||
} else if (agent.state == AgentState::GoingToEat || agent.state == AgentState::Eating) {
|
||||
execution.kind = TransferKind::Meal;
|
||||
execution.destination = 0;
|
||||
if (agent.state == AgentState::GoingToEat) {
|
||||
add({0, ReservationKind::Item, {OwnerKind::Storage, agent.storage_id},
|
||||
storage_stack(agent.storage_id, ItemType::Berries), ItemType::Berries, 1, 0, agent.storage_id});
|
||||
} else {
|
||||
add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id},
|
||||
agent.inventory.stack_id(ItemType::Berries), ItemType::Berries, 1});
|
||||
}
|
||||
} else {
|
||||
execution.kind = TransferKind::Return;
|
||||
for (std::size_t i = 1; i <= item_type_count; ++i) {
|
||||
const auto item = static_cast<ItemType>(i);
|
||||
if (const auto count = agent.inventory.item_count(item)) {
|
||||
add({0, ReservationKind::Item, {OwnerKind::Resident, agent.id}, agent.inventory.stack_id(item), item, count});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (execution.destination != 0) {
|
||||
add({0, ReservationKind::Capacity, {OwnerKind::Storage, execution.destination}, 0, {}, 1, capacity_backing});
|
||||
}
|
||||
agent.execution = execution;
|
||||
agent.next_admission = 2;
|
||||
}
|
||||
}
|
||||
|
||||
void World::write_save(std::ostream& stream, WorldSaveFormat format) const {
|
||||
const auto version = static_cast<std::uint32_t>(format);
|
||||
require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14,
|
||||
require_save(format == WorldSaveFormat::Legacy13 || format == WorldSaveFormat::Current14 ||
|
||||
format == WorldSaveFormat::Current15,
|
||||
"Unsupported save output format.");
|
||||
if (format != WorldSaveFormat::Current15 && !legacy_representable()) {
|
||||
throw UnsupportedLegacyState{};
|
||||
}
|
||||
if (format == WorldSaveFormat::Current15) WorldSaveCodec::validate(*this, true);
|
||||
SaveWriter archive(stream);
|
||||
for (char letter : signature) archive.field(letter);
|
||||
archive.field(version);
|
||||
@@ -685,6 +1018,7 @@ void World::write_save(std::ostream& stream, WorldSaveFormat format) const {
|
||||
archive.field(width_);
|
||||
archive.field(height_);
|
||||
WorldSaveCodec::body(archive, *this, version);
|
||||
if (version >= 15) WorldSaveCodec::custody(archive, *this);
|
||||
}
|
||||
|
||||
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode,
|
||||
@@ -707,6 +1041,7 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
|
||||
archive.field(height);
|
||||
auto world = std::make_unique<World>(seed, width, height, workers, mode, std::move(worker_options));
|
||||
WorldSaveCodec::body(archive, *world, version);
|
||||
if (version >= 15) WorldSaveCodec::custody(archive, *world);
|
||||
archive.finish();
|
||||
if (version < 5) {
|
||||
std::vector<GridPosition> occupied_ground;
|
||||
@@ -723,7 +1058,11 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
|
||||
}
|
||||
}
|
||||
}
|
||||
WorldSaveCodec::validate(*world);
|
||||
WorldSaveCodec::validate(*world, version >= 15);
|
||||
if (version < 15) {
|
||||
world->migrate_legacy_custody();
|
||||
world->validate_custody();
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user