Compare commits

..
Author SHA1 Message Date
faumaray 5dd0e35093 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 89bbb81317 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray e5464784f5 Record verified migration of thirteen historical colony states 2026-12-02 23:37:52 +03:00
faumaray e348a4291d Cross-check active work, retired receipts and storage claims 2026-12-02 23:34:58 +03:00
faumaray d613b73e1f Check source and capacity claims in authentic gathering and canceled work 2026-12-02 23:34:58 +03:00
faumaray 120db6cfa0 Canonicalize custody outcomes and enforce operation-specific work phases 2026-12-02 23:34:58 +03:00
faumaray 67fba6e3df Reject impossible terminal and travel states in authenticated checkpoints 2026-12-02 23:30:23 +03:00
faumaray a34733797b Compare stack, reservation and transfer state in every authoritative replay 2026-12-02 23:27:36 +03:00
faumaray 596b491acf Wait for owner fence admission when verifying viewer fault recovery 2026-12-02 23:26:10 +03:00
faumaray 7d5fbeb349 Exercise receipt uniqueness on a real split-input carpenter job 2026-12-02 23:26:10 +03:00
faumaray 8522f910b3 Exercise full-state replay with validated idle and generic job phases 2026-12-02 23:25:54 +03:00
faumaray 4f4c038051 Keep generic job phases and checked ID allocation consistent across loads 2026-12-02 23:23:51 +03:00
faumaray e26b9c2936 Replay complete custody receipts and historical migration state 2026-12-02 23:19:32 +03:00
faumaray ccd50ec40c Validate persisted operations against live custody invariants 2026-12-02 23:19:06 +03:00
faumaray a76bf87787 Bound save expansion and test authentic custody migration and journal wrap 2026-12-02 23:19:06 +03:00
faumaray 9e20f99a66 Validate work phases and retain exact refusal and consumption receipts 2026-12-02 23:19:05 +03:00
faumaray 3c7cc3ce2c Exercise replay against the modern custody state and migration 2026-12-02 23:17:10 +03:00
faumaray 539cea0608 Exercise modern saves against live transfer and reservation accounting
# Conflicts:
#	CMakeLists.txt
2026-12-02 23:11:05 +03:00
faumaray 6c6f4e7857 Track transfers, reservations and item owners through colony work 2026-12-02 23:10:35 +03:00
faumaray f1b8d41bb4 Persist item custody and restore in-flight work from historical saves 2026-12-02 23:10:35 +03:00
faumaray 4f42488d54 Define durable custody contracts shared by the world and checkpoint codec 2026-12-02 23:01:43 +03:00
47 changed files with 3609 additions and 2996 deletions

No files matched your search

+3 -11
View File
@@ -39,6 +39,7 @@ endif()
find_package(Threads REQUIRED)
add_library(settlement_core
engine/src/custody.cpp
engine/src/checkpoint.cpp
engine/src/checkpoint_files.cpp
engine/src/colony_profile.cpp
@@ -48,9 +49,7 @@ add_library(settlement_core
engine/src/rules_manifest.cpp
engine/src/save_service_win32.cpp
engine/src/simulation_runtime.cpp
engine/src/voxel_navigation.cpp
engine/src/worker_pool.cpp
engine/src/voxel_region.cpp
engine/src/world.cpp
engine/src/world_save.cpp
)
@@ -123,6 +122,8 @@ if(BUILD_TESTING)
add_executable(settlement_core_tests
tests/checkpoint_tests.cpp
tests/checkpoint_file_tests.cpp
tests/custody_tests.cpp
tests/custody_migration_tests.cpp
tests/core_tests.cpp
tests/executor_tests.cpp
tests/identity_tests.cpp
@@ -135,8 +136,6 @@ if(BUILD_TESTING)
tests/save_service_tests.cpp
tests/session_tests.cpp
tests/snapshot_tests.cpp
tests/voxel_navigation_tests.cpp
tests/voxel_region_tests.cpp
tests/test_main.cpp
)
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
@@ -146,13 +145,6 @@ if(BUILD_TESTING)
target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing)
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
add_executable(settlement_viewer_frame_smoke
tests/viewer_frame_smoke.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp)
target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing)
add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests)
+19 -44
View File
@@ -486,11 +486,6 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
} // namespace
class PreparedGeometry {
public:
Mesh mesh;
};
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
@@ -506,11 +501,10 @@ struct D3DScene::Backend {
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
std::shared_ptr<const PreparedGeometry> uploaded;
Mesh mesh;
bool resize(int w, int h) {
if (w == width && h == height && target_view && depth_view) return true;
uploaded.reset();
context->OMSetRenderTargets(0, nullptr, nullptr);
target_texture.Reset();
target_view.Reset();
@@ -538,7 +532,7 @@ struct D3DScene::Backend {
return true;
}
bool upload_geometry(const Mesh& mesh) {
bool upload_geometry() {
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
if (bytes > buffer_bytes) {
@@ -584,7 +578,7 @@ D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_shared<Backend>();
auto graphics = std::make_unique<Backend>();
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
@@ -634,41 +628,24 @@ bool D3DScene::initialize(HWND target, bool software) {
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
std::shared_ptr<const PreparedGeometry> D3DScene::prepare(const World& world, const SceneView& view) {
auto prepared = std::make_shared<PreparedGeometry>();
terrain(prepared->mesh, world, view);
resources(prepared->mesh, world);
construction(prepared->mesh, world, view.building_view);
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *backend_;
if (!graphics.resize(view.width, view.height)) return false;
graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view);
resources(graphics.mesh, world);
construction(graphics.mesh, world, view.building_view);
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
if (view.moving_room == index) continue;
const auto& plan = view.room_blueprints[index];
draw_room_plan(prepared->mesh, plan, false, world.can_place_room(plan));
}
if (view.room_preview) draw_room_plan(prepared->mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(prepared->mesh, part, false);
if (view.preview) draw_blueprint(prepared->mesh, *view.preview, true);
residents(prepared->mesh, world, view);
return prepared;
}
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
return render(prepare(world, view), view, capture);
}
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
std::vector<std::uint32_t>* capture) {
// Present may dispatch window messages, including destruction. Keep this
// backend alive until the current submission has returned.
const auto held_backend = backend_;
if (!held_backend || !geometry || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *held_backend;
if (!graphics.resize(view.width, view.height)) return false;
if (graphics.uploaded != geometry) {
if (!graphics.upload_geometry(geometry->mesh)) return false;
graphics.uploaded = geometry;
++uploads_;
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
}
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view);
if (!graphics.upload_geometry()) return false;
auto* ctx = graphics.context.Get();
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
@@ -689,11 +666,9 @@ bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const Sc
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
ctx->Draw(static_cast<UINT>(geometry->mesh.vertices.size()), 0);
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
if (graphics.swap_chain && FAILED(graphics.swap_chain->Present(0, 0))) return false;
++frames_;
return true;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
}
} // namespace settlement::viewer
+1 -12
View File
@@ -40,29 +40,18 @@ struct SceneView {
std::optional<std::size_t> moving_room;
};
// Immutable CPU geometry can outlive the latest frame and any GPU backend.
class PreparedGeometry;
class D3DScene {
public:
D3DScene();
~D3DScene();
D3DScene(const D3DScene&) = delete;
D3DScene& operator=(const D3DScene&) = delete;
bool initialize(HWND target, bool software = false);
[[nodiscard]] bool ready() const noexcept;
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
[[nodiscard]] static std::shared_ptr<const PreparedGeometry> prepare(const World& world, const SceneView& view);
bool render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
std::vector<std::uint32_t>* capture = nullptr);
[[nodiscard]] std::uint64_t uploads() const noexcept { return uploads_; }
[[nodiscard]] std::uint64_t frames() const noexcept { return frames_; }
void reset() noexcept;
private:
std::uint64_t uploads_ = 0, frames_ = 0;
struct Backend;
std::shared_ptr<Backend> backend_;
std::unique_ptr<Backend> backend_;
};
} // namespace settlement::viewer
+89 -268
View File
@@ -90,7 +90,6 @@ constexpr int min_interface_scale = 50;
constexpr int max_interface_scale = 250;
constexpr int default_interface_scale = 125;
constexpr int timer_id = 1;
constexpr int frame_timer_id = 2;
constexpr int map_size = settlement::first_colony_map_size;
constexpr int tile_width = 24;
constexpr int tile_height = 14;
@@ -295,63 +294,6 @@ std::optional<settlement::GridPosition> hover_cell;
std::optional<settlement::AgentId> selected_resident;
std::wstring placement_message;
// Publication stays on the UI thread. Readers pin the complete packet before
// calling Win32 (which can dispatch nested messages). Upstream publication:
// https://git.faumaray.com/Void/Library/issues/5
struct StatusText { std::wstring status, production, priority; };
struct FrameContent {
std::shared_ptr<const settlement::World> world;
std::vector<settlement::viewer::BlueprintPart> blueprint;
std::vector<settlement::RoomPlan> rooms;
settlement::viewer::SceneView view{};
std::shared_ptr<const settlement::viewer::PreparedGeometry> geometry;
std::wstring hint, details;
StatusText status;
};
struct PreparedFrame {
std::shared_ptr<const FrameContent> content;
settlement::viewer::SceneView view{};
DockLayout dock;
int width = 0, height = 0;
bool backend_ready = false;
std::shared_ptr<void> font;
};
std::shared_ptr<const PreparedFrame> prepared_frame;
std::uint64_t frame_requests = 1, sampled_request = 0;
bool pumping_session = false, preparing_frame = false, painting_scene = false, painting_main = false;
bool viewer_destroyed = false, repaint_pending = false;
void sample_frame(HWND window);
#ifdef SETTLEMENT_FRAME_TEST
std::function<void()> frame_test_after_poll, frame_test_during_paint;
#endif
struct PaintScope {
HWND window;
PAINTSTRUCT paint{};
HDC dc;
explicit PaintScope(HWND target) : window(target), dc(BeginPaint(target, &paint)) {}
~PaintScope() { EndPaint(window, &paint); }
};
struct PaintBuffer {
HDC dc;
HBITMAP bitmap;
HGDIOBJ previous;
PaintBuffer(HDC target, int width, int height) : dc(CreateCompatibleDC(target)),
bitmap(CreateCompatibleBitmap(target, width, height)),
previous(dc && bitmap ? SelectObject(dc, bitmap) : nullptr) {}
~PaintBuffer() {
if (previous) SelectObject(dc, previous);
if (bitmap) DeleteObject(bitmap);
if (dc) DeleteDC(dc);
}
explicit operator bool() const { return dc && bitmap && previous; }
};
struct FlagScope {
bool& flag;
explicit FlagScope(bool& value) : flag(value) { flag = true; }
~FlagScope() { flag = false; }
};
void pump_session(HWND window);
void reconcile_ticking();
@@ -527,9 +469,13 @@ POINT client_point(LPARAM coordinates) {
}
void invalidate_scene(HWND window) {
++frame_requests;
if (painting_main || painting_scene) repaint_pending = true;
if (showing_title && !viewer_destroyed) InvalidateRect(window, nullptr, FALSE);
RECT scene{};
GetClientRect(window, &scene);
scene.top = map_top;
if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE);
if (!showing_title && graphics.ready() && scene_window) {
InvalidateRect(scene_window, nullptr, FALSE);
}
}
void layout_scene(HWND window) {
@@ -947,8 +893,8 @@ void sync_resident_roster(bool update_selection = false) {
update_roster_details();
}
StatusText prepare_status() {
StatusText result;
void update_status() {
if (status_label == nullptr || !world) return;
const auto busy = std::count_if(world->agents().begin(), world->agents().end(),
[](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; });
std::uint64_t wood = 0;
@@ -975,13 +921,21 @@ StatusText prepare_status() {
L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) +
L" Двери: " + std::to_wstring(doors) +
L" Ход: " + std::to_wstring(world->tick());
result.status = text;
SetWindowTextW(status_label, text.c_str());
const bool scenario = world->scenario_active();
const bool can_play = can_give_orders();
if (work_panel != WorkPanel::None && !can_play) {
set_work_panel(GetParent(residents_button), WorkPanel::None);
}
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, can_play);
EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move);
const wchar_t* priority = L"Равный приоритет";
if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда";
else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка";
result.priority = priority;
if (scenario) {
SetWindowTextW(priority_button, priority);
if (scenario && production_label != nullptr) {
const auto progress = world->scenario_progress();
const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(),
[](const auto& agent) { return agent.state == settlement::AgentState::Sleeping; });
@@ -990,10 +944,10 @@ StatusText prepare_status() {
std::to_wstring(progress.residents) + L" Еда " + std::to_wstring(progress.available_food) +
L"/" + std::to_wstring(progress.food_goal) + L" Ткань " + std::to_wstring(cloth) +
L" Лён " + std::to_wstring(flax) + L" Спят " + std::to_wstring(sleeping);
result.production = goal;
return result;
SetWindowTextW(production_label, goal.c_str());
return;
}
{
if (production_label != nullptr) {
unsigned waiting = 0;
unsigned carrying = 0;
unsigned building = 0;
@@ -1013,22 +967,8 @@ StatusText prepare_status() {
L" Ткань: " + std::to_wstring(cloth) + L" Домики В очереди: " + std::to_wstring(waiting) +
L" Доставка: " + std::to_wstring(carrying) + L" Строятся: " + std::to_wstring(building) +
L" Готовы: " + std::to_wstring(built);
result.production = production;
SetWindowTextW(production_label, production.c_str());
}
return result;
}
void update_status() {
if (!world) return;
const bool scenario = world->scenario_active();
const bool can_play = can_give_orders();
if (work_panel != WorkPanel::None && !can_play) {
set_work_panel(GetParent(residents_button), WorkPanel::None);
}
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, can_play);
EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move);
}
void update_bed_choices() {
@@ -1373,7 +1313,7 @@ void handle_lan_menu(HWND window, int command) {
guest_intents.clear();
if (was_guest) {
clear_blueprints();
if (!session->changing_world()) world = session->world();
world = session->world();
}
enter_game_on_snapshot = false;
set_work_panel(window, WorkPanel::None);
@@ -1761,13 +1701,12 @@ void reconcile_ticking() {
}
void pump_session(HWND window) {
if (!session || pumping_session || preparing_frame || viewer_destroyed) return;
FlagScope pumping(pumping_session);
static bool pumping = false;
if (!session || pumping) return;
pumping = true;
struct Finish { ~Finish() { pumping = false; } } finish;
reconcile_ticking();
auto events = session->poll();
#ifdef SETTLEMENT_FRAME_TEST
if (frame_test_after_poll) frame_test_after_poll();
#endif
if (lan->is_guest()) {
if (auto incoming = lan->poll_guest()) {
session->receive_guest(std::move(incoming));
@@ -1776,21 +1715,13 @@ void pump_session(HWND window) {
} else if (lan->state() != LanState::Offline) {
lan->poll_host(session->runtime());
}
// A runtime install may publish after poll_changes observed an unready
// future. Never read that candidate until Replaced has reset client state.
const bool replacing = std::any_of(events.begin(), events.end(), [](const auto& event) {
return event.kind == settlement::viewer::ViewerEventKind::Replaced;
});
if (!session->changing_world() && !replacing) world = session->world();
world = session->world();
for (const auto& event : events) {
switch (event.kind) {
case settlement::viewer::ViewerEventKind::Replaced:
clear_blueprints();
camera = {};
selected_resident.reset();
hover_cell.reset();
move_source.reset();
world = session->world();
has_session = true;
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Поселение готово.");
@@ -2215,7 +2146,31 @@ std::wstring blueprint_details() {
return text;
}
std::pair<std::wstring, std::wstring> prepare_hud() {
void draw_world(HDC dc, int width, int height) {
RECT bounds{0, 0, width, height};
HBRUSH background = CreateSolidBrush(color(239, 235, 222));
FillRect(dc, &bounds, background);
DeleteObject(background);
if (!world) return;
if (!graphics.ready() && height > map_top + dock_layout.height) {
RECT scene{16, map_top + 24, width - 16, height - dock_layout.height};
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(55, 68, 59));
DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.",
-1, &scene, DT_CENTER | DT_WORDBREAK);
}
const RECT dock{0, height - dock_layout.height, width, height};
const auto dock_brush = CreateSolidBrush(color(34, 46, 40));
FillRect(dc, &dock, dock_brush);
DeleteObject(dock_brush);
const RECT dock_edge{0, dock.top, width, dock.top + 2};
const auto edge_brush = CreateSolidBrush(color(142, 132, 92));
FillRect(dc, &dock_edge, edge_brush);
DeleteObject(edge_brush);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(231, 227, 205));
const wchar_t* hint = world->scenario_active() ?
L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" :
L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство";
@@ -2255,6 +2210,10 @@ std::pair<std::wstring, std::wstring> prepare_hud() {
} else if (work_panel == WorkPanel::Carpenter) {
hint = L"Дверь и станок требуют по 2 дерева, шкаф — 1 дерево, стойка — по 1 дереву и камню.";
}
const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr;
const int margin = dock_pixels(12);
RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height};
DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
auto details = has_blueprint() ? blueprint_details() :
selected_room_template != settlement::RoomTemplate::Empty
? std::wstring((world->staged_beds() ? house_contents : simple_house_contents)
@@ -2278,43 +2237,9 @@ std::pair<std::wstring, std::wstring> prepare_hud() {
details += L" Назначьте плотника в списке «Жители».";
}
}
return {hint, std::move(details)};
}
void draw_world(HDC dc, const PreparedFrame& frame) {
const int width = frame.width, height = frame.height;
const auto& frame_dock = frame.dock;
RECT bounds{0, 0, width, height};
HBRUSH background = CreateSolidBrush(color(239, 235, 222));
FillRect(dc, &bounds, background);
DeleteObject(background);
if (!frame.content) return;
if (!frame.backend_ready && height > map_top + frame_dock.height) {
RECT scene{16, map_top + 24, width - 16, height - frame_dock.height};
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(55, 68, 59));
DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.",
-1, &scene, DT_CENTER | DT_WORDBREAK);
}
const RECT dock{0, height - frame_dock.height, width, height};
const auto dock_brush = CreateSolidBrush(color(34, 46, 40));
FillRect(dc, &dock, dock_brush);
DeleteObject(dock_brush);
const RECT dock_edge{0, dock.top, width, dock.top + 2};
const auto edge_brush = CreateSolidBrush(color(142, 132, 92));
FillRect(dc, &dock_edge, edge_brush);
DeleteObject(edge_brush);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(231, 227, 205));
const auto previous_font = frame.font ? SelectObject(dc, frame.font.get()) : nullptr;
const int margin = MulDiv(12, frame_dock.scale, 100);
RECT legend{margin, frame_dock.hint_top, width - margin, frame_dock.hint_top + frame_dock.line_height};
DrawTextW(dc, frame.content->hint.c_str(), -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
SetTextColor(dc, color(190, 201, 178));
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + frame_dock.line_height};
DrawTextW(dc, frame.content->details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height};
DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
if (previous_font) SelectObject(dc, previous_font);
}
@@ -2343,117 +2268,23 @@ settlement::viewer::SceneView scene_view(int width, int height) {
building_view, room_draft_move ? std::optional(room_draft_move->index) : std::nullopt};
}
bool same_part(const settlement::viewer::BlueprintPart& a, const settlement::viewer::BlueprintPart& b) {
return a.cell == b.cell && a.recipe == b.recipe && a.base == b.base;
}
bool same_room(const settlement::RoomPlan& a, const settlement::RoomPlan& b) {
return a.first == b.first && a.last == b.last && a.entrance == b.entrance && a.layout == b.layout;
}
template<class T, class Equal>
bool same_optional(const std::optional<T>& a, const std::optional<T>& b, Equal equal) {
return a.has_value() == b.has_value() && (!a || equal(*a, *b));
}
bool same_geometry(const FrameContent& a, const FrameContent& b) {
const auto& x = a.view; const auto& y = b.view;
return a.world == b.world && x.cursor == y.cursor && x.valid_cursor == y.valid_cursor &&
x.move_source == y.move_source && x.selected == y.selected && x.building_view == y.building_view &&
x.moving_room == y.moving_room && same_optional(x.preview, y.preview, same_part) &&
same_optional(x.room_preview, y.room_preview, same_room) &&
std::equal(a.blueprint.begin(), a.blueprint.end(), b.blueprint.begin(), b.blueprint.end(), same_part) &&
std::equal(a.rooms.begin(), a.rooms.end(), b.rooms.begin(), b.rooms.end(), same_room);
}
bool frame_visible(HWND window) {
if (viewer_destroyed || showing_title || !IsWindowVisible(window) || IsIconic(window)) return false;
RECT client{}; GetClientRect(window, &client);
return client.right > 0 && client.bottom > map_top + dock_layout.height;
}
void sample_frame(HWND window) {
if (!frame_visible(window) || preparing_frame || pumping_session || painting_main || painting_scene) return;
FlagScope preparing(preparing_frame);
// changing_world is UI-owned: the worker cannot clear this gate. This also
// holds an absent initial world while a first install is in flight.
if (session && !session->changing_world()) {
auto latest = session->world();
if (world != latest) { world = std::move(latest); ++frame_requests; }
}
if (prepared_frame && !repaint_pending && sampled_request == frame_requests &&
prepared_frame->backend_ready == graphics.ready()) return;
const auto request = frame_requests;
const bool repaint = std::exchange(repaint_pending, false);
RECT client{}; GetClientRect(window, &client);
auto frame = std::make_shared<PreparedFrame>();
frame->width = client.right; frame->height = client.bottom;
frame->dock = dock_layout; frame->backend_ready = graphics.ready();
const auto previous = prepared_frame;
if (previous && previous->dock.scale == dock_layout.scale) frame->font = previous->font;
else if (dock_font) {
LOGFONTW font{};
if (GetObjectW(dock_font, sizeof(font), &font)) {
frame->font = std::shared_ptr<void>(CreateFontIndirectW(&font), [](void* value) { if (value) DeleteObject(value); });
}
}
if (session && session->changing_world()) {
if (previous) frame->content = previous->content;
} else if (world) {
auto content = std::make_shared<FrameContent>();
content->world = world;
content->blueprint = blueprint; content->rooms = room_blueprints;
content->view = scene_view(client.right, client.bottom - map_top - dock_layout.height);
content->view.blueprint = content->blueprint; content->view.room_blueprints = content->rooms;
content->status = prepare_status();
auto hud = prepare_hud();
content->hint = std::move(hud.first); content->details = std::move(hud.second);
if (previous && previous->content && same_geometry(*content, *previous->content)) {
content->geometry = previous->content->geometry;
} else content->geometry = settlement::viewer::D3DScene::prepare(*content->world, content->view);
frame->content = std::move(content);
}
if (frame->content) frame->view = frame->content->view;
const auto pan = camera.offset(); const auto scale = camera.scale();
frame->view.width = client.right; frame->view.height = client.bottom - map_top - dock_layout.height;
frame->view.origin_x = static_cast<float>(client.right / 2 * scale + pan.x);
frame->view.origin_y = static_cast<float>(map_origin_y * scale + pan.y - map_top);
frame->view.scale = static_cast<float>(scale);
sampled_request = request;
if (!repaint && previous && previous->content && frame->content &&
previous->content->geometry == frame->content->geometry &&
previous->content->hint == frame->content->hint && previous->content->details == frame->content->details &&
previous->width == frame->width && previous->height == frame->height &&
previous->dock.scale == frame->dock.scale && previous->dock.height == frame->dock.height &&
previous->dock.hint_top == frame->dock.hint_top && previous->dock.line_height == frame->dock.line_height &&
previous->backend_ready == frame->backend_ready && previous->view.origin_x == frame->view.origin_x &&
previous->view.origin_y == frame->view.origin_y && previous->view.scale == frame->view.scale) return;
prepared_frame = std::move(frame);
// Publish before notifying child controls: their synchronous paints may nest.
if (prepared_frame->content) {
const auto content = prepared_frame->content;
SetWindowTextW(status_label, content->status.status.c_str());
SetWindowTextW(production_label, content->status.production.c_str());
SetWindowTextW(priority_button, content->status.priority.c_str());
}
InvalidateRect(window, nullptr, FALSE);
if (scene_window && IsWindowVisible(scene_window)) InvalidateRect(scene_window, nullptr, FALSE);
}
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
const auto held_world = world;
try {
if (message == WM_NCHITTEST) return HTTRANSPARENT;
if (message == WM_ERASEBKGND) return 1;
if (message == WM_PAINT) {
const auto frame = prepared_frame;
if (painting_scene) { ++frame_requests; repaint_pending = true; ValidateRect(window, nullptr); return 0; }
FlagScope painting(painting_scene);
PaintScope paint(window);
#ifdef SETTLEMENT_FRAME_TEST
if (frame_test_during_paint) frame_test_during_paint();
#endif
const auto parent = GetParent(window);
RECT viewport{}; GetClientRect(window, &viewport);
if (viewport.right <= 0 || viewport.bottom <= 0) return 0;
if (!frame_visible(parent) || !IsWindowVisible(window) || !frame || !frame->content) return 0;
const bool drawn = !graphics.ready() || graphics.render(frame->content->geometry, frame->view);
PAINTSTRUCT paint{};
BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const bool drawn = !world || !graphics.ready() ||
client.right <= 0 || client.bottom <= 0 ||
graphics.render(*world, scene_view(client.right, client.bottom));
EndPaint(window, &paint);
if (!drawn) {
graphics.reset();
const auto parent = GetParent(window);
layout_scene(parent);
invalidate_scene(parent);
}
@@ -2756,9 +2587,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
apply_interface_scale(window, read_interface_scale());
show_title_screen(window, true);
refresh_lan_controls(window);
viewer_destroyed = false;
SetTimer(window, timer_id, 60, nullptr);
SetTimer(window, frame_timer_id, 16, nullptr);
return 0;
}
case WM_DRAWITEM:
@@ -3103,8 +2932,6 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
}
break;
case WM_TIMER:
if (viewer_destroyed) return 0;
if (wparam == frame_timer_id) { sample_frame(window); return 0; }
if (wparam == timer_id) {
pump_session(window);
return 0;
@@ -3112,12 +2939,7 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
break;
case WM_ERASEBKGND:
return 1;
case WM_SHOWWINDOW:
repaint_pending = true;
invalidate_scene(window);
break;
case WM_SIZE:
invalidate_scene(window);
if (showing_title) {
RECT client{};
GetClientRect(window, &client);
@@ -3128,29 +2950,28 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
InvalidateRect(window, nullptr, FALSE);
break;
case WM_PAINT: {
sample_frame(window);
const auto frame = prepared_frame;
if (painting_main) { ++frame_requests; repaint_pending = true; ValidateRect(window, nullptr); return 0; }
FlagScope painting(painting_main);
PaintScope paint(window);
RECT client{}; GetClientRect(window, &client);
const int width = client.right, height = client.bottom;
if (viewer_destroyed || !IsWindowVisible(window) || IsIconic(window) || width <= 0 || height <= 0) return 0;
PaintBuffer buffer(paint.dc, width, height);
if (!buffer) { ++frame_requests; repaint_pending = true; return 0; }
if (showing_title) title_screen.draw(buffer.dc, width, height, placement_message);
else if (frame) draw_world(buffer.dc, *frame);
else FillRect(buffer.dc, &client, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
const RECT& dirty = paint.paint.rcPaint;
BitBlt(paint.dc, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top,
buffer.dc, dirty.left, dirty.top, SRCCOPY);
PAINTSTRUCT paint{};
HDC target = BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const int width = client.right - client.left;
const int height = client.bottom - client.top;
HDC buffer = CreateCompatibleDC(target);
HBITMAP bitmap = CreateCompatibleBitmap(target, width, height);
HGDIOBJ old_bitmap = SelectObject(buffer, bitmap);
if (showing_title) title_screen.draw(buffer, width, height, placement_message);
else draw_world(buffer, width, height);
const RECT& dirty = paint.rcPaint;
BitBlt(target, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top,
buffer, dirty.left, dirty.top, SRCCOPY);
SelectObject(buffer, old_bitmap);
DeleteObject(bitmap);
DeleteDC(buffer);
EndPaint(window, &paint);
return 0;
}
case WM_DESTROY:
viewer_destroyed = true;
KillTimer(window, frame_timer_id);
KillTimer(window, timer_id);
prepared_frame.reset();
lan->leave();
graphics.reset();
if (dock_font) DeleteObject(std::exchange(dock_font, nullptr));
-6
View File
@@ -93,9 +93,3 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
В `a8cd7bb` объединены заказы с постоянными ID и два варианта правил строительства кровати. Формат контрольной точки 2 сохраняет ID заказов и следующий свободный ID. Прежние контрольные точки и обычные сохранения версии 13 продолжают загружаться. Оба варианта правил прошли строительство реальных кроватей, сохранение во время доставки и сравнение продолжений на 1/2/6/12 исполнителях. В объединённой сборке под Wine прошли 122 теста ядра и 9 LAN. Аппаратная Windows ещё не проверена. [Заказы S04](../plan/systems/S04.md) · [Правила S19](../plan/systems/S19.md) · [Интеграционная проверка](tasks/M01-V11.md)
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
В `37fb6a8` объединены проверяемая передача всего груза одной остановки и выбор правил на титульном экране. Игрок может создать поселение с поэтапной сборкой кровати либо с рецептом из одной доски. При открытии сохранения восстанавливается его собственный набор правил. Испытание настоящего окна проверило оба выбора мышью и клавиатурой, файл и продолжение из нового процесса. В общей сборке под Wine прошли 136 тестов ядра, 9 LAN и 14 клиента. [Загрузка и инвентарь S06](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11) · [Клиент S18](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/13) · [Совместная проверка](tasks/M01-V12.md)
В `048268a` две настоящие рабочие задачи завершаются в противоположном порядке. Во всех 24 воспроизведениях победитель спорной заявки и байты состояния совпали с последовательной партией. При загрузке более старого мира запоздалый результат не изменил новую партию. Windows x64 под Wine прошла 141 тест ядра, 9 LAN и 14 клиента. [Проверки S21](../plan/systems/S21.md) · [Интеграционная проверка](tasks/M01-V13.md) · [Управляемый порядок завершения в VoidLibrary](https://git.faumaray.com/Void/Library/issues/15)
В `455630f` камера отвечает на колесо мыши и перетаскивание, пока симуляция или запись файла задержана. Проверка настоящего окна сравнила пиксели и байты контрольной точки, воспроизвела замену мира между опросом и рисованием и проверила сохранение прежнего кадра. Под Wine прошли 141 тест ядра, 9 LAN, 14 клиента и отдельное испытание кадра с видимой цепочкой D3D11 и WARP. Проверка в нескольких процессах также подтвердила выбор и загрузку обоих рецептов кровати. Частота кадров на физическом Windows-ПК ещё не измерена. [Рендерер S17](../plan/systems/S17.md) · [Совместная проверка](tasks/M01-V13.md)
-4
View File
@@ -48,7 +48,3 @@ User authorizes roadmap/push/MRs/upstream issues; root owns all external actions
Return M01-V12 separate S06/S18 verdicts, real files/paths/tests, exact remains and native caveats, later integrated check as assigned.
The S06 component passed and is committed as `3c997ed`. Compare integration `66af7c5` (parents `e6a01be` and `3c997ed`) to each parent. Inspect actual `m01-quantity-{build,ctest}.log`: Windows x64 under Wine passed 136 core, 9 LAN and 10 viewer tests. S18-02 is still a separate pending review.
The integrated S06 check passed. S18-02 now has finished production changes against `e6a01be` in the s18 checkout. Inspect both real title/handler sources in the temporary evidence directory and `client-profile-*` logs, including a real two-process title choice/save/open, normal GUI regressions, held-load Host refusal and 14 viewer cases. Validate the actual six edited files, costs and initial/async gate along with the compiled profile and LAN boundaries.
The S18 component passed and is committed as `180506d`. Integrated `37fb6a8` has parents `f6493e2` and `180506d`. Inspect the combined selector/quantity source against those parents, CMake and `m01-selection-{build,ctest,ui}.log`. The real application smoke used the executable in the integrated build directory.
-52
View File
@@ -1,52 +0,0 @@
# Audit deterministic completion evidence and immutable presentation frames
Task ID: M01-V13
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S21-01 sibling s21 at 66af7c5 with new optional success hook and actual replay/fault barrier tests; branch final pass imminent. S17-01 sibling s17 same base with immutable packet/render caching and test target in progress. Original contracts S21-01/S17-01 and preflight F9/P6. Root cumulative currently 5a64a27 includes S18-02 profile chooser.
## 2. Objective and deliverables
Review CPU observer/real replay/diagnostics and independent GUI presentation as separate completed components and later combined integration. Send all actual blocking findings immediately.
## 3. Scope and non-goals
S21 worker adapter and tests/diagnostics/docs; S17 frame packet creation, D3D mesh/upload, lifetime/timer and actual test path. S06 custody15 beyond scope except future compatibility noted.
## 4. Files to inspect
Inspect actual tracked/untracked files and exact contracts in siblings. S21 world.hpp/world.cpp stage layout, WorkerPool submit/admit, tests/executor/replay/runtime, new diagnostics, end-to-end old corpora and logs. S17 actual Win32 handlers, scene packet and D3D, tests/viewer_frame_smoke.cpp, CMake, involved S18 session/GUI, Win32 smoke and docs.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch; siblings outside root graph require direct source. Check diff --check and new source separately.
## 6. Implementation or investigation approach
S21 success-only invocation (void/value/reference/move-only, throws, overload and before_submit/before_execute failure), original no-hook semantics and capacity. Validate opposing actual completions (two real candidate calculations, separate driver/hook release), lower ID winner, serial berry claim vs parallel advancement, no flakiness/deadlocks, stale load barrier and modern Current14, domain mismatch reports and tests incl byte fallback; inspect fixture/scoped source and actual logs.
## 7. Interfaces and data contracts
S17 after ready marker verify one immutable prepared packet held across nested callbacks even during release/install, candidate not sampled while changing before consumed Replaced, owned overlays and HUD, true camera-only reuse of prepared physical geometry and GPU upload keyed over all visuals incl reset, no extra work hidden/resized/destroyed; original camera input, GUI titles/profile and normal LAN/events still work. Check actual settled tests including two real windows, blocked file/owner, saved content, offscreen/native fallback and helper includes.
## 8. Dependencies and integration
Stage A S21 ready first; stage B only on finished status, separate integrated approvals requested later. No sign-off until actual cross-component evidence and fixes are available.
## 9. Edge cases security and performance
Pay particular attention to return category/dangling references, accidentally recording pre-completion, capacity1 coordinator deadlock, exceptions in optional hook, tests changing data outside owner. For S17 camera/cursor geometry keys, offscreen rendering and clipping/nested frames, pending parent/child window messages, backend recreation and save/peer replacement while rendering. Do not equate Wine with native Windows.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. State source/trigger/severity and corrective acceptance per defect. 3. Verify actual logs with issue #15 link and stable old corpora, new frame target and prior GUI smoke. No unsupported physical 60fps claim.
## 11. Verification commands and evidence
Use git -C <wt> rev-parse/status/diff --check; read new files and surrounding actual consumers. In /tmp/stoneheart-milestones.xprJ2SVp inspect s21-replay-* and s17-frame-* logs and harnesses once supplied. Eventual merged refs and logs will be appended.
## 12. Constraints and stop conditions
Check actual completed source, no early approval of another component. No source/branch/Gitea changes/children. After corrective commit re-audit relevant behavior per root instructions.
## 13. Authorization and decisions
User authorizes all milestone/system development and Gitea, root owns all external operations; published reusable missing completion test support upstream #15 and existing publication issue #5.
## 14. Return format
Return M01-V13 S21/S17 independent findings, inspected source/logs/limits, then integrated recheck when supplied.
S21 branch `ef980af` passed component review. Integrated root commit `048268a` has parents `5a64a27` and `ef980af`; inspect `m01-replay-{build,ctest}.log` and check its actual merged adapter, registered suites and unchanged core/GUI. S17 code and docs have also frozen in the sibling worktree at the original base plus working source. Read the actual committed-path smoke source, all tracked edits, and `s17-frame-*` logs. Verify the corrected pre-Replaced fence and stable rendering/cache/lifecycle conditions before branch approval.
Final S17 integration `455630f` joins reviewed `1cf8bd0` and `e9e7e82`. Cross-check S18 title/profile/host eligibility and S17 packet replacement, timer, GPU and cleanup against both parents. The build, verbose four-target CTest and separate multi-process real profile smoke are in `m01-frame-build.log`, `m01-frame-ctest.log` and `m01-frame-profiles.log`.
-48
View File
@@ -1,48 +0,0 @@
# Review finite voxel region contracts before implementation
Task ID: M02-F1
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Read-only preflight of M02-P1 initial design from actual 455630f M02 worktree. The signed 32³ sparse page foundation is independent of M01 custody 539cea0 now in progress. Existing renderer already uses z as vertical height via x−y, (x+y)−z and existing viewer picks the z=0 plane. Library first M02-R1 confirmed pin 7b0fea6, upstream #11 signed division and #14 sparse atomic edits, #12 ray traversal, #13 revision readsets, #10 RNG; actual public math/binary/hash available.
## 2. Objective and deliverables
Independently decide whether bounded S02 geometry/generation contract is safe to implement now. Review the later S03/normal runtime/save/presentation boundaries insofar as they constrain S02 data. Send foundation verdict early; root may later supply planner final addendum.
## 3. Scope and non-goals
Only M02 correctness preflight with first S02 slice priority. No implementation, release/PR acceptance, M03+ design or approval of unchecked future code.
## 4. Files to inspect
Read real M02 worktree docs/agent-workflow/tasks/M02-P1.md, M02-R1 and plans M02/S02/S03/S15/S17/S18, void-library.md; root existing world.hpp, world.cpp WorldState::capture, worker_pool, world_save and checkpoint, app/map_camera.hpp, d3d_scene_win32.cpp shader, viewer_win32.cpp pick_grid, first_colony and actual tests; private current15 in /tmp/stoneheart-milestones.xprJ2SVp/combined-custody. Inspect exact graph root only if relevant; direct sibling sources required.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posting, shared project switching, user contact or children.
## 6. Implementation or investigation approach
Attack proposed NEW VoxelRegion/value view with nonzero RegionId, int32 voxel xyz, finite half-open bounds, ordered key directory/sharing immutable 32³ pages, generator keyed by exact seed+version+absolute xyz, queries separate outside/unloaded/loaded air. Page publication precedes ready only at logical designated step. Edits validate all expected revisions/bounds/materials/caps/unsupported operations, finite canonical order and no partial mutation, publish touched revisions once and invalidate face neighbors without fictitious content changes. Focus on material id stability, thin bounds intersecting pages and border operations. Query correctness at both signed extremes and boundary examples, no pointer/reference mutation. Check which exact domain is expected to be represented.
## 7. Interfaces and data contracts
Review ownership/constructor/geometry exposure, immutable page pointers vs mutable alias to page/cache/directory, exact all-or-nothing publication, result visibility/cache invalidation incl reads of inactive/neighbors, validity of one stable geometry revision for render and path when head changes due to activation/deactivation. Propose minimal interfaces and stable tests without duplicating future WorldState. Check D3D renderer z-up and slice/face tie contract.
## 8. Dependencies and integration
Foundation worker has isolated file ownership in NEW voxel_region.hpp/cpp/test plus CMake and S02 docs. World/runtime/save protocol integrating with S15/16 requires final agreed schema and cannot clobber S06 custody15. Preserve protocol11 by explicit representability; original 2D first colony must remain readable/playable.
## 9. Edge cases security and performance
Negative division at INT_MIN and max half-open bounds, dirty neighbor overflow at extreme chunk ids, seed sign/ordering/algorithm version, bounded page/batch memory and worst-case old snapshot retention, revision rollover/admission, no-op/duplicates/conflicting expectations; negative/zero ray incl edge tie, stale auth, work/tick exposure, failed chunk activation/crossing. Differentiate genre policies/materials and requested Void issues.
## 10. Acceptance criteria
1. READY or BLOCKED with precise mandatory first-slice fixes and testable criteria. 2. State if parallel independent implementation is sound within compiled M02 base before M01 finished. 3. Capture edge behavior and feasible tests for generation, bounds, stale atomic recompute, immutable view, deterministic batch and subsequent consumers. 4. Mark unknown physical target verification. Do not review a future code diff prematurely.
## 11. Verification commands and evidence
Read-only git status/rev-parse and source refs in the M02 and combined worktrees. Compare pinned source with M02-R1 and note no binary evidence unless reading actual existing logs. Project index root-only; direct reads for sibling files. Later CTest should use exact Windows x64 GCC16/Wine test setup in M02-P1.
## 12. Constraints and stop conditions
No approval of M01 scope or M02 implementation, no code, no Git/Gitea changes/children. If a substantial missing contract is identifiable, provide counterexample and precise remedy without tacking on speculative features.
## 13. Authorization and decisions
User requested end-to-end milestone implementation and library gap filing. Preflight gates first edits, not engineering judgment on reversible local choices. Root integrates findings into worker specs and owns upstream effects.
## 14. Return format
Return M02-F1 preflight with earliest foundation assessment then notes for remaining consumers, actual source references, required tests and stop conditions for implementation.
-48
View File
@@ -1,48 +0,0 @@
# Design the first playable editable voxel region and its integration
Task ID: M02-P1
Role: astra_planner
Status: READY
## 1. Context and baseline
The user approved implementing M00–M12 on milestone and system branches. M01 currently provides a 50 ms authoritative World, immutable snapshots, authenticated commands, released rules profiles, protocol11 and modern checkpoints. M02 worktree at 455630f has S17 immutable frames and S21 real scheduler tests. Local M01 candidate 539cea0 adds modern raw15/checkpoint3 transfer persistence. An independent pin/API audit M02-R1 at Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 found library gaps reported as Void/Library #10–14. This is a preparatory design while M01 exit evidence is in flight.
## 2. Objective and deliverables
Provide actionable dependency boundaries for M02 and the first implementable S02 region/chunk/component that can be built now without conflicting with M01 custody work. Continue to cover S03, S17/S18, S15 and normal owner/runtime end to end so the first terrain output has real consumers.
## 3. Scope and non-goals
Read-only milestone architecture and phased, playable acceptance. Focus limited M02 editable voxel scenario through two levels and chunk edge. Defer M03 colony storage/building changes, water, other worlds, plugin changes and release. No arbitrary lowering of approved roadmap scope or new UI product choice.
## 4. Files to inspect
Inspect docs/plan/milestones/M01.md and M02.md; docs/plan/systems/{S02,S03,S15,S17,S18,S21}.md, docs/plan/void-library.md and M02-R1; engine/include/settlement/core/{world,simulation_runtime,command_dispatcher,worker_pool,deterministic_rng}.hpp and world/first_colony/world_save CPU paths; app/d3d_scene_win32.*, map_camera.hpp, viewer_win32.cpp, tests/frame/replay/identity/checkpoint. Use actual names in results. Read sibling custody.hpp and checkpoint.hpp at combined 539cea0 to avoid schema collision. No fetching private data outside project.
## 5. Write ownership and coordination
Write scope: none
No edits, branch/remote ops, builds that modify worktrees, project switch or children. Parent persists results. Root and sibling agents are working in separate checkouts. For isolated M02 use direct files and avoid changing shared Serena project.
## 6. Implementation or investigation approach
Map owner/tick/frame/file architecture, deterministic generation keyed by signed world location, gates for snapshots/cache and async activation. Specify finite 32³ sparse page representation and signed Euclidean division, fatal and retriable edit paths, exact row/coordinate order, native Win32 interaction scenario, known old-save/old-LAN behavior and how these can be tested using real consumers. Identify the first S02 slice that can receive an independent concrete coding contract at once; send it early.
## 7. Interfaces and data contracts
Propose NEW clear types and methods by responsibility with essentials only: region identities/int coords with z up, bounds/limits, material query/source/support+edit revision set and undo on failure, copy-on-write pages immutable to snapshots, deterministic per-chunk source and edit overlay; S03 use cases incl stable ties, minimum profile/door/stairs and consulted revision sets incl misses and neighbors; ray/pick face from D3D Y-up conversion and actual commands; M02 persistent version/generator identity; reconcile normal M01 World lifecycle, actual public source/test consumers and authored test scenario. Distinguish proposed APIs from existing ones.
## 8. Dependencies and integration
Root reconciles M02-R1, planner, independent preflight and starts S02 in an isolated branch before coupling to mutable M01 sources when safe. Make ownership/dependency ordering and concrete integration points clear. Source-only private S06/S15 candidates must never be treated as published.
## 9. Edge cases security and performance
Bound coordinate overflow (INT_MIN, ±32), sparse memory and checked edit count, stale/mixed revisions, border invalidation, optimistic deterministic admission/queued jobs, signed normal/cell at equally crossed faces, old saves and LAN projections of edited maps, delayed/out-of-order and corrupted chunk I/O, camera/view consistency and finite scheduling. Respect pinned Void API/tests and replacement cases for #10–14 in repository matrix.
## 10. Acceptance criteria
1. Concrete HOW/WHAT for S02 first worker including new files/headers/CMake and behavioral tests with cross-boundary negative coordinates, immutable snapshots, failed multi-page edit and independent generation. 2. Bounded follow-on packages S03, authoritative/edit/tick+save, real UI and exit verification with actual dependencies. 3. Identify genuine missing library contract only after checking pin and issues. 4. Normal small scenario is visible, editable, traversable and survives save/restore across thread order.
## 11. Verification commands and evidence
Read-only git -C <m02> rev-parse HEAD/status/diff and git -C /tmp/stoneheart-milestones.xprJ2SVp/combined-custody show as needed; use direct source in sibling worktrees. Give real proposed CMake GCC16 cross and CTest commands for later workers based on /tmp/stoneheart-verify.KoZwE4o8/env.sh and existing target. Native Windows cannot be asserted from Wine.
## 12. Constraints and stop conditions
Stop and report if a required product choice truly blocks first slice; use reversible decisions matching approved M02 otherwise. No source mutation, speculative library ticket, user messages, or children. Do not claim test execution.
## 13. Authorization and decisions
User explicitly asks to implement all milestones, reuse library APIs and file concrete gaps. Root owns all side effects. User authorization already covers bounded M02 foundation and branch/MRs.
## 14. Return format
Return M02-P1 PLAN with early immediately implementable S02 slice, dependency order/ownership, immutable contracts, concrete tests/risks/source refs and remaining evidence. No approval or merge decisions.
-50
View File
@@ -1,50 +0,0 @@
# Implement immutable finite voxel regions and atomic multi-chunk edits
Task ID: S02-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Actual isolated system/s02-voxel-world at 0d71bcf, parent milestone/m02-voxel-world. M02-P1 plan and F1 independently accepted first slice. Existing first colony WorldState copied on capture and flat terrain remains, renderer z-up. Cross-toolchain CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Void Math::Numeric checked arithmetic, Binary::Writer and Hash public, signed split/atomic pages absent and tracked upstream #11/#14. M01 final custody in isolated siblings, no overlapping source needed.
## 2. Objective and deliverables
Build a tested, ready-to-integrate finite authoritative voxel region with deterministic versioned terrain, signed coords and immutable chunk pages, checked all-or-nothing multi-page edits and accurate surface invalidation. The first file consumers are S03 nav queries, S17 surfaces and M02 World/serializer/activation. Freeze a usable header early and send actual declarations to root.
## 3. Scope and non-goals
Only memory representation, generation, prepared page installation, querying and edits for the finite one-region M02 foundation. No unrelated RNG, terrain viewer, WorldState or format edits, S03 path solver, resource ledger, gameplay or network. Input/outcome types below are NEW and may be named idiomatically.
## 4. Files to inspect
Read docs/plan/milestones/M02.md, systems/S02 + S03, dependency matrix section M02 + actual pin headers/tests for Math/Numeric, Binary and Hash. Inspect world.hpp/world.cpp capture, default 2D semantics, actual 3D shader at app/d3d_scene_win32.cpp, CMake targets and registered Void::Testing suites. S06 / S15 provisional custody data unneeded. Read M02-P1/F1.
## 5. Write ownership and coordination
Write scope: NEW engine/include/settlement/core/voxel_region.hpp; NEW engine/src/voxel_region.cpp; NEW tests/voxel_region_tests.cpp; CMakeLists.txt only two source/test entries; docs/plan/systems/S02.md
Your isolated s02 checkout only. Others work in separate WTs, do not overwrite or revert their changes. No Git/remote operations, shared Serena switch, children.
## 6. Implementation or investigation approach
Define checked nonzero uint64 RegionId, int32 xyz with z-up, int64 half-open endpoints verifying within [INT32_MIN,INT32_MAX+1], strictly positive volume per axis (finite coordinate bounds need not densely allocate), chunk/local split no -INT_MIN, x-fast 32³ index. Stable material identifiers air/soil/stone, configurable bounded resident pages (default256), edit count (default4096), and actual checked staging/result/directory sizes (default allow full bounded batch). Region copies or dedicated immutable views share complete directory/pages via const ownership; no retained mutable aliases or mutable raw span. Immutable generator candidate is keyed by metadata/coords, source initialized independent of job ordering, deterministic generator1 with plausible soil surface/stone below and canonical absolute-coordinate encoding via actual Void Binary/Hash, uses no shared RNG. Mask all cells outside partial region.
## 7. Interfaces and data contracts
Ordinary query distinguishes outside bounds vs unavailable vs loaded air; returns stable coordinate/read stamp matching caller lifetime. Separate pure generation/preparation from explicit all-or-nothing publication so later M02 owner controls logical tick. Region may not install result from a different region/seed/generator/coordinate or expired expectation. Keep page/availability paths usable by future persistence. A bounded atomic edit requires exact revision expectations for each touched chunk (including no-op), rejects duplicate cells, unsupported material/coords/bad expectations before publishing. Empty/all-identical edit has no changes. Sort changed cells/pages and actual neighbor invalidations canonically; increment once per truly changed page, unchanged neighbors keep material stamp, loading must be observable by dependencies. Extreme revision denies change before first effect. No need for unload until a later consumer, if implemented prevent ABA with persistent stamp. Define what finite bounds/unavailable neighbor contributes to dirty key.
## 8. Dependencies and integration
Host only builds Windows; unit checks linked in actual settlement_core_tests. Root merges S02 into M02 and cumulative only after review. Need write stable header before dependent S03/S17 and alert parent if implementation materially changes contract. Other workers own old World/codec/camera, never edit those. Local implementation explicitly references Void/Library #11/#14 in S02 docs with exact replacement tests.
## 9. Edge cases security and performance
Widen origins, local indexes and neighbor math before conversion; avoid INT overflow/padding/endian and unbounded directory/grid construction. Bound working + staging memory before allocations and reject insufficient limits unchanged. Stage all pages and result list before final nonthrowing swap; preserve original content/pointer/revision on bad batch, allocation failure and MAX counter. External retained snapshots own memory separately, state its limit precisely. Prefer compact materials and deterministic column generation; full active 256 pages must not cause unrelated pages to be recopied on each edit. No nondeterministic unordered serialization or generation.
## 10. Acceptance criteria
1. Exact split/join and x-fast indices at INT_MIN,−33,−32,−1,0,31,32,INT_MAX incl [max,max+1) and partial negative/extreme bounds. 2. Canonical full material content and revisions independent of forward/reverse/parallel preparation, real neighboring signed coordinate continuity/golden seed, precise different availability/air. 3. Two-page edit succeeds atomically and old view unchanged; stale second/unloaded/duplicate/unknown/budget/MAX fail unchanged, unchanged writes validate expectation and do not increment; correct face vs edge neighbor invalidation across boundaries. 4. No additional unlinked generic shim outside #11/#14; real release compilation and focused/full CTest, report actual footprint/copy behavior and evidence. 5. Document useful public operations in S02 and share frozen header.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run --tag voxel-region at your build, complete CTest -V (coordinate any real windows via root) and git diff --check; logs /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-*.log. Native Windows beyond cross tests not verified. Test revision exhaustion via meaningful persistence/import or narrow deterministic seam without exposing an unchecked arbitrary setter.
## 12. Constraints and stop conditions
Do not silently expand M02 to full renderer/World or change prior save formats. If dependency contract missing, verify pin plus check existing issues, report exact consumer/guarantee and root handles any filing. Two unsuccessful same-cause fixes escalate with original contract/evidence. No publishing or other checkout edits.
## 13. Authorization and decisions
User authorizes all milestone/system coding, Gitea PRs and true Void gaps. Root chose region identity and finite signed z-up cells, M02 product decisions in milestone doc; planner/preflight complete for this slice. Concrete bounded storage/container choices delegated.
## 14. Return format
Return S02-01 READY or PARTIAL, early frozen API and relevant coordinate/frame assumptions, controlled failure cases, working paths, actual verification counts/measurements/limits and remaining integration seams.
The M02 door uses two stable non-generated cell kinds, `MaterialId::DoorClosed` and `MaterialId::DoorOpen`, appended after Air, Soil and Stone. A closed door blocks body clearance; an open door and air permit clearance. Only Soil and Stone provide standing support. Publish NEW `voxel_blocks_passage(MaterialId)` and `voxel_provides_support(MaterialId)` queries for the navigation and presentation owners. Both halves of a door can be changed in the same checked edit batch. Invalid materials remain rejected. The generator produces natural materials only, and the gameplay owner controls who may operate or mine a door. Add tests for these shared semantics, both updating over a page boundary if applicable, and tell root when the adjusted header is frozen. This prevents a second source of door geometry, occupancy and invalidation in navigation.
-52
View File
@@ -1,52 +0,0 @@
# Find and revalidate settler routes across editable voxel chunks
Task ID: S03-01
Role: sol_implementer
Status: READY
## 1. Context and baseline
Actual isolated system/s03-navigation worktree at 6d1123e has frozen region API voxel_region.hpp, S02 implementation/registration arriving from sibling before testing. M02-P1/F1 reviewed source/algorithm limits; M01 flat assignment_path keys are two-dimensional and World::step advances without revalidation. S03 is disjoint from existing World and S02 implementation. Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 supplies IndexedGraphView/bfs/shortest_path_unweighted WorkLimits. Generic consulted revision sets absent, already tracked #13.
## 2. Objective and deliverables
Implement tested bounded 3D ordinary-settler path query, interaction positions, consulted effective chunk revisions and transition revalidation. Ready for the authorized M02 World movement/mining owner to consume; send actual frozen public API early.
## 3. Scope and non-goals
Only new voxel navigation module, real standalone tests, CMake entries and S03 docs. Use shared S02 data; leave old flat A*, World/serializer/actual HWND/drawing to their assigned M02 consumers. No new navmesh, multi-region streaming, liquids/animals or future profiles. Do not copy any unfinished S02 source.
## 4. Files to inspect
Read docs/plan/milestones/M02.md, systems/S02/S03, void-library.md and M02-P1/F1/S02-01; frozen engine/include/settlement/core/voxel_region.hpp at6d1123e, root engine/src/world.cpp assignment_path/advance, headers command_dispatcher.hpp::SessionIdentity (UUID epoch), CMake/tests. Official pinned Void/Algorithms/Graph.hpp plus tests in pinned tree, see real limits, edges, start==target early success.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/voxel_navigation.hpp; engine/src/voxel_navigation.cpp; tests/voxel_navigation_tests.cpp; CMakeLists.txt; docs/plan/systems/S03.md
First three paths are new. In CMake add only your source, test and, if needed, a link to the already enabled Void::Algorithms target.
Other people work in separate WTs; never overwrite/revert their work, never change shared Serena project. No Git/remote ops, children, edits to S02 files, existing World or M01.
## 6. Implementation or investigation approach
Represent foot at one voxel, two vertical cells clear, support directly below. 4 horizontal cardinal neighbors with level/one-step up/down, no unsupported pure flight or diagonal wall/corner clipping. Evaluate the swept body under up/down (needed headroom over raised/descending transition). Reuse S02 voxel_blocks_passage/voxel_provides_support and stamps; DoorOpen+air passable, DoorClosed blocked; soil/stone support only. A stair flight is a sequence of supported steps. Provide single-hop validation and standing check from same queries as solver, and separate API for adjacent accessible task interactions (range/line of contact cannot mine through wall/above unreachable geometric separation).
## 7. Interfaces and data contracts
NEW request/result includes region and session/incarnation from existing actual UUID type, bounded search volume/goals (deterministic ties), route/current to goal route semantics documented, cost, failure reason, sorted deduplicated consulted chunk stamps incl support/head/blocked/unavailable neighbours, and stale check via Region.matches + owner session. An unrelated edit must preserve result. Opening previously unavailable gateway invalidates negative result, same ID and numeric revisions after world reload still require new session. Distinguish invalid inputs, truly unreachable, unavailable/awaiting activation, boundary/budget and cancellation errors. Small finite known search uses Void::Algorithms::bfs or shortest_path on bounded IndexedGraphView; respect start==goal check before library fast path. For multi-goal choose canonical shortest (distance then stable coordinate and neighbor order); restrict result to reachable interaction positions. Do not allocate full coordinate extent on sparse huge region. Check vertex count, edges/step/aggregate scratch, size_t/int64 computations and bound read-set. Non-exhaustive clipping/budget must not masquerade as proven unreachable.
## 8. Dependencies and integration
Parent gives compiled S02 implementation and test registration via local merge after worktree is sealed when ready. Can compile your TUs against header first; no mock replaces genuine final evidence. Future M02 authority, persistence, frame/picking will use foot positions/goal and read stamps. Protocol11/legacy file unaffected. Local revision set #13 to be linked with its exact replacement tests in S03.
## 9. Edge cases security and performance
Include INT extremes/partial bounds/overflow, headroom at source+destination, missing vertical support in a different page, start==same blocked target, path/missing pages and time/epoch; cannot mutate captured VoxelRegion. Keep memory bounded by explicit realistic work limits; e.g. 256*32³ cells must not allocate 136MiB per worker to traverse a four-cell corridor. Check allocation failure/too many input goals gracefully. Avoid per-node heap allocations for bounded neighbor enumeration where appropriate. No hiding application bugs in arbitrary timeout/different path cost.
## 10. Acceptance criteria
1. Real S02 volume route through two-cell open door and cross-chunk stair to upper interaction; closed door/headwall/no support block and reason. 2. Remove next future support while traveler still safe, route/stamps stale, next-hop rejects; reopen, route returns; unrelated chunk change preserves validation; unavailable-to-loaded negative becomes stale; new session stale. 3. Stable exact cost/goal/tie path on small fixtures vs independent exhaustive reference + multiple worker schedules, direct same-goal invalid case. 4. Explicit bounded-limit behavior before dense allocation/partial proof, integer extremes and deterministic sorted queried stamps. 5. Real cross-build/full tests with S02 and docs issue linkage.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s03-navigation-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. After link run --tag voxel-navigation, full ctest -V and git diff --check with /tmp/stoneheart-milestones.xprJ2SVp/s03-voxel-*.log. Native Windows unavailable. Before full interactive CTest contact root to avoid simultaneous keyboard-driven smoke test.
## 12. Constraints and stop conditions
No invented S02 or Void API; if integration contract insufficient, send precise new dependency to root and continue self-contained cases. No alternate user workflow, new external tickets, or duplicate library pathfinder. Two unsuccessful same-cause attempts escalate. No remote or children.
## 13. Authorization and decisions
User requested all milestone/system coding, actual upstream library gaps and per-branch MRs. M02 architecture accepted ordinary one-cell-wide/two-tall profile, one step max; root handles publishing.
## 14. Return format
Return S03-01 READY or PARTIAL, early stable interface for M02 owner, actual code/test limits, work bounds and cross-branch evidence including cross-boundary route/invalidation and distinct failure outcomes.
Review at `7a7ff32` found a confirmed negative-result bug. On a solid, loaded z=0 floor a downward candidate may sample an unloaded z=-1 support while the known solid destination foot conclusively forbids the transition. A two-high closed wall then appears to be waiting for unrelated activation. Retain the actual sampled stamps but classify missing data as a potential frontier only if the corresponding transition, standing goal or reachable continuation cannot already be ruled out. Add the walled-floor regression and a positive genuinely unavailable frontier. Check analogous search-boundary handling and real interaction targets. Keep the existing signature and scoped files.
Independent interaction clipping finding at `17389b2`: a known blocked list of in-window contacts does not prove a global negative when additional valid interaction candidates lie outside the finite window and the reached search frontier can leave it. Reproduce in a flat 8×8×4 fixture, start (1,1,1), search upper.x=4, target stone (3,3,1), blockers (2,3,2), (3,2,2), (3,4,2) and (3,3,3). With a reachable contact at (4,3,1) the narrow search returns SearchBoundary; upper.x=6 must reach it. Preserve all prior fixed direct-goal and unknown-frontier contracts. Include cases without any traversable exit and with an unavailable exit, freeze actual before/after code and run 13 previous focused cases, new regression and full CTest under the shared GUI lock.
+50
View File
@@ -0,0 +1,50 @@
# Track real item ownership from sources through worksite and cancellation
Task ID: S06-03
Role: astra_implementer
Status: READY
## 1. Context and baseline
Exclusive s06 worktree f6493e2 has checked pickups (3c997ed), durable ProductionId, current14, S18 snapshot client. docs/plan/custody.md and root M01-F8/P5 contain binding full model. Existing World loses physical cargo on arrival at a construction site; its recipes and storage share ItemStack, and historical source leases continue until production completion. S15 peer independently captures authentic historical fixtures and implements codec.
## 2. Objective and deliverables
Implement authoritative physical ownership and bounded reservation/transfer lifecycle on every current inventory-affecting game path: grant/stock, extraction, meals, crafting, construction, return and demolition. Provide frozen in-memory data/validation contracts early for S15, raw13 representability for S16 and cancel/resume for S04. Do not publish a half-integrated version.
## 3. Scope and non-goals
Existing modeled item types/jobs/recipes only. No regions, filters/marketplace, scripts, new graphics or custom database. World and actual operation record are the source of truth. Authoritative persistent codec, command adapters/live LAN and UI are separate owned work packages.
## 4. Files to inspect
Read docs/plan/custody.md, plans S04/S06 and root F8/P5 (root and s06). Read entire world.hpp/world.cpp incl assign/step, stock/sources/idle/meal/all recipes, inventory_transaction, writer/validation in world_save.cpp, current schema2 and capture/runtime/old replay tests. F8 corrections on held old source IDs, work_remaining=0 and unsupported legacy states apply.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/include/settlement/core/inventory_transaction.hpp and engine/src/inventory_transaction.cpp; NEW engine/include/settlement/core/custody.hpp and engine/src/custody.cpp or narrow related source files for actual World operations; NEW tests/custody_tests.cpp; CMakeLists.txt limited to own implementation/tests; docs/plan/systems/S06.md
S15 exclusively owns all world_save/checkpoint/fixture changes, S04 later command dispatcher/cancel UI, S16 LAN. You may declare WorldSaveFormat::Current15 and agreed in-memory migration/validation seam in owned header. Never write other branches/Git/remote/Serena/children; other workers share filesystem.
## 6. Implementation or investigation approach
Separate recipe requirements from owned stacks. Embed one nonzero durable StackId per nonempty owner/item slot. Full move into empty retains ID; splitting allocates once; merging keeps destination ID; move matching ReservationIds and keep other source reservations. World-owned counters 0 none, MAX exhausted, plan all required IDs/counts/physical capacity/balance entries/receipt storage and allocations before effect, with nonthrow final commit. Single physical count per storage/resident/ProductionId input; caches exclusively updated/rebuilt from claims. Restore snapshot copies without stale pointers. Source/sink tracking Opening+Grant+Harvest+RecipeOutput equals live+RecipeInput+Meal+Installation+StorageDemolition. Use Void::Numeric and existing #7/#8, avoid O(N²) global scans in hot step. Preserve real original source and timing/game decisions in normal v13 trajectories.
## 7. Interfaces and data contracts
AgentId+positive durable next_admission (starts 1) keys admission; distinct tagged key namespace from TransferId+ordinal. On admission record exact request and issued transfer and increment next_admission together; pre-admission refusal unchanged. Persistent next available IDs avoid reuse; active single execution per worker. 4096 global receipts in commit order, each canonical typed input and outcome <=1024 bytes each, no opaque hash-only comparison or arbitrary route payloads. Normalized source/material lines max actual recipe units (cabin five positive units across different storages), bounded stock kinds, typed data. Retained duplicate same bytes gets exact result, conflict distinct payload, evicted old sequence Stale, future unissued rejected. Retired receipt references may identify no-longer-live objects but must be in issued ranges. Prefer compact immutable shared payloads/COW for retained snapshots; account memory/time at full retention.
## 8. Dependencies and integration
Reservations distinct for exact item+owner, output capacity, worksite, harvest/tending. Input-backed output slot links the actual ReservationId in the same store; never counted or backed twice. Preserve old origin-storage lease until work finishes for Move/Demolish Busy. Worksite arrival moves real goods into order input, consumed only at stage completion. Research genuine existing guarantees and send actual frozen declarations immediately to root, including explicit entries/interfaces for S15 legacy migration, strict modern full validation and pure legacy representability. S04 needs World::cancel_production(ProductionId) and World::resume_production(ProductionId) or equivalent typed result. S16 needs pure preflight that correctly recognizes ALL unsupported modern states incl single canceled plank/stone-block, absent destination, partial mixed return and suspended site.
## 9. Edge cases security and performance
On cancel pre-pickup release claims; in-transit/at-site cargo remains with same transfer/worker until all types actually deposited, with meaningful blocked reason and persistent no-destination status. Partial return exact, do not allow meals/rest/new jobs while carrying. Canceled staged bed after prior installation or already built recurring loom remains suspended under same ID/occupancy; explicit resume continues retained phase without duplicated inputs. Installed/completed final objects refuse cancel. Historical demolish/move occupied semantics continue. Completion with zero remaining and temporary refusal is a valid modern pending phase; never unsigned-decrement 0 on retry, new ordinal on actual retry; reject legacy projection if not exact. Before destroying stock record exact reason/qty and preflight replenishment production IDs as in S04.
## 10. Acceptance criteria
1. Live single ownership and conservation for all current paths including partial splits/merge, last item, storage disappearance and worksite delivery before consumption; exact conditional refusals and repeat/eviction/conflict. 2. Cancel/return at each stage incl full/no storage and suspended partial bed/installed loom resume; actual normal World operations. 3. Snapshot immutability and deterministic serial/2/6/12, old raw13 corpora remain exact. 4. Tests for zero/MAX/overflow, duplicate/cross-owner and exhaustion, last active worker and terminal failure. 5. Frozen schema integration passes with S15 before public delivery; provide measured 500 resident, ~10K stack/2K order and full/empty 4096 receipt state costs where technically applicable.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focused new custody tag and CTest -V; both existing byte regression probes in temp dir; S15 tests/migration validation added after interface merge. Capture p50/p95/size and actual benchmark workload/environment (5ms p95 initial Wine capture budget, disclose measured values). Use s06-custody-* logs. Keep fixtures and user saves private/isolated.
## 12. Constraints and stop conditions
Send concrete C++ data declarations/API seam before broad implementation so S15 can progress; do not generate or edit schema15 on disk yourself. Preserve public Inventory/Storage read-facing APIs and existing behavior relied on by old tests. Never ship/claim completion until integrated codec and cancellation boundaries; alert parent on needed scope/ownership or two failed same-cause attempts. No children/Git/remote.
## 13. Authorization and decisions
User authorizes complete roadmap. Root accepts compact bounded retention, embedded single-owner stacks and verified F8 corrections; normal multi-stage behavior and legacy bytes remain mandatory. Root integrates and publishes only fully verified compatible state.
## 14. Return format
After local candidate `4f4c038`, S15 observed that a retained admission can be authenticated with repeated reservation IDs, even though the allocator always issues distinct increasing IDs. Inspect canonical emitters and reject repeated issued reservation IDs or demonstrably duplicate identical effect rows, including after the referenced actor/stack has retired. S15 adds authentic malformed fixtures in its own files. Verify genuine consumed-through-zero and valid split/merge results continue to pass. Use the same exclusive scope, tests, and Gitea restrictions.
Return S06-03 status, frozen seam early, actual source/operations/remaining integrations, tests/goldens/perf logs. Clearly identify original old boundary vs actual strengthened ownership and any native limitations.
+48
View File
@@ -0,0 +1,48 @@
# Migrate historical cargo and persist modern custody atomically
Task ID: S15-04
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated s15 worktree f6493e2. Stable read-only historical checkout /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 at same ref, old Windows build available. Current published checkpoint schema2/body14, schema1/body1–13. S06-03 under construction in sibling s06 exclusively owns World types/normal transitions, will supply concrete data declarations via parent. Source-grounded M01-P5/F8, docs/plan/custody.md include full decisions.
## 2. Objective and deliverables
Capture genuine old schema2/raw14 fixtures now, then implement canonical raw15/checkpoint3 encoding, strict validation, bounded migration of prior genuine worlds and before-output typed rejection of unrepresentable raw13 states. Complete end-to-end after root integrates S06 schema declarations into this worktree.
## 3. Scope and non-goals
Persistence/codecs and validated restored state only. No World gameplay changes, command dispatcher, UI, net or new dependency. Data snapshots/custody/command semantics remain owned by sibling S06/S04. Do not invent temporary independent schema if peer interface pending; use that interval for golden collection and historical phase audit.
## 4. Files to inspect
Read root/S06 docs plan/custody, M01-F8, old world_save.cpp full validator and historical fields, checkpoint.hpp/.cpp, checkpoint_files.cpp, world.hpp current14, new custody declarations when supplied, existing tests/checkpoint*, identity/production_identity/replay/snapshot/quantity, pinned Binary budgets and hash. Fixtures old source and golden corpus/probe helpers in /tmp/stoneheart-milestones.xprJ2SVp. S15-03 already version/size-safe reader/write service.
## 5. Write ownership and coordination
Write scope: engine/src/world_save.cpp; optional NEW engine/src/custody_save.cpp/internal header for supported codec; engine/include/settlement/core/checkpoint.hpp; engine/src/checkpoint.cpp; engine/src/checkpoint_files.cpp only as genuinely required; tests/checkpoint_tests.cpp/tests/checkpoint_file_tests.cpp/tests/snapshot_tests.cpp only for schema/current snapshot checks; NEW tests/custody_migration_tests.cpp and concise frozen fixture data if needed; CMakeLists.txt limited to registering owned codec/test sources; docs/plan/systems/S15.md
Do not change world.hpp/world.cpp (S06 owner), dispatcher or LAN/app. Other agents work in sibling checkouts; never revert their work. Root will integrate S06 headers when ready. No Git/remote/children or shared Serena switch.
## 6. Implementation or investigation approach
First capture authentic schema2/raw14 from old binary before peer edits. Include fixed seed/UUID, actual legacy Working worksite after pickup, between stops/hauled product, normal/direct order, staged simple as applicable. Preserve original bytes or minimal readable hex fixture + provenance+SHA and exercise actual decode; do not generate expected old bytes using new writer. Parse/check input under historical schema first; preserve true unused/complete routes. For versions before 5 preserve sleep normalization, versions1–8 historical footer/different fields. Old Working delivery order with stops cleared/no resident material reconstructs exactly validated input at ProductionId; direct SawPlank/CutStoneBlock/WeaveCloth inputs stay in storage; post-carpentry output belongs to resident, no active production link. Meal and tending phases distinct. Allocate migrated IDs deterministically by owner kind/ID/item, active execution by AgentId. Opening balance computed only after implicit site stock reconstructed. Migrated active admission generation1,next2, no fabricated receipt, inactive next1.
## 7. Interfaces and data contracts
Explicit schema table 1→body1..13, 2→14, 3→15 with digest before decoding, no version-constant-only dropping v2. Strict authenticated body15 data includes all counters/IDs, owner stacks incl site, live execution+claims/capacity backing and source leases, saved phase/pending completion/suspended partials, opening/source/sink totals, exact canonical creation+ordinal receipt ring incl bounds/retired refs. Enforce sorted unique live identities, ID nonzero/less-than valid highwater, one owner, references/counts/claim capacity and valid reservations; historical receipts may name retired IDs below issued highwater, never demand liveness of those refs. Reject modern missing/inconsistent states; no rematerializing missing modern data. Original current14 vs Legacy13 outputs must remain available as defined. Use shared S06 pure validation/projection method where feasible; avoid duplicate simulation/codec rules.
## 8. Dependencies and integration
Raw13 projection performs complete legacy representability check BEFORE first externally written byte incl single Plank/StoneBlock canceled orderless haul, mixed cargo, missing dropoff, suspended residual bed/loom, zero-completion pending or other modern combinations. Signal typed UnsupportedLegacyState from agreed core type for S16. Preserve valid historical reserved counts/source storage leases, stops and route metadata, actual frozen old byte corpora exact. Modern persistent codec must save unsupported-on-LAN states safely. Parent handles per-worktree header merge; report exact needed seam early. Avoid a 128MiB scratch copy just to detect unsupported states when pure preflight suffices.
## 9. Edge cases security and performance
Strict 128 MiB body/existing size limits/1M collection caps and exact 4096 receipts, <=1024 bytes each request/result, checked iteration/preallocation budget/count arithmetic before allocation. No hash-only conflict comparison. Tests fully authenticated malformed data for wrong outer/body pair, duplicates and mismatched counters/balances, dangling live vs valid historical refs, embedded wrong epoch, exhausted IDs, canonical order. Preserve existing file/owner transaction semantics and background service. Avoid O(N²) owner/claim lookups and full defensive copies in hot paths.
## 10. Acceptance criteria
1. Tests load authentic old fixtures (old1–14 layout as supported) at real phases then continue to same economic/gameplay outcome, including original current14. 2. Canonical full modern equality over save/load mid transfers/suspension/return and replay, retained snapshots include new state. 3. Host-facing raw13 rejected states write zero bytes while normal golden projections match. 4. Every malformed candidate rejected without affecting active world/data. 5. All cross-branch integration, Wine CTest and focused migration tests; native caveat.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s15-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. For historical capture use immutable /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14 headers/source and matching prechange runtime library; save evidence/probe/hash under /tmp, freeze meaningful fixtures in tests where necessary. Later CTest -V/targeted custody migration/current/old golden probes and git diff --check; s15-custody-* logs.
## 12. Constraints and stop conditions
If core declarations are not frozen, deliver authentic fixtures and precise needed interfaces now; do not guess incompatible wire layout or edit S06 files. Root coordinates compile/integration. No standalone incomplete publication. After two failed same-cause fixes escalate with evidence.
## 13. Authorization and decisions
User authorizes full roadmap, file compatibility and Gitea milestones. Root accepts 1–3 outer + 1–15 body migration and all F8 constraints. Server/client adverse input validation is defensive, with no external communication. Root owns all public actions.
## 14. Return format
Return S15-04 progress including authentic prechange fixture SHA early, actual agreed storage schema/constraints, changed paths/tests/golden behaviors; mark native/combined gates explicitly.
-48
View File
@@ -1,48 +0,0 @@
# Prepare immutable client frames and present camera changes independently
Task ID: S17-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated system/s17-rendering at 66af7c5 includes reviewed S18-01 client. app/viewer_win32.cpp has a 60 ms session/network timer, parent+child paints retain an old pointer but still dereference changing globals and SceneView spans live blueprint vectors. D3DScene::render presently regenerates flat geometry even on camera-only paints. S18-02 alters title/host gates and bed text in another worktree. M01-P6/F9 advise independent dirty-only 16ms frame sampling and strict install boundary.
## 2. Objective and deliverables
Implement S17-W01 normal Windows entry: scene and HUD consume one immutable prepared client packet including owned overlays, camera and pinned snapshot; camera frames can render while 20 Hz world step or file/load busy. Coalesce invalidation and reuse geometry on view-only changes.
## 3. Scope and non-goals
Existing flat game map, hardware Direct3D/WARP and error HUD only. No M02 chunk meshes, new camera settings, render thread, input/protocol changes or 60fps hardware claim. Preserve current viewer/rooms/blueprints/colony UX and all baseline harnesses.
## 4. Files to inspect
Inspect app/viewer_win32.cpp scene_window and main WndProc, WM_TIMER/PAINT/DESTROY, camera wheel/drags, pump_session, draft/room render, title/minimize/resize, D3DScene in app/d3d_scene_win32.hpp/.cpp, map_camera, actual /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. CMake/tests WARP/capture availability, app/viewer_session member changing_world/poll_changes.
## 5. Write ownership and coordination
Write scope: app/viewer_win32.cpp (drawing, camera invalidation, timer/pump sequencing only); app/d3d_scene_win32.{hpp,cpp}; NEW app/viewer_frame.hpp/.cpp if useful; NEW tests/viewer_frame_smoke.cpp; CMakeLists.txt limited to registering frame test/owned sources; docs/plan/systems/S17.md
Other branches own title/profile and stock; do not revert others' changes or switch Serena. Exclusive isolated s17 checkout. No Git/remote operations, further agents or unrelated app changes.
## 6. Implementation or investigation approach
Prepare owned immutable presentation data on UI thread, derive HUD/selection/cursor/room validity and existing geometry from exactly one accepted world and copied relevant overlay state. Avoid borrowed spans into mutable UI across nested WM_PAINT or an overwritten single scratch buffer. Main and child paint each pin packet locally; no global world deref to render. Frame timer and camera/window invalidation independently drive dirty visible frames; keep existing 60ms LAN/control pump. While session->changing_world() keep prior presented world/frame including null, even if runtime.latest has already installed newer; release new world only after pump consumes Replaced, resets overlays/camera and updates identity. Guest/epoch transitions likewise cannot mix old work and new overlays. Sample ordinary healthy revisions with stable client identity.
## 7. Interfaces and data contracts
Keep one current flat geometry version keyed by world identity/snapshot and all overlay/selected/cursor/BuildingView inputs. Camera-only or size-only change regenerates only camera/projection constants; account for resize/device/backend reset invalidating GPU upload. Explicit immutable geometry ownership shared by packets retained by readers; stale packets can render consistently even after newer packet then reuse correct upload. No work on hidden/title/minimized/zero sizes. On restoration or failed/recreated backend request fresh frame. No busy loop or full mesh rebuild/upload for unchanged view. Preserve existing D3DScene::render callers or update only within ownership. RAII for paint/DC and timers/shutdown.
## 8. Dependencies and integration
Integration root will merge separately from S18 title+host. Avoid code dependencies on S06 custody changes, S21 hooks. Reuse Void owner snapshot (#5) and current D3D facilities; GPU resource ownership remains in renderer. Do not copy fixture include paths from other worktrees into repo. There is no GDI world renderer to invent in this scope.
## 9. Edge cases security and performance
Check nested dialog/WM_PAINT while replacements happen, applied room/draft vector lifetime, same-world rollback or new UUID taking same tick, mouse cursor remains coherent re camera zoom and changes may legitimately affect preview geometry, no blocked owner/file calls on presentation thread. Render failure presents current HUD error and recoverable state. Graphics-test availability must be explicit, tests need bounded cleanup and skip/report only genuine backend unavailability.
## 10. Acceptance criteria
1. Durable actual regression target (repo-relative source paths) observes fresh render and actual input camera/zoom/drag while owner worker and file writer blocked; original tick/canonical snapshot preserved. 2. Frame timer alone advances camera frame without event timer. 3. Held old packet remains renderable with old overlays across nested install; new packet resets correctly; exact saved snapshot content. 4. Geometry/upload reuse on pure camera/unchanged, title/hide/minimize/0-size/restore/destruct, device reset semantics; WARP/offscreen capture/real UI as available. 5. All original UI, core and LAN checks still pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-frame-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. CTest -V, git diff --check; source actual Wine GUI/D3D environment from env.sh. Add/verify focused new real frame smoke and existing UI regressions (three-process/temp harness with isolated LOCALAPPDATA, no user data). Use s17-frame-* logs and report observed device/driver.
## 12. Constraints and stop conditions
Stop if independent-frame scheduling would require replacing app/renderer architecture or mutating unrelated title/guest controls. Ask root on genuine scope change; after two failed same-cause fixes escalate with evidence. No M02 feature additions, Git/remote or children.
## 13. Authorization and decisions
User authorizes complete roadmap on system/milestone branches. Root approved independent dirty-only 16ms sampling, immutable packet, one flat geometry generation and no unsourced performance claims. F9 requires explicit pre-Replaced candidate fence.
## 14. Return format
Return S17-01 READY or PARTIAL, actual owned changes/normal paths, packet/geometry lifetime, render/repaint file/worker evidence, exact logs/native limits. Send frozen smoke seam early.
+50
View File
@@ -0,0 +1,50 @@
# Compare authoritative custody state in journal and runtime replay
Task ID: S21-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
S21 sibling at 3c7cc3c merges approved replay ef980af with provisional live World/codec 539cea0, later partner fixes will be included. tests/replay_diagnostics.hpp canonical and tests/replay_tests.cpp saved_state still choose Current14, tests/runtime_tests.cpp bytes currently defaults to Legacy13. Both projections drop custody15. S15 owns tests/snapshot_tests.cpp. Released S21 real opposite-order tests and prior hashes must still pass.
## 2. Objective and deliverables
Use current complete raw15 state for replay/owner snapshots and identify divergent item owner, stack/reservation/transfer/receipt/balance when those facts change. Exercise retained cancel/retry and continuation on 1/2/6/12. Keep intentional legacy13/14 compatibility fixtures and golden outputs as separate existing coverage.
## 3. Scope and non-goals
Only test replay/diagnostics and their S21 explanation. No changes to application World, protocol/codec, CMake unless unavoidable for existing registered suites, generator/M02 or unrelated tests. This is a contracted validation extension of S21-01 (M01-F8/F9).
## 4. Files to inspect
Inspect tests/replay_tests.cpp, replay_diagnostics.hpp, runtime_tests.cpp, tests/custody_tests.cpp and custody_migration_tests.cpp, engine/include/settlement/core/{world,custody,simulation_runtime}.hpp, custody.cpp, world_save.cpp, S06-03/S15-04/docs/plan/custody.md and S21. Read surrounding domain projections and fallback.
## 5. Write ownership and coordination
Write scope: tests/replay_tests.cpp; tests/replay_diagnostics.hpp; tests/runtime_tests.cpp; docs/plan/systems/S21.md
Isolated s21 only. You share checkout state with others in separate working directories; do not revert others or change other WTs/branches, shared Serena or any Git/Gitea state. Parent handles schema source seals.
## 6. Implementation or investigation approach
Centralize canonical save selection in the test helper to Current15 and apply it to current replay & runtime owner world equality paths, preserving any explicit legacy compatibility expectations. Extend first-difference report from real public immutable facts with stable entity/owner IDs: resident/storage/order input stack quantities/IDs, execution and active claims, admission/operation receipt keys and result outcome, material balance. Compare canonical bytes first and retain unknown/opaque byte fallback. Organize human-readable distinctions so stock change still reports stock, before a secondary balance if relevant. Do not construct huge diagnostic maps on equality.
## 7. Interfaces and data contracts
Consume Inventory::stack_id, Agent.execution and next_admission, ProductionOrder.input and suspended, World::item_balances(), custody_receipts() and public receipt/request/result. A public vector is a ring backing store; use key and true order only when authoritative, avoid exposing physical ring layout as game identity. No modifying private counters nor pointers into mutable shared data for assertions. Use a valid game action/migrated world with same historical projection but differing modern owner/receipts if possible (old projected world loaded vs originating modern).
## 8. Dependencies and integration
Real source base includes custody and codec; parent will furnish final stricter validation and zero-count terminal semantics as local commits. S06 owns normal domain fixtures S15 authenticated raw15/history; S21 owns comparison and divergent-entity diagnostics, runtime stale/reload, not another codec test. External library support references existing issue #15 real execution, #7 ids/#8 transfer only if relevant. No request creation.
## 9. Edge cases security and performance
Only derive proof from real accepted actions with invariant-valid states. Catch first divergence when original legacy projection matches despite changed durable facts; do not falsely flag a different ring backing index as a logical change. Preserve old positive-negative receipt/stale owner and reproducible opposing completion trace. Keep replay test runtime bounded (first compare bytes and build facts on mismatch only). Notify root early of genuine production defects.
## 10. Acceptance criteria
1. Current canonical captures include all custody state on real replay and after load; regression makes prior projection blind yet new one finds named entity/step. 2. Existing identity/stock/job/context and byte fallback still work. 3. Continue canceled in-flight durable cargo through checkpoint on serial/2/6/12, retained replay/conflict without physical duplicate. 4. Root can integrate while all registered tests, 24 actual completion traces and historical golden checks remain intact.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focus --tag replay and --tag runtime after build, full CTest -V, named /tmp/stoneheart-milestones.xprJ2SVp/s21-custody-*.log and git diff --check. Authentic raw13 corpora old-trajectory.bin + identity-compat-old.bin independently validated by S06; compare if behavior or underlying partner revisions change.
## 12. Constraints and stop conditions
No application edits, publishing, shared source checkout switch, new helper API into World or script internals just for diagnostics. If blocked by partner fix, obtain it through root while implementing independent diagnostics; report exact evidence. Review independent via root.
## 13. Authorization and decisions
Approved milestone/system work plus explicit exact-state replay and ID diagnostics from M01. Root keeps transient cross-branch commits local pending package acceptance.
## 14. Return format
Return S21-02 READY or PARTIAL with real base, owned diff, command results, source domain/id and regression observations, test runtime and external dependencies.
Worktree now at `e26b9c2` includes the stricter S06 validator and S15 zero-count terminal effects, count budgets and authentic migration/ring tests from `ccd50ec`. Begin on this combined source.
-12
View File
@@ -22,18 +22,6 @@
## Проверки и выход
### Контракты первой реализации
Воксели имеют знаковые 32-битные координаты, высота растёт по оси `z`. Границы конечного региона задаются полуинтервалами с 64-битными концами, чтобы в них можно было включить последний положительный воксель. Чанк содержит 32³ ячеек; быстрее всего меняется индекс `x`. Отдельные результаты чтения обозначают воздух, недоступный чанк и координату за пределами региона. Генератор получает версию, seed и абсолютные координаты. Порядок подготовки страниц не влияет на материал.
Снимок региона разделяет неизменяемые страницы. Операция проверяет все ожидаемые ревизии, размер и бюджет до публикации. Пустая операция или запись прежнего материала сохраняет ревизию после проверки ожиданий. Дублированная координата отклоняет весь запрос. Изменение на грани оповещает соседний чанк, сохраняя его собственную ревизию материала. Реализация и проверки замены библиотечным API связаны с задачами о [знаковых координатах](https://git.faumaray.com/Void/Library/issues/11), [транзакциях страниц](https://git.faumaray.com/Void/Library/issues/14) и [зависимостях по ревизиям](https://git.faumaray.com/Void/Library/issues/13).
Житель занимает одну клетку в плане и две по высоте, поднимается на одну ступень. Поиск учитывает опору, свободное место для головы, дверь и соседние чанки, включая чтения, из-за которых путь не найден. Перед очередным перемещением житель перепроверяет переход. Удаление следующей ступени сохраняет его собственную позицию, груз и цель. Поиск через ещё не подготовленный чанк либо за пределами бюджета имеет отдельный результат.
Добыча создаёт авторитетный заказ с доступной соседней рабочей позицией. При завершении мир заранее проверяет правку и возможность зачислить материал по правилам S06. Удаление грунта и передача добычи выполняются одной операцией. Если для добычи нет места, заказ ждёт с указанием причины. Повтор принятой команды находит исходный заказ. Режим тестовой колонии имеет собственный манифест с версией генератора и определениями материалов.
Координатор принимает подготовленные чанки на назначенной границе такта в порядке координат. Во время ожидания он обслуживает загрузку и завершение программы. В сохранение попадают требуемые чанки, назначения работ и безопасная позиция после правки. Прежние колонии сохраняют прежнюю геометрию на высоте ноль. Форматы нового региона согласуются с подтверждённой версией сохранений M01. Текущий шейдер уже проецирует высоту `z`; луч выбора и видимый срез должны пользоваться той же проекцией. [Проектирование](../../agent-workflow/tasks/M02-P1.md) · [Проверка контрактов](../../agent-workflow/tasks/M02-F1.md)
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
-28
View File
@@ -10,34 +10,6 @@
## Данные и ответственность
### Исполняемая основа ограниченного региона
`VoxelRegion` хранит ненулевой ID, seed, версию генератора и границы. Ячейки имеют знаковые координаты `int32`, а концы полуинтервалов используют `int64`, включая верхнюю границу `INT32_MAX + 1`. Деление на размер чанка округляет вниз, поэтому координата −1 попадает в чанк −1 и локальную ячейку 31. Индекс внутри страницы вычисляется как `x + 32 * (y + 32 * z)`. Результат `sample()` различает загруженный воздух, недоступную страницу и выход за границы. [Публичный контракт](../../../engine/include/settlement/core/voxel_region.hpp) · [Реализация](../../../engine/src/voxel_region.cpp)
Копия региона разделяет каталог и страницы через неизменяемые объекты. `directory()` возвращает владеющую ссылку на прежний каталог. Изменение создаёт новый каталог и копирует затронутые страницы. Срок жизни снимка охватывает все его материалы. Номер региона и `ChunkStamp` связывают чтение с состоянием доступности и ревизией страницы. Владелец мира дополнительно проверяет инкарнацию сеанса при загрузке партии.
`prepare_generated()` независимо готовит страницу генератора 1. Он кодирует seed, версию и координаты опорных столбцов в little-endian через `Void::Binary::Writer`, затем использует FNV-1a из `Void::Hash`. Интерполяция сетки с шагом 16 даёт высоты от −8 до 8. Верхние три слоя состоят из почвы, нижние — из камня. Соседние столбцы по горизонтальной оси отличаются по высоте максимум на одну ячейку. Область вне частичного чанка заполнена воздухом. Для seed 42 чанк (−1, −1, −1) имеет FNV-1a `13302332479434111011`; этот результат отдельно воспроизведён по закодированным полям. Подготовка не меняет каталог региона.
`prepare_restored()` проверяет полный размер страницы, ненулевую ревизию, материалы и воздух за границами, затем копирует данные вызывающего кода. `activate()` принимает весь набор подготовленных страниц одной операцией. Она проверяет точный дескриптор региона, дубликаты, бюджет и отсутствие уже опубликованной страницы. `edit()` проверяет ожидаемую ревизию каждой ячейки, даже если материал уже совпадает. Повтор координаты отклоняет весь запрос. Пустая и тождественная запись сохраняют ревизии. Исчерпанная ревизия запрещает изменение страницы. Все новые страницы, каталог и результат готовятся до публикации. При отказе прежние указатели, материалы и ревизии сохраняются.
Список изменённых чанков упорядочен по координатам `x,y,z`; список ячеек — по мировым координатам. Правка на грани добавляет пересекающего регион соседа в `dirty_chunks`. Это касается и недоступных соседей. Диагонали не включаются. Неизменившийся сосед сохраняет свою ревизию материала. Активация страницы оповещает все её соседние грани. Выгрузка страниц появится с отдельным контрактом сохранения их ревизий.
| Материал | Значение | Проход | Опора |
| --- | --- | --- | --- |
| Воздух | 0 | Свободен | Нет |
| Почва | 1 | Занят | Есть |
| Камень | 2 | Занят | Есть |
| Закрытая дверь | 3 | Занят | Нет |
| Открытая дверь | 4 | Свободен | Нет |
Навигация и изображение используют общие `voxel_blocks_passage()` и `voxel_provides_support()`. Генератор создаёт природные материалы. Игровая команда определяет право изменить дверь и обновляет обе её ячейки одной операцией, в том числе через границу страниц.
По умолчанию разрешены 256 страниц и 4096 ячеек в запросе. Лимиты полезных данных резидентного региона и одной транзакции равны 16 МиБ каждый. Проверяемая арифметика учитывает объекты страниц, каталог, сортируемый запрос, временную страницу и массивы результата до их выделения. На проверенной Windows x64-сборке страница занимает 32 776 байтов, запись каталога — 32 байта, каталог с 256 страницами — 8 398 872 байта. Служебные данные распределителя, подготовленные страницы и старые снимки, удерживаемые потребителями, имеют отдельный расход памяти. Будущий владелец ограничивает число таких потребителей.
Проверки `--tag voxel-region` покрывают отрицательные и предельные координаты, частичные страницы, порядок завершения настоящих задач на 2/6/12 исполнителях, границы двери, загрузку, точный отказ целого набора и неизменяемые снимки. На заполненном каталоге правка одной ячейки сохранила прежние 255 страниц. Отдельная программа по очереди вызвала отказ каждого выделения памяти при генерации, восстановлении, активации и правке двух страниц; все отказы сохранили прежний каталог. Переход на библиотечную реализацию должен повторить эти проверки. [Тесты региона](../../../tests/voxel_region_tests.cpp) · [Знаковая арифметика в VoidLibrary](https://git.faumaray.com/Void/Library/issues/11) · [Атомарные страницы в VoidLibrary](https://git.faumaray.com/Void/Library/issues/14)
Windows x64 Release с GCC 16.2 под Wine 11 прошла 14 проверок региона и весь CTest — 155 тестов ядра, 9 LAN, 14 клиента и испытание кадра с видимым D3D11 и WARP. В одном прогоне подготовка и активация 256 страниц заняли 57 917 мкс, правка одной ячейки — 11 мкс. Это измерение относится к данному прогону под Wine. Нативная Windows и аппаратная частота кадров ещё не проверены.
| Новый контракт | Содержимое и владелец |
| --- | --- |
| Позиция мира | Постоянный ID региона и знаковые целочисленные координаты вокселя. Вертикальная ось — `z`, горизонтальная плоскость — `x,y`. |
-28
View File
@@ -8,34 +8,6 @@
В прототипе есть A*, фиксированный порядок соседей и кэш запросов. Изменение проходимости инвалидирует маршруты. Тесты проверяют проход через отверстие в стене и открытие ранее недоступной шахты. Карта использует двумерную позицию, а маршрут хранится последовательностью клеток внутри жителя. [Мир](../../../engine/src/world.cpp) · [Типы](../../../engine/include/settlement/core/world.hpp) · [Тесты маршрутов](../../../tests/core_tests.cpp)
## Первый исполняемый срез M02
Модуль `voxel_navigation` работает с неизменяемым `VoxelRegion`. `voxel_standing` проверяет опору, клетку ног и клетку головы. `voxel_transition` использует те же проверки для одного горизонтального перехода с подъёмом или спуском на одну клетку. При изменении высоты дополнительно проверяется объём, через который проходит голова. Закрытая дверь препятствует движению, открытая дверь допускает проход. Земля и камень предоставляют опору. [Интерфейс](../../../engine/include/settlement/core/voxel_navigation.hpp) · [Реализация](../../../engine/src/voxel_navigation.cpp)
`find_voxel_path` получает ID региона, UUID текущей инкарнации, старт, множество целей и явное окно поиска. Путь содержит очередные позиции после старта. Его стоимость равна числу переходов. При равной стоимости выбирается первая цель в порядке координат, соседи каждой позиции перечисляются в том же порядке. Поиск использует `Void::Algorithms::bfs` из закреплённой версии библиотеки. Множество вершин относится к заданному окну, список соседей вычисляется по запросу. До выделения массивов проверяется полный размер окна. Разреженный регион с большой протяжённостью требует меньшего окна для конкретной задачи.
`find_voxel_interaction_path` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием.
Позиции контакта за пределами окна поиска сохраняются для проверки отрицательного ответа. Если такой контакт допускает размещение жителя, достигнутый допустимый выход из окна даёт `SearchBoundary`, а достигнутый неопределённый переход требует загрузки данных. При известном отсутствии выхода результат остаётся `Unreachable`. Заблокированные контакты внутри окна не доказывают недоступность всех внешних позиций. Общий предел целей учитывает и пропущенные контакты.
Каждый ответ содержит `VoxelReadSet` с ID региона, инкарнацией и упорядоченными уникальными ревизиями прочитанных чанков. В набор входят опора, свободное место над головой, заблокированные соседи и недоступные страницы. `current` проверяет тот же сеанс и все эти ревизии. Загрузка недоступной страницы делает прежний отрицательный ответ устаревшим. Правка непрочитанного чанка сохраняет ответ пригодным. Сам ответ и его маршрут удерживают собственные данные. Для замены локального набора библиотечным повторить проверки опоры через границу чанка, открытия прохода, загрузки страницы и смены инкарнации. [Void/Library #13](https://git.faumaray.com/Void/Library/issues/13)
Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений.
Недостающие данные требуют ожидания, когда они могут продолжить путь из уже достигнутой позиции. Известная сплошная стена или занятая клетка ног окончательно запрещает переход, даже если его проверка прочитала недоступную опору. Прочитанные ревизии сохраняются в ответе. Недоступная цель за доказанно непроходимой стеной сама по себе не создаёт достижимый проход. Выход за окно учитывается после проверки допустимого перехода через его границу.
Пределы по умолчанию составляют 65 536 вершин, 1 000 000 шагов алгоритма, 4 000 000 чтений клеток, 64 цели, 4096 ревизий и 8 МиБ рабочих данных. Бюджет учитывает четыре массива `size_t` и посещённость из Void BFS, собираемый маршрут и зарезервированный набор ревизий. Список соседей из 12 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками.
Ёмкости проверяются также против `vector::max_size()`. Непредставимая ёмкость возвращает `LimitExceeded` через каждую из четырёх публичных операций. Проверка с `max_dependencies = max_size() + 1` и максимальным байтовым бюджетом воспроизводит этот отказ без выделения указанной памяти.
Селектор `--tag voxel-navigation` проверяет двухклеточную дверь, ступени на границе `x=31/32` и работу наверху, удаление следующей опоры, прежний неизменяемый снимок, место для головы, недоступную опору через отрицательную границу по высоте, постороннюю правку, смену сеанса и предельные координаты. Стоимости сравниваются с независимым полным обходом 16 малых плоских карт. Запросы в настоящем пуле с 2, 6 и 12 потоками дают те же маршруты и ревизии. [Проверки](../../../tests/voxel_navigation_tests.cpp)
На совместной базе S02 `e7046a9` сборка Windows x64 GCC 16.2 и все десять проверок навигации прошли под Wine 11. Полный `ctest -V` прошёл четыре набора с 165 случаями ядра, 9 LAN, 14 клиента и испытанием кадра с видимой цепочкой D3D11 и WARP. Проверка заняла 4,66 с. Нативная Windows и связь навигации с исполнением работ в `World` проверяются при последующей интеграции M02.
Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся.
Проверка замечания к `17389b2` воспроизвела ложную недоступность при единственном пригодном контакте за границей окна. После исправления узкое окно возвращает `SearchBoundary`, расширенное достигает той же позиции контакта. Изолированный старт и незагруженный проход проверены отдельно. Под Wine прошли 14 проверок навигации и полный `ctest -V` с блокировкой общего интерактивного окружения. Все четыре набора прошли, включая 169 случаев ядра, 9 LAN, 14 клиента и испытание кадра за 4,74 с.
## Пространственная модель
Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками.
+23
View File
@@ -84,3 +84,26 @@ S06 владеет фактическими количествами, содер
- Разделить и снова объединить стек с активным резервом. Количество и свойства сохраняются, ссылка остаётся разрешимой.
- Повторить подтверждение торговли и прибытия в регион. История содержит одну завершённую операцию.
- На контрольных 10 000 стеках и 2 000 работах измерить поиск поставщика, стоимость операций и объём сохранения через [S21](S21.md). Варианты предметов и логистики связать с [реестром паритета](../parity.md).
## Срез S06-03: владение грузом и восстановление исполнения
Кандидат M01 хранит единственное количество у склада, жителя либо входного запаса `ProductionId`. `StackId` встроен в эту запись; требования рецепта используют отдельный `ItemAmount`. Получение целого стека в пустой слот сохраняет ID, разделение выдаёт ID новой части, объединение сохраняет ID получателя. Вместе с количеством меняются ссылки резервов; исторический исходный склад остаётся в материалах заказа до завершения. [Типы](../../../engine/include/settlement/core/custody.hpp) · [Реальные операции мира](../../../engine/src/custody.cpp)
Обычные начисления, добыча, все существующие рецепты, монтаж, еда и разбор склада учитывают источники и расходы. На стройке материалы действительно принадлежат входу заказа до завершения стадии. Перед изменением количества готовятся ограниченные копии затронутых владельцев, арифметика, ID и место для квитанции; после проверки выполняется не бросающий commit. Используются `Void::Numeric` закреплённого `7b0fea6`; локальные счётчики и условные операции связаны с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Условие замены — повторить проверки исчерпания, целого/частичного переноса, последней единицы, отмены и продолжения после загрузки на Windows x64.
Назначение использует ключ `(AgentId, next_admission)`, дальнейший шаг — отдельное пространство `(TransferId, next_operation)`. Планировщик выдаёт ключ и применяет операцию; `custody_request` восстанавливает результат уже выданного запроса и отказывает неизвестному будущему ключу. Сохраняются последние 4096 квитанций в порядке применения с точными типизированными полями, результатами и выданными ID. Снимки разделяют только неизменяемые объекты квитанций; массив указателей и остальные данные копируются. Длина материалов ограничена пятью реальными единицами крупнейшего рецепта, включая пять разных складов. Этот локальный повтор также связан с [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6).
`cancel_production` освобождает неполученные резервы, возвращает вход площадки жителю и удерживает исполнителя в `Returning` до сдачи всех видов груза. Частичная сдача и отсутствие свободного склада не уничтожают остаток. Уже смонтированное основание кровати или существующий ткацкий станок сохраняют ID и приостанавливаются; `resume_production` продолжает оставшуюся стадию. Завершённые конечные объекты не отменяются. При отказе завершения нулевой таймер остаётся нулевым; следующая проверка получает новый номер операции. `legacy_representable` не изменяет мир и запрещает экспорт несовместимых фаз до записи первого байта. Сериализацию Current15, миграцию старых тел и контрольную точку схемы 3 реализует связанный S15.
Проверки `custody` охватывают реальный вход стройки, баланс расхода, разделение/объединение, пять источников, смешанный частичный возврат, приостановку/возобновление, неизменность снимка и истории, точный повтор/конфликт/будущий запрос/вытеснение, неверные ссылки и фазы, нулевые и максимальные счётчики, ожидающее завершение после загрузки. Отдельная проверка `custody-metrics` строит мир 512×512 с 500 жителями, 10 000 стеками в 1000 складах и 2000 заказами на распределённых площадках; второй вариант дополнительно создаёт 4096 квитанций реальными циклами ткачества. Измеряются 101 захват снимка и 21 последовательный такт с полной проверкой и кодированием Current15. Это синтетический сценарий, а не измерение рендеринга или сети. [Исполняемые проверки](../../../tests/custody_tests.cpp)
Нативный Windows, MSVC и отказ системного аллокатора не проверялись. Числовые отказы и отказы вставки из-за неверных аргументов проверяются без изменения сериализуемого состояния. Готовность к публикации зависит от независимой проверки интегрированного M01; локальные изменения и измерения не означают разрешение на выпуск.
Проверка интегрированного кандидата: GCC 16.2, Windows x64 Release, Wine 11; полный `ctest --output-on-failure -V` прошёл 3/3 исполняемых набора (162 core, 9 LAN, 10 viewer). Включены 14 проверок `custody`, отдельная метрика и исторические/повреждённые контрольные точки S15. Оба обычных старых корпуса повторно совпали побайтово на 1/2/6/12 исполнителях: 738386 и 393857 байт.
В описанном синтетическом сценарии без квитанций захват снимка занял p50/p95 0,036/0,049 мс; с 4096 квитанциями — 0,046/0,053 мс. Полная проверка: 0,784/0,922 и 1,301/1,664 мс; кодирование Current15 с проверкой: 9,357/9,583 и 11,881/12,025 мс; 21 последовательный такт: 0,010/0,032 и 0,010/4,728 мс. Кодирование выполнялось в памяти без записи на диск. Размер Current15 — 924042 и 1335950 байт; исходное число стеков второго варианта — 10002 из-за ткацкого запаса. Один неизменяемый объект квитанции занимает 584 байта на проверенном ABI; 4096 объектов — 2392064 байта без служебных данных аллокатора и массива указателей. Измерения зависят от прогрева и нагрузки Wine; p95 снимка укладывается в исходный ориентир 5 мс, кодирование всего мира выполняется отдельно. Локальные журналы: `/tmp/stoneheart-milestones.xprJ2SVp/s06-custody-build-final.log`, `s06-custody-ctest-final.log` и `s06-custody-{trajectory,identity-compat}-compare.log`.
Дополнительная проверка кандидата Current15 требует уникальных ID резервов в порядке выдачи, в том числе в квитанциях уже завершённых исполнений. Результат завершения сначала объединяет строки материалов, которые относятся к одному окончательному `(владелец, StackId, ItemType)`: два склада с древесиной могут образовать один входной стек плотника. Одна итоговая запись сохраняет нулевой остаток расхода, отдельная — реальный результат у жителя. Повтор такой итоговой записи отклоняется независимо от указанного количества; одинаковый вид предмета у разных владельцев или разных стеков сам по себе не является повтором. Проверка ограничена восемью выданными резервами и одиннадцатью итоговыми записями.
Терминальная квитанция не может относиться к действующему исполнению, получению со склада или доставке на рабочую площадку. Задания с получением материалов переходят через `FetchingMaterials` и `Hauling`, затем в `Working`; обычный `Travelling` для них отклоняется, поскольку обходил бы получение. Дополнительные проверки используют реальные два склада плотника и пять источников хижины, точный повтор после загрузки и подписанные повреждённые контрольные точки S15. Сборка и полный CTest после этой коррекции: 167/167 core, 9/9 LAN, 10/10 viewer; отдельный `custody` — 17/17. Журналы этой проверки — `s06-custody-uniqueness-{build,focused,ctest}.log` в том же временном каталоге. Схема 15 остаётся неопубликованным кандидатом; старые опубликованные форматы не меняются.
+20
View File
@@ -37,6 +37,26 @@ Windows-адаптер чтения связан с [Void/Library #9](https://gi
При каждом успешном открытии файла создаётся новый экземпляр сетевой сессии, в том числе при откате того же мира на ранний такт. Запоздалый результат рабочего потока и команда клиента относятся к старому экземпляру и отбрасываются. Состояние переносимых резервов определяется сохранением, а права подключений проверяются заново. [Контракт сессии](S16.md)
## Владение имуществом в версии 15
`encode_checkpoint` записывает схему 3 и тело 15. Декодер проверяет отдельную таблицу пар: схема 1 допускает тела 1–13, схема 2 — только 14, схема 3 — только 15. Проверка внешнего SHA-256 предшествует декодированию мира. Старый FNV-footer тел 1–8 и нормализация сна до версии 5 сохранены.
Тело 15 сохраняет прежний набор полей тела 14 и добавляет реестр владения: три границы выданных ID, ID складских стеков и инвентарей, номер назначения каждого жителя, действующее исполнение с номерами операций и резервами, входы и приостановку заказов, восемь счётчиков баланса для каждого предмета и журнал результатов. Резервы содержат владельца, конкретный стек, количество, источник обеспечения вместимости и исходный склад. Пустые позиции массивов имеют единственное нулевое представление. Журнал записывается от самого старого результата к самому новому независимо от физической позиции кольца в памяти.
Запрос и результат имеют собственные 16-битные длины и типизированные поля little-endian. Текущий запрос занимает не более 109 байт, результат — 318 байт; общий предел каждого остаётся 1024 байта. Непустой элемент результата может содержать нулевой остаток уже израсходованного стека. Это историческая ссылка, а не новый пустой стек. Максимум 4096 записей занимает до 1 765 376 байт вместе с длинами. Проверяются точные данные запросов, а не только их хеши.
Лимит тела 128 МиБ отделён от лимита старого сетевого снимка 4 МиБ и от бюджета декодированной памяти. Число записей каждой исторической коллекции ограничено миллионом. Бюджет памяти учитывает расширенные C++-записи всех ограниченных пулов, вложенные массивы и журнал; арифметика верхней границы проверяется при компиляции. Чтение растит вектор по одному элементу и не резервирует память под объявленное недоверенным файлом число. Маленький обрезанный файл с числом жителей 1 000 000 заканчивается ошибкой после первой незавершённой записи.
Перенос старого тела начинается только после полной исторической проверки. ID назначаются в порядке вида владельца, ID владельца и предмета. Материалы, уже доставленные на стройку, восстанавливаются во входе заказа без повторного списания склада; у прямых рецептов исходный материал остаётся на складе. Только после этого измеряется начальный баланс. У старого активного задания следующее назначение равно 2, следующая операция — 1; исторические квитанции не создаются. При загрузке тела 15 недостающие данные не достраиваются.
Экспорт 13 и 14 вызывает чистую проверку представимости до первого байта. `UnsupportedLegacyState` сообщает о возвращаемом несовместимом грузе, приостановленной площадке и нулевом времени ожидающего завершения. Эти состояния полностью сохраняются в современной контрольной точке. Правила собственности и фаз проверяет общий `World::validate_custody`; кодек дополнительно проверяет геометрию, задания, ссылки, размеры и каноничность полей.
[Исторический корпус](../../../tests/fixtures/custody_v14/README.md) содержит 13 подлинных контрольных точек схемы 2, созданных исходной сборкой `f6493e2`, и ожидаемые хеши 80 последующих тактов. Объединённый прогон `e348a42` на Windows x64 GCC 16.2 под Wine 11 подтвердил все такты на последовательном исполнителе и 2/6/12 потоках, точный экспорт 14, канонический цикл схемы 3 и продолжение после загрузки. Отдельно проверены отменённая одиночная доска и каменный блок, смешанный груз без места, частичный возврат, приостановленные кровать и станок, нулевой таймер, старые ссылки квитанций и отказ после аутентифицированного повреждения. [Проверки миграции](../../../tests/custody_migration_tests.cpp) · [Снимки с полной версией 15](../../../tests/snapshot_tests.cpp)
Итоговая проверка S15-04: 14/14 тестов миграции и аутентифицированных изменений прошли за 4,92 с; полный CTest — 3/3 цели, 169 основных, 9 сетевых и 10 клиентских проверок, за 9,57 с. Реальные 2050 заказов заполнили кольцо до 4096 результатов; проверены точный повтор, конфликт, вытеснение, устаревшие номера и каноническая перезапись кольца после загрузки. Дополнительные отрицательные случаи меняют терминальность действующего исполнения, фазу доставки, источник добычи, вместимость отменённого возврата и уникальность ID/эффектов квитанции, сохраняя согласованные вторичные счётчики и внешний SHA-256. Допустимые исторические ссылки на израсходованный стек, нулевой остаток и разные виды владельцев проходят тот же кодек. Полный протокол проверки находится в `s15-custody-final-build.log`, `s15-custody-final-migration.log` и `s15-custody-final-ctest.log` во внешнем каталоге верификации.
Универсальные части продолжают использовать закреплённые Void Binary/Core/Crypto. Собственный формат и перенос игровых фаз относятся к S15; проверка замены библиотечным реестром остаётся связана с [Void/Library #7](https://git.faumaray.com/Void/Library/issues/7) и [#8](https://git.faumaray.com/Void/Library/issues/8). Нативная Windows и сохранность после отключения питания остаются отдельными проверками.
## Ошибки и восстановление
| Ситуация | Требуемое поведение |
+3 -26
View File
@@ -1,33 +1,10 @@
# S17. D3D11-рендеринг, камера и визуальное состояние
Статус — S17-W01 реализован и проверен в Windows x64/Wine; ожидает независимой приёмки. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
S17-W01 сохраняет существующую плоскую карту и Win32/D3D11. `PreparedFrame` удерживает один принятый `World`, параметры камеры и области, копии чертежей/комнат, выбор и предпросмотр, готовую CPU-геометрию, строки HUD и собственный шрифт. Главная и дочерняя `WM_PAINT` сначала удерживают весь пакет, затем рисуют без обращения к живому миру или векторам редактирования. [Подготовка кадров](../../../app/viewer_win32.cpp) · [Интерфейс сцены](../../../app/d3d_scene_win32.hpp)
Отдельный таймер 16 мс выбирает актуальный кадр только для видимой ненулевой игровой области и при изменениях. Таймер управления/LAN остаётся 60 мс, владелец симуляции — 50 мс. Это частоты обслуживания, а не утверждение о физической частоте экрана. Камера и размеры не пересобирают плоскую CPU-геометрию; неизменённая геометрия повторно не загружается на GPU. Размер render target, пересоздание устройства или возврат к удержанному старому пакету требуют соответствующей загрузки.
Ключ геометрии учитывает удержанный снимок мира, курсор и его допустимость, переносимый объект, жителя, все поля чертежей/комнат и предпросмотра, режим крыши/стен и переносимую комнату. Сравнение удерживаемых объектов снимков различает новые публикации даже при одинаковом такте. Пакеты владеют CPU-геометрией совместно; у renderer остаётся только текущая GPU-загрузка. Старый пакет можно отрисовать после нового или после сброса backend.
Пока `ViewerSession::changing_world()` истинно, прежнее представление сохраняется, включая отсутствие мира. Фоновая публикация между проверкой future и чтением мира не выпускает кандидата в UI. Только обработанный `Replaced` сбрасывает чертежи, выбор и камеру перед подготовкой замены. Подготовка приостанавливается внутри обработки событий и отрисовки; вложенная инвалидизация остаётся запросом следующего кадра. `BeginPaint` и временные DC/bitmap имеют RAII, backend удерживается до возврата из `Present`. При отказе остаётся HUD ошибки с восстановлением через повторный вход из меню; резервного GDI-рендера карты нет.
### Проверка S17-W01
Постоянная CMake/CTest-цель `settlement_viewer_frame_smoke` использует относительный include реального обработчика и настоящие главное/дочернее окна. [Тест](../../../tests/viewer_frame_smoke.cpp) проверяет:
- колесо и оба перетаскивания с изменением кадра/пикселей, когда настоящий рабочий `World` и запись файла `WriteStage` удерживаются барьерами; таймер событий в этой части не вызывается;
- неизменность полного канонического снимка и такта, повторное использование CPU/GPU-геометрии, побайтовое равенство сохранённого checkpoint исходному `World` и метаданным;
- отдельный удержанный файловый reader, старые комнаты/чертежи после редактирования, вложенные paint и незатерянную инвалидизацию;
- публикацию установки после `poll()` до чтения мира, вложенные paint в этом промежутке, сохранение прежнего/нулевого представления до `Replaced`;
- скрытие, минимизацию, меню, восстановление последней публикации, изменение размера, нулевую область, ошибку и повторный запуск renderer, отрисовку старого пакета после сброса backend;
- разрушение окна внутри paint и игнорирование оставшихся таймерных сообщений.
Сборка: GCC 16.2 MinGW, Release, закреплённая VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, `BUILD_TESTING=ON`. Проверка: `cmake --build <build> --parallel 6`, `ctest --test-dir <build> -V`, `git diff --check`. В Wine 11 с доступным DISPLAY работают видимый swap chain и offscreen WARP; проба DXGI сообщает «ATI Radeon HD 5600 Series» для обоих типов устройств. Это имя адаптера Wine, а не подтверждение физического GPU. Если устройства отсутствуют, smoke возвращает CTest skip 77; отказ renderer при доступном устройстве считается ошибкой.
Дополнительно прошли прежние UI-прогоны: blueprint/room handlers, отказ команд и сохранность чертежей, загрузка/выход из гостя, rollback LAN-диалогов, три настоящих процесса viewer с изолированным `LOCALAPPDATA`, меню, реальный file picker, современное и прежнее сохранение. Нативная Windows, физическая потеря устройства, 1080p60/p95 и будущая воксельная геометрия здесь не проверялись. Тест отказа renderer намеренно подаёт неподходящий viewport и проверяет штатный HUD/повторный вход.
Общий примитив публикации остаётся связан с [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5). При его появлении заменить локальное владение только после тех же проверок старого пакета, вложенной установки и срока жизни геометрии. `PreparedFrame` и игровые правила формирования HUD остаются клиентскими данными.
`D3DScene::render` принимает `const World&`, заново собирает геометрию карты, ресурсов, построек и жителей, загружает её и вызывает D3D11. `SceneView` хранит положение камеры, выбор и предпросмотр. Вызов происходит из `WM_PAINT`, а симуляция — из `WM_TIMER` того же окна. Основой нового клиента остаётся имеющийся Win32/D3D11-путь. [Интерфейс сцены](../../../app/d3d_scene_win32.hpp) · [Текущий рендер](../../../app/d3d_scene_win32.cpp)
## Границы данных и потоков
@@ -39,7 +16,7 @@ S17-W01 сохраняет существующую плоскую карту и
## Последовательность реализации
1. **S17-W01, M01 — реализовано, ожидает приёмки.** Неизменяемый пакет, отдельный таймер кадра и проверки камеры при удержанном рабочем/файловом вводе-выводе описаны выше.
1. **S17-W01, M01.** Ввести публикацию снимков и самостоятельный цикл кадров. Перенести обращения к миру из обработчиков отрисовки в подготовку снимка. Проверить работу камеры при искусственно долгом такте.
2. **S17-W02, M02.** Построить геометрию изменившихся чанков и обработку общих граней. Добавить отсечение невидимых областей и приоритет ближних участков. В тесте редактировать грань между двумя чанками и проверять отсутствие щели и дублирующей поверхности.
3. **S17-W03, M02–M03.** Добавить вращение, масштабирование вокруг указателя, выбор по лучу и срез высоты. Выбор возвращает регион, клетку, грань и ревизию, по которым интерфейс формирует намерение. При подтверждении симуляция проверяет действие на актуальной геометрии.
4. **S17-W04, M03–M07.** Разделить статическую геометрию, жителей, предметы и эффекты. Интерполировать визуальные позы между подтверждёнными тактами. Подключить оригинальные модели, анимацию, освещение, время суток и читаемую индикацию работы.
+39 -3
View File
@@ -111,7 +111,7 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu
координатора, который при переполнении сам может ждать в inline callable.
Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до
ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает
все 40 тактов с последовательным эталоном через настоящий `Current14` writer.
все 40 тактов с последовательным эталоном через настоящий `Current15` writer.
Лог содержит фактическую последовательность завершений каждой конфигурации.
[RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время
@@ -124,8 +124,9 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu
[Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает
канонические байты. Только при несовпадении она показывает первый различающийся
публичный факт: ID жителя/задания/производства, поле, expected/actual; для запасов —
владельца и тип предмета; для команд — игрока и следующую последовательность.
публичный факт с ID жителя, задания или производства, именем поля и значениями
expected/actual. Для запасов указываются владелец, тип предмета и ID стека,
для команд — игрок и следующий номер.
Сравнение квитанций содержит игрока, номер команды, статус, tick и revision.
Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков,
расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией
@@ -150,3 +151,38 @@ Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `Futu
Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись.
Serena/граф были связаны с основным checkout; для изолированного worktree использована
прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом.
## Полное состояние владения грузом
Потактный эталон и сравнение публикаций владельца используют `Current15`.
Сравнение включает имущество у производства, приостановку заказа, следующий
номер назначения, действующее исполнение и его резервы, результаты передач
и баланс каждого предмета. При расхождении диагностика показывает сначала
видимое изменение запасов или задания, затем постоянные ID и шаги исполнения,
сохранённые результаты и счётчики баланса. Ключ квитанции состоит из вида,
ID и номера операции. Положение квитанции в кольцевом буфере не служит её ID.
Если публичные факты совпали, сравнение сообщает первое различие байтов.
Проверка загрузки прежнего формата создаёт корректные миры с одинаковыми
байтами `Current14` и разными данными `Current15`. Она выявляет восстановленный
ID стека, различие начального остатка и начисления и отсутствие квитанции
назначения в историческом сохранении. Диагностический пример сообщает
`stock owner=storage:1 item=3 field=stack_id expected=2 actual=1`.
Отдельный сценарий отменяет настоящую стройку после доставки, заполняет
исходный склад и возвращает одну доску в склад вместимостью один предмет.
Оставшиеся две доски и два каменных блока ждут места у того же исполнителя
с тем же ID передачи. Контрольная точка восстанавливается на 1/2/6/12
исполнителях. После появления свободного склада каждый такт совпадает
с непрерывной партией. Точные и конфликтующие повторы квитанций назначения
и отмены проверяются до и после загрузки и после возврата груза.
Windows x64 Release GCC 16.2 под Wine 11 выполнил 10 проверок `replay` за 2,71 с
и 11 проверок `runtime` за 30 мс на рабочем срезе `e26b9c2` с этой проверкой.
Все 24 расписания завершения настоящих задач сохранились. Сценарий частичного
возврата занял 19,1 мс. Логи находятся в
`/tmp/stoneheart-milestones.xprJ2SVp/s21-custody-{configure,build-final,replay,runtime}.log`.
После объединения с исправлением проверки времени и ссылок S06 в `8522f91`
повторная сборка и CTest завершились с кодом 0. Все три цели прошли за 26,91 с,
включая 169 проверок ядра, 9 LAN и 10 клиента. Журналы этой сборки и запуска —
`s21-custody-build-validated.log` и `s21-custody-ctest-validated.log`.
@@ -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(
+115
View File
@@ -0,0 +1,115 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace settlement {
enum class ItemType : std::uint8_t;
using StackId = std::uint64_t;
using ReservationId = std::uint64_t;
using TransferId = std::uint64_t;
// Recipe quantities are not property and never carry an identity.
struct ItemAmount {
ItemType type{};
std::uint32_t count = 0;
bool operator==(const ItemAmount&) const = default;
};
enum class OwnerKind : std::uint8_t { None, Storage, Resident, Production };
struct StockOwner {
OwnerKind kind = OwnerKind::None;
std::uint64_t id = 0;
bool operator==(const StockOwner&) const = default;
};
enum class ReservationKind : std::uint8_t { Item, Capacity, Worksite, Harvest, Tending };
struct Reservation {
ReservationId id = 0;
ReservationKind kind = ReservationKind::Item;
StockOwner owner{};
StackId stack = 0;
ItemType item{};
std::uint32_t count = 0;
ReservationId backing = 0;
std::uint64_t origin_storage = 0;
bool operator==(const Reservation&) const = default;
};
enum class TransferKind : std::uint8_t { Production, Harvest, Tending, Meal, Return };
enum class CustodyStatus : std::uint8_t {
Accepted, Conflict, Stale, Future, Invalid, Busy, Capacity, Exhausted, Overflow, NoDestination
};
enum class CustodyOperation : std::uint8_t { Admit, Pickup, Deliver, Complete, Cancel, Return, Harvest, Eat, Tend };
enum class CustodyKeyKind : std::uint8_t { Admission, Operation };
struct CustodyKey {
CustodyKeyKind kind = CustodyKeyKind::Admission;
std::uint64_t id = 0; // AgentId for admission, TransferId for operation.
std::uint64_t ordinal = 0;
bool operator==(const CustodyKey&) const = default;
};
struct CustodyLine {
std::uint64_t storage = 0;
ItemType item{};
std::uint32_t count = 0;
bool operator==(const CustodyLine&) const = default;
};
inline constexpr std::size_t custody_material_limit = 5;
inline constexpr std::size_t custody_reservation_limit = 8;
inline constexpr std::size_t custody_receipt_limit = 4096;
struct CustodyRequest {
CustodyKey key{};
CustodyOperation operation = CustodyOperation::Admit;
TransferKind kind = TransferKind::Production;
std::uint64_t production = 0;
std::uint64_t source = 0;
std::uint64_t destination = 0;
std::array<CustodyLine, custody_material_limit> lines{};
std::uint8_t line_count = 0;
bool operator==(const CustodyRequest&) const = default;
};
struct CustodyEffect {
StockOwner owner{};
StackId stack = 0;
ItemType item{};
std::uint32_t count = 0;
bool operator==(const CustodyEffect&) const = default;
};
struct CustodyResult {
CustodyStatus status = CustodyStatus::Invalid;
TransferId transfer = 0;
std::array<ReservationId, custody_reservation_limit> reservations{};
std::array<CustodyEffect, 11> effects{};
std::uint8_t reservation_count = 0;
std::uint8_t effect_count = 0;
bool terminal = false;
bool operator==(const CustodyResult&) const = default;
};
struct CustodyReceipt {
CustodyRequest request{};
CustodyResult result{};
};
struct TransferExecution {
TransferId id = 0;
TransferKind kind = TransferKind::Production;
std::uint64_t production = 0;
std::uint64_t source = 0;
std::uint64_t destination = 0;
std::uint64_t next_operation = 1;
std::array<Reservation, custody_reservation_limit> reservations{};
std::uint8_t reservation_count = 0;
CustodyStatus blocked = CustodyStatus::Accepted;
};
struct ItemBalance {
std::uint64_t opening = 0;
std::uint64_t grant = 0;
std::uint64_t harvest = 0;
std::uint64_t recipe_output = 0;
std::uint64_t recipe_input = 0;
std::uint64_t meal = 0;
std::uint64_t installation = 0;
std::uint64_t demolition = 0;
};
static_assert(sizeof(CustodyRequest) <= 1024 && sizeof(CustodyResult) <= 1024);
} // namespace settlement
@@ -1,84 +0,0 @@
#pragma once
#include "settlement/core/voxel_region.hpp"
#include <Void/Core/Uuid.hpp>
#include <cstddef>
#include <optional>
#include <span>
#include <stop_token>
#include <vector>
namespace settlement {
enum class VoxelNavigationStatus {
Reachable, Unreachable, Unavailable, SearchBoundary, LimitExceeded,
Cancelled, InvalidInput, AllocationFailed
};
struct VoxelNavigationLimits {
std::size_t max_vertices = 65'536;
std::size_t max_steps = 1'000'000;
std::size_t max_samples = 4'000'000;
std::size_t max_scratch_bytes = 8 * 1024 * 1024;
std::size_t max_goals = 64;
std::size_t max_dependencies = 4096;
};
struct VoxelReadSet {
RegionId region = 0;
Void::Uuid::Uuid session;
// Sorted unique chunk coordinates, including blocked and unavailable reads.
std::vector<ChunkStamp> chunks;
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept;
};
struct VoxelTraversalResult {
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
VoxelReadSet consulted;
};
struct VoxelPathRequest {
RegionId region = 0;
Void::Uuid::Uuid session;
VoxelPosition start;
// The caller chooses a finite search window contained in the region.
VoxelBounds search_bounds;
std::vector<VoxelPosition> goals;
VoxelNavigationLimits limits;
};
struct VoxelPathResult {
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
std::optional<VoxelPosition> goal;
// Excludes start, includes goal. An already satisfied goal has an empty route.
std::vector<VoxelPosition> route;
std::size_t cost = 0;
std::size_t visited = 0;
VoxelReadSet consulted;
};
// Ordinary settlers occupy the foot cell and the cell above, with solid support
// below. A transition is one cardinal horizontal move and at most one step.
[[nodiscard]] VoxelTraversalResult voxel_standing(
const VoxelRegion& world, const Void::Uuid::Uuid& session, VoxelPosition foot,
VoxelNavigationLimits limits = {}, std::stop_token stop = {});
[[nodiscard]] VoxelTraversalResult voxel_transition(
const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits = {},
std::stop_token stop = {});
// Finds a shortest known route within the requested window. Equal costs choose
// the lexicographically first goal; each vertex's neighbors use coordinate order.
// A negative result distinguishes missing chunks and an escapable window edge.
[[nodiscard]] VoxelPathResult find_voxel_path(
const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop = {});
// Candidate feet touch the target by a face of either body cell, or stand one
// cell above / two below it. The target must be loaded. Work policy stays with
// the owner; navigation only proves contact and a supported clear body volume.
// request.goals is ignored; the same bounds, identity and limits apply.
[[nodiscard]] VoxelPathResult find_voxel_interaction_path(
const VoxelRegion& world, const VoxelPathRequest& request,
VoxelPosition target, std::stop_token stop = {});
} // namespace settlement
@@ -1,168 +0,0 @@
#pragma once
#include <array>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace settlement {
using RegionId = std::uint64_t;
inline constexpr std::int32_t voxel_chunk_side = 32;
inline constexpr std::size_t voxel_chunk_cells = 32 * 32 * 32;
inline constexpr std::uint32_t voxel_generator_version = 1;
struct VoxelPosition {
std::int32_t x = 0, y = 0, z = 0;
auto operator<=>(const VoxelPosition&) const = default;
};
struct ChunkCoordinate {
std::int32_t x = 0, y = 0, z = 0;
auto operator<=>(const ChunkCoordinate&) const = default;
};
struct VoxelEndpoint {
std::int64_t x = 0, y = 0, z = 0;
bool operator==(const VoxelEndpoint&) const = default;
};
struct VoxelBounds {
VoxelEndpoint lower, upper;
[[nodiscard]] bool contains(VoxelPosition position) const noexcept;
bool operator==(const VoxelBounds&) const = default;
};
struct LocalVoxel {
std::uint8_t x = 0, y = 0, z = 0;
bool operator==(const LocalVoxel&) const = default;
};
struct VoxelAddress {
ChunkCoordinate chunk;
LocalVoxel local;
};
[[nodiscard]] VoxelAddress split_voxel(VoxelPosition position) noexcept;
[[nodiscard]] std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept;
[[nodiscard]] std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept;
enum class MaterialId : std::uint8_t { Air = 0, Soil = 1, Stone = 2, DoorClosed = 3, DoorOpen = 4 };
[[nodiscard]] bool valid_voxel_material(MaterialId material) noexcept;
[[nodiscard]] bool voxel_blocks_passage(MaterialId material) noexcept;
[[nodiscard]] bool voxel_provides_support(MaterialId material) noexcept;
struct VoxelRegionDescriptor {
RegionId id = 0;
std::uint64_t seed = 0;
std::uint32_t generator_version = voxel_generator_version;
VoxelBounds bounds;
bool operator==(const VoxelRegionDescriptor&) const = default;
};
struct VoxelLimits {
std::size_t max_resident_chunks = 256;
std::size_t max_edit_cells = 4096;
// Budgets charge object and vector payloads. Allocator bookkeeping and
// snapshots/prepared pages retained by the caller have separate lifetimes.
std::size_t max_resident_bytes = 16 * 1024 * 1024;
std::size_t max_transaction_bytes = 16 * 1024 * 1024;
};
enum class VoxelAvailability : std::uint8_t { Outside, Unavailable, Loaded };
struct ChunkStamp {
RegionId region = 0;
ChunkCoordinate coordinate;
VoxelAvailability availability = VoxelAvailability::Unavailable;
std::uint64_t revision = 0;
bool operator==(const ChunkStamp&) const = default;
};
struct VoxelSample {
VoxelAvailability availability = VoxelAvailability::Outside;
MaterialId material = MaterialId::Air;
ChunkStamp stamp;
};
class VoxelChunk {
public:
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
[[nodiscard]] std::span<const MaterialId, voxel_chunk_cells> cells() const noexcept { return cells_; }
private:
friend class VoxelRegion;
VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells);
std::uint64_t revision_;
std::array<MaterialId, voxel_chunk_cells> cells_;
};
struct VoxelChunkEntry {
ChunkCoordinate coordinate;
std::shared_ptr<const VoxelChunk> chunk;
};
using VoxelDirectory = std::vector<VoxelChunkEntry>;
class PreparedVoxelChunk {
public:
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
[[nodiscard]] ChunkCoordinate coordinate() const noexcept { return coordinate_; }
[[nodiscard]] const std::shared_ptr<const VoxelChunk>& chunk() const noexcept { return chunk_; }
private:
friend class VoxelRegion;
PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
std::shared_ptr<const VoxelChunk> chunk);
VoxelRegionDescriptor descriptor_;
ChunkCoordinate coordinate_;
std::shared_ptr<const VoxelChunk> chunk_;
};
enum class VoxelError : std::uint8_t {
InvalidCoordinate, InvalidMaterial, InvalidRevision, InvalidSource,
Duplicate, Unavailable, Stale, RevisionExhausted, LimitExceeded, AllocationFailed
};
struct VoxelEdit {
VoxelPosition position;
MaterialId material = MaterialId::Air;
std::uint64_t expected_revision = 0;
};
struct VoxelChange {
VoxelPosition position;
MaterialId before = MaterialId::Air;
MaterialId after = MaterialId::Air;
bool operator==(const VoxelChange&) const = default;
};
struct VoxelCommit {
std::vector<ChunkStamp> changed_chunks;
std::vector<VoxelChange> changed_cells;
// Changed chunks and intersecting face-neighbors, including unavailable
// neighbors. Unchanged neighbors keep their own material revision.
std::vector<ChunkCoordinate> dirty_chunks;
};
// Copies retain the complete immutable directory. A reader keeps its own copy
// while the single owner publishes changes. Session identity fences snapshots
// across save/load; this layer does not unload or reuse chunk revisions.
class VoxelRegion {
public:
explicit VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits = {});
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
[[nodiscard]] const VoxelLimits& limits() const noexcept { return limits_; }
[[nodiscard]] std::shared_ptr<const VoxelDirectory> directory() const noexcept { return directory_; }
[[nodiscard]] std::size_t resident_bytes() const noexcept;
[[nodiscard]] bool intersects(ChunkCoordinate coordinate) const noexcept;
[[nodiscard]] ChunkStamp chunk_stamp(ChunkCoordinate coordinate) const noexcept;
[[nodiscard]] bool matches(const ChunkStamp& stamp) const noexcept;
[[nodiscard]] VoxelSample sample(VoxelPosition position) const noexcept;
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_generated(ChunkCoordinate coordinate) const;
// Validated, deep-copied import for persistence, including exhausted valid
// revisions. Cells outside a partial region must be canonical air.
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_restored(
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const;
// Activation only accepts unavailable chunks from this exact descriptor.
// Every candidate is installed together or the directory is preserved.
[[nodiscard]] std::expected<VoxelCommit, VoxelError> activate(std::span<const PreparedVoxelChunk> candidates);
[[nodiscard]] std::expected<VoxelCommit, VoxelError> edit(std::span<const VoxelEdit> edits);
private:
VoxelRegionDescriptor descriptor_;
VoxelLimits limits_;
std::shared_ptr<const VoxelDirectory> directory_;
};
} // namespace settlement
+49 -5
View File
@@ -13,6 +13,7 @@
#include <vector>
#include "settlement/core/worker_pool.hpp"
#include "settlement/core/custody.hpp"
namespace settlement {
@@ -22,7 +23,12 @@ using ResourceNodeId = std::uint64_t;
using StorageId = std::uint64_t;
using ProductionId = std::uint64_t;
enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14 };
enum class WorldSaveFormat : std::uint32_t { Legacy13 = 13, Current14 = 14, Current15 = 15 };
class UnsupportedLegacyState : public std::runtime_error {
public:
UnsupportedLegacyState() : std::runtime_error("state has no exact legacy representation") {}
};
// Raised only by a complete production-ID preflight, before any domain effects.
class ProductionCapacityError : public std::overflow_error {
@@ -47,7 +53,8 @@ enum class AgentState : std::uint8_t {
GoingToEat,
Eating,
GoingToSleep,
Sleeping
Sleeping,
Returning
};
enum class JobState : std::uint8_t {
@@ -237,9 +244,13 @@ public:
void add(ItemType type, std::uint32_t count = 1) noexcept;
void remove(ItemType type, std::uint32_t count = 1) noexcept;
[[nodiscard]] ItemType first_item() const noexcept;
[[nodiscard]] StackId stack_id(ItemType type) const noexcept;
private:
friend class World;
friend struct WorldSaveCodec;
void set_stack_id(ItemType type, StackId id) noexcept;
std::array<std::uint32_t, item_type_count> counts_{};
std::array<StackId, item_type_count> stack_ids_{};
};
struct Agent {
@@ -260,6 +271,9 @@ struct Agent {
bool resting_on_ground = false;
Profession profession = Profession::Generalist;
std::uint64_t next_admission = 1;
std::optional<TransferExecution> execution;
[[nodiscard]] bool hungry() const noexcept { return hunger >= hunger_threshold; }
[[nodiscard]] bool tired() const noexcept { return fatigue >= fatigue_threshold; }
};
@@ -292,6 +306,7 @@ struct ItemStack {
ItemType type = ItemType::None;
std::uint32_t count = 0;
std::uint32_t reserved = 0;
StackId id = 0;
};
struct Storage {
@@ -351,6 +366,8 @@ struct ProductionOrder {
AgentId bed_owner = 0;
BedBase bed_base = BedBase::Wood;
BedStage bed_stage = BedStage::Legacy;
Inventory input;
bool suspended = false;
[[nodiscard]] ItemType bed_material() const noexcept {
if (bed_stage == BedStage::Legacy) return ItemType::Plank;
@@ -382,6 +399,12 @@ struct WorldState {
std::uint64_t next_resource_node_id_ = 1;
std::uint64_t next_storage_id_ = 1;
ProductionId next_production_id_ = 1;
StackId next_stack_id_ = 1;
ReservationId next_reservation_id_ = 1;
TransferId next_transfer_id_ = 1;
std::array<ItemBalance, item_type_count> item_balances_{};
std::vector<std::shared_ptr<const CustodyReceipt>> custody_receipts_;
std::size_t custody_receipt_cursor_ = 0;
std::vector<std::uint8_t> blocked_;
std::vector<Agent> agents_;
std::vector<WorkJob> jobs_;
@@ -417,12 +440,19 @@ public:
StorageKind kind = StorageKind::Materials);
void stock_storage(std::uint64_t id, ItemType type, std::uint32_t count);
void enable_hunger() noexcept;
[[nodiscard]] CommandStatus cancel_production(ProductionId id);
[[nodiscard]] CommandStatus resume_production(ProductionId id);
[[nodiscard]] bool legacy_representable() const noexcept;
void validate_custody() const;
[[nodiscard]] CustodyResult custody_request(const CustodyRequest& request);
[[nodiscard]] const auto& item_balances() const noexcept { return item_balances_; }
[[nodiscard]] const auto& custody_receipts() const noexcept { return custody_receipts_; }
void queue_production(GridPosition position, RecipeId recipe);
[[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept;
[[nodiscard]] bool can_place_room(const RoomPlan& plan) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] std::array<ItemAmount, 2> construction_materials(RecipeId recipe, BedBase base) const;
[[nodiscard]] RecipeId room_construction_recipe(RecipeId part) const noexcept;
[[nodiscard]] std::array<ItemStack, 2> carpentry_materials(RecipeId recipe) const;
[[nodiscard]] std::array<ItemAmount, 2> carpentry_materials(RecipeId recipe) const;
[[nodiscard]] std::optional<GridPosition> carpenter_workshop() const noexcept {
if (!scenario_active_) return std::nullopt;
return scenario_sawmill_;
@@ -475,6 +505,20 @@ public:
private:
friend struct WorldSaveCodec;
void migrate_legacy_custody();
[[nodiscard]] bool admit_custody(Agent& agent, TransferKind kind, ProductionId production,
ResourceNodeId source, StorageId destination, const std::vector<MaterialReservation>& materials);
void finish_custody(Agent& agent) noexcept;
void advance_return(Agent& agent);
[[nodiscard]] bool pickup_custody(Agent& agent, Storage& source,
const std::vector<MaterialReservation>& materials, bool reserve_output);
[[nodiscard]] bool deliver_custody(Agent& agent, Inventory& destination, StockOwner owner);
[[nodiscard]] bool deposit_custody(Agent& agent, Storage& destination, ItemType type, std::uint32_t count);
void record_custody(std::shared_ptr<const CustodyReceipt> receipt) noexcept;
[[nodiscard]] std::shared_ptr<const CustodyReceipt> prepare_custody(
Agent& agent, CustodyOperation operation, CustodyStatus status = CustodyStatus::Accepted,
StorageId source = 0, StorageId destination = 0);
void commit_custody(Agent& agent, std::shared_ptr<const CustodyReceipt> receipt) noexcept;
struct CaptureTag {};
World(CaptureTag, const World& source);
struct PathResult {
+4 -3
View File
@@ -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()});
+836
View File
@@ -0,0 +1,836 @@
#include "settlement/core/world.hpp"
#include "settlement/core/inventory_transaction.hpp"
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <limits>
#include <set>
#include <map>
#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;
const auto fail = [&](CustodyStatus status) {
receipt->result.status = status;
commit_custody(agent, receipt);
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 fail(CustodyStatus::Invalid);
slots -= claim.count;
claim = {};
}
}
if (planned.total_items() + slots + count > planned.capacity) return fail(CustodyStatus::Capacity);
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 fail(CustodyStatus::Overflow);
target->count = *amount;
id = target->id;
} else {
id = inventory.stack_id(type);
if (count < inventory.item_count(type)) {
if (!room(next, 1)) return fail(CustodyStatus::Exhausted);
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<JobId, const WorkJob*> work_jobs;
std::set<JobId> assigned_jobs;
for (const auto& job : jobs_) require(work_jobs.emplace(job.id, &job).second);
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::unordered_map<TransferId, std::uint64_t> active_ordinals;
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 &&
actor.state != AgentState::Gathering && actor.state != AgentState::FetchingMaterials &&
(actor.state != AgentState::Working || actor.current_job != 0));
require(actor.storage_id == 0 && actor.haul_route.empty());
if (actor.state == AgentState::Working || actor.state == AgentState::Travelling) {
const auto job = work_jobs.find(actor.current_job);
require(job != work_jobs.end() && job->second->state == JobState::InProgress &&
assigned_jobs.insert(actor.current_job).second && actor.work_remaining > 0 && actor.work_remaining <= job->second->work_required);
if (actor.state == AgentState::Working) require(actor.position == job->second->position && actor.route_cursor == actor.route.size());
else require(actor.route_cursor < actor.route.size() && actor.route.back() == job->second->position);
} else require(actor.current_job == 0 && actor.work_remaining == 0 &&
(actor.state == AgentState::Idle || actor.state == AgentState::GoingToSleep || actor.state == AgentState::Sleeping));
continue;
}
const auto& execution = *actor.execution;
require(actor.current_job == 0 && !actor.resting_on_ground);
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);
active_ordinals.emplace(execution.id, execution.next_operation);
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.haul_route.empty());
require((actor.state == AgentState::Returning && !actor.storage_id && !execution.destination && !execution.reservation_count) ||
(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 && actor.haul_route.empty());
if (actor.state == AgentState::GoingToEat) {
const auto* pantry = find_storage(actor.storage_id);
require(pantry && pantry->kind == StorageKind::Pantry && actor.inventory.empty() && actor.work_remaining == 0);
require(actor.route.empty() ? actor.position == pantry->position : actor.route.back() == pantry->position);
} else require(!actor.storage_id && actor.route.empty() && actor.route_cursor == 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.source != 0) == (actor.state != AgentState::Hauling));
if (execution.kind == TransferKind::Tending) require(actor.state != AgentState::Hauling && !actor.storage_id && !execution.destination && actor.haul_route.empty());
else require(execution.destination != 0 && actor.storage_id == execution.destination);
} else {
require(actor.state == AgentState::Travelling || actor.state == AgentState::Working ||
actor.state == AgentState::FetchingMaterials || actor.state == AgentState::Hauling);
if (execution.production) {
const auto* order = find_production(execution.production);
require(order && !actor.storage_id);
require(is_carpentry_recipe(order->recipe) || actor.haul_route.empty());
}
else require(actor.state == AgentState::Hauling && is_carpentry_item(actor.inventory.first_item()));
}
std::array<unsigned, 5> claim_kinds{};
std::array<std::uint64_t, item_type_count> resident_claims{};
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);
++claim_kinds[static_cast<std::size_t>(claim.kind)];
if (claim.kind == ReservationKind::Item) {
if (claim.owner.kind == OwnerKind::Resident && claim.item > ItemType::None && claim.item <= ItemType::Loom)
resident_claims[static_cast<std::size_t>(claim.item) - 1] += claim.count;
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;
require((claim.kind == ReservationKind::Tending) == (execution.kind == TransferKind::Tending));
}
}
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Worksite)] == (execution.production ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Capacity)] == (execution.destination ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Harvest)] ==
(execution.kind == TransferKind::Harvest && execution.source ? 1U : 0U));
require(claim_kinds[static_cast<std::size_t>(ReservationKind::Tending)] == (execution.kind == TransferKind::Tending ? 1U : 0U));
if (execution.kind == TransferKind::Harvest || execution.kind == TransferKind::Tending ||
(execution.kind == TransferKind::Production && !execution.production)) require(claim_kinds[0] == 0);
if (execution.kind == TransferKind::Meal) {
require(claim_kinds[0] == 1);
for (const auto& claim : execution.reservations) if (claim.id && claim.kind == ReservationKind::Item) {
require(claim.item == ItemType::Berries && claim.count == 1 && claim.owner ==
(actor.state == AgentState::Eating ? StockOwner{OwnerKind::Resident, actor.id} : StockOwner{OwnerKind::Storage, actor.storage_id}));
}
}
if (actor.state == AgentState::Eating || (execution.kind == TransferKind::Return && actor.state == AgentState::Hauling)) {
for (std::size_t i = 0; i < item_type_count; ++i) require(resident_claims[i] == actor.inventory.item_count(static_cast<ItemType>(i + 1)));
}
if (execution.source) {
const auto* node = find_resource_node(execution.source);
require(node && actor.inventory.empty() && (actor.state == AgentState::Gathering || actor.state == AgentState::Travelling));
require(execution.kind != TransferKind::Tending || node->needs_tending());
require(execution.kind != TransferKind::Harvest || (node->quantity && execution.destination && actor.storage_id == execution.destination));
if (actor.state == AgentState::Travelling) require(actor.work_remaining > 0 && actor.route_cursor < actor.route.size() && actor.route.back() == node->position);
else require(actor.position == node->position && actor.route_cursor == actor.route.size());
if (execution.kind == TransferKind::Harvest) {
const auto* destination = find_storage(execution.destination);
require(destination && destination->accepts(node->type));
require(actor.haul_route.empty() ? node->position == destination->position : actor.haul_route.back() == destination->position);
}
}
if (actor.state == AgentState::Hauling && !execution.production) {
require(actor.storage_id == execution.destination && execution.destination && actor.work_remaining == 0);
std::uint64_t carried = 0;
for (std::size_t i = 1; i <= item_type_count; ++i) carried += actor.inventory.item_count(static_cast<ItemType>(i));
require(carried == 1 && actor.haul_route.empty());
const auto cargo = actor.inventory.first_item();
const bool resource = cargo == ItemType::Wood || cargo == ItemType::Stone || cargo == ItemType::Berries || cargo == ItemType::Flax;
require(resource || is_carpentry_item(cargo));
if (execution.kind == TransferKind::Harvest) require(resource);
const auto* destination = find_storage(execution.destination);
require(destination && destination->accepts(cargo));
require(actor.route.empty() ? actor.position == destination->position : actor.route.back() == destination->position);
}
}
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& job : jobs_) require((job.state == JobState::InProgress) == assigned_jobs.contains(job.id));
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;
require(order.materials.size() <= custody_material_limit && order.collected_stops <= order.delivery_stops.size());
const bool delivery = delivers_materials(order.recipe);
const auto destination = is_construction(order.recipe) ? 0 : order.materials.front().storage_id;
require(actor->execution->destination == destination);
if (destination) {
ReservationId backing = 0;
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item &&
claim.owner == StockOwner{OwnerKind::Storage, destination}) { backing = claim.id; break; }
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Capacity) require(claim.backing == backing);
}
require(delivery || order.delivery_stops.empty());
// Delivered recipes never use the generic Travelling transition:
// that transition enters Working without performing any pickup.
if (delivery) {
require(actor->state == AgentState::FetchingMaterials || actor->state == AgentState::Hauling || actor->state == AgentState::Working);
if (actor->state == AgentState::Working) require(order.delivery_stops.empty() && order.collected_stops == 0 && actor->position == order.position);
else {
require(!order.delivery_stops.empty() && actor->work_remaining > 0);
require(actor->state == AgentState::FetchingMaterials ? order.collected_stops == 0 : order.collected_stops > 0);
auto target = order.position;
if (order.collected_stops < order.delivery_stops.size()) {
const auto* store = find_storage(order.delivery_stops[order.collected_stops].storage_id);
require(store != nullptr); target = store->position;
}
require(actor->route.empty() ? actor->position == target : actor->route.back() == target);
}
} else {
require(order.collected_stops == 0 && (actor->state == AgentState::Travelling || actor->state == AgentState::Working));
if (actor->state == AgentState::Travelling) require(actor->work_remaining > 0 && actor->route_cursor < actor->route.size() && actor->route.back() == order.position);
else require(actor->position == order.position);
}
std::array<std::uint64_t, item_type_count> required{}, planned{}, claimed{}, cargo{};
const auto need = [&](ItemType item, std::uint32_t count) { if (count) required[static_cast<std::size_t>(item) - 1] += count; };
if (order.recipe == RecipeId::SawPlank) need(ItemType::Wood, 1);
else if (order.recipe == RecipeId::CutStoneBlock) need(ItemType::Stone, 1);
else if (order.recipe == RecipeId::WeaveCloth) need(ItemType::Flax, 1);
else if (order.recipe == RecipeId::BuildBed) need(order.bed_material(), 1);
else for (const auto& item : is_carpentry_recipe(order.recipe) ? carpentry_materials(order.recipe) :
construction_materials(order.recipe, order.bed_base)) need(item.type, item.count);
StorageId previous_stop = 0;
for (const auto& stop : order.delivery_stops) {
require(stop.storage_id > previous_stop && find_storage(stop.storage_id)); previous_stop = stop.storage_id;
require(std::any_of(order.materials.begin(), order.materials.end(), [&](const auto& m) { return m.storage_id == stop.storage_id; }));
}
for (const auto& line : order.materials) {
require(line.type > ItemType::None && line.type <= ItemType::Loom && line.count && find_storage(line.storage_id));
planned[static_cast<std::size_t>(line.type) - 1] += line.count;
StockOwner expected{OwnerKind::Storage, line.storage_id};
if (delivery) {
if (actor->state == AgentState::Working) expected = {OwnerKind::Production, order.id};
else {
const auto stop = std::find_if(order.delivery_stops.begin(), order.delivery_stops.end(), [&](const auto& e) { return e.storage_id == line.storage_id; });
require(stop != order.delivery_stops.end());
if (static_cast<std::size_t>(stop - order.delivery_stops.begin()) < order.collected_stops) expected = {OwnerKind::Resident, actor->id};
}
}
std::uint64_t line_claims = 0;
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item &&
claim.item == line.type && claim.origin_storage == line.storage_id) { require(claim.owner == expected); line_claims += claim.count; }
require(line_claims == line.count);
if (expected.kind == OwnerKind::Resident) cargo[static_cast<std::size_t>(line.type) - 1] += line.count;
}
for (const auto& claim : actor->execution->reservations) if (claim.id && claim.kind == ReservationKind::Item)
claimed[static_cast<std::size_t>(claim.item) - 1] += claim.count;
require(planned == required && claimed == required);
for (std::size_t i = 0; i < item_type_count; ++i) require(cargo[i] == actor->inventory.item_count(static_cast<ItemType>(i + 1)));
if (actor->state == AgentState::Working) require(actor->route_cursor == actor->route.size() && order.delivery_stops.empty());
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;
std::map<std::pair<CustodyKeyKind, std::uint64_t>, std::uint64_t> last_ordinals;
TransferId last_admission = 0;
ReservationId last_issued_reservation = 0;
std::set<TransferId> terminal_transfers;
for (std::size_t receipt_index = 0; receipt_index < custody_receipts_.size(); ++receipt_index) {
const auto& receipt = custody_receipts_[(receipt_index + custody_receipt_cursor_) % custody_receipts_.size()];
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);
auto& last_ordinal = last_ordinals[{request.key.kind, request.key.id}];
require(last_ordinal == 0 || (last_ordinal != maximum && request.key.ordinal == last_ordinal + 1));
last_ordinal = request.key.ordinal;
require(!terminal_transfers.contains(result.transfer));
if (result.terminal) {
require(result.status == CustodyStatus::Accepted && !active_ordinals.contains(result.transfer));
require(request.operation == CustodyOperation::Complete || request.operation == CustodyOperation::Eat ||
request.operation == CustodyOperation::Tend || request.operation == CustodyOperation::Cancel ||
request.operation == CustodyOperation::Return ||
(request.operation == CustodyOperation::Deliver && request.destination != 0));
terminal_transfers.insert(result.transfer);
}
require(request.source < (((request.operation == CustodyOperation::Admit &&
(request.kind == TransferKind::Harvest || request.kind == TransferKind::Tending)) ||
request.operation == CustodyOperation::Harvest || request.operation == CustodyOperation::Tend) ? next_resource_node_id_ : next_storage_id_));
if (request.key.kind == CustodyKeyKind::Admission) {
require(result.transfer > last_admission && !result.terminal);
last_admission = result.transfer;
require(result.status == CustodyStatus::Accepted && 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 && result.transfer == request.key.id);
const auto active = active_ordinals.find(request.key.id);
if (active != active_ordinals.end()) require(request.key.ordinal < active->second);
}
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);
}
if (request.operation == CustodyOperation::Admit) {
require(result.effect_count == 0);
require(result.reservation_count == request.line_count + static_cast<unsigned>(request.production != 0) +
static_cast<unsigned>(request.source != 0) + static_cast<unsigned>(request.destination != 0));
switch (request.kind) {
case TransferKind::Production: require(request.production && !request.source && request.line_count); break;
case TransferKind::Harvest: require(!request.production && request.source && request.destination && !request.line_count); break;
case TransferKind::Tending: require(!request.production && request.source && !request.destination && !request.line_count); break;
case TransferKind::Meal:
require(!request.production && !request.source && !request.destination && request.line_count == 1 &&
request.lines[0].item == ItemType::Berries && request.lines[0].count == 1); break;
case TransferKind::Return: require(false); break;
}
} else {
switch (request.operation) {
case CustodyOperation::Pickup:
require((request.kind == TransferKind::Production || request.kind == TransferKind::Meal) &&
request.source && !request.destination && !request.line_count &&
(request.production != 0) == (request.kind == TransferKind::Production)); break;
case CustodyOperation::Deliver:
require(!request.source && (request.kind == TransferKind::Production || request.kind == TransferKind::Harvest));
if (request.destination) require(!request.production && request.line_count == 1 && request.lines[0].storage == request.destination);
else require(request.kind == TransferKind::Production && request.production && !request.line_count);
break;
case CustodyOperation::Complete:
case CustodyOperation::Cancel:
require(request.kind == TransferKind::Production && request.production && !request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Return:
require(request.kind == TransferKind::Return && !request.production && !request.source && request.destination &&
request.line_count == 1 && request.lines[0].storage == request.destination); break;
case CustodyOperation::Harvest:
case CustodyOperation::Tend:
require(request.kind == (request.operation == CustodyOperation::Harvest ? TransferKind::Harvest : TransferKind::Tending) &&
!request.production && request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Eat:
require(request.kind == TransferKind::Meal && !request.production && !request.source && !request.destination && !request.line_count); break;
case CustodyOperation::Admit: require(false); break;
}
}
require(result.status <= CustodyStatus::NoDestination && result.transfer && result.transfer < next_transfer_id_ &&
result.reservation_count <= custody_reservation_limit && result.effect_count <= item_type_count);
// Only admissions issue claims, in allocator order. Check their retained
// history without resolving already released claims to live objects.
require(request.operation == CustodyOperation::Admit || result.reservation_count == 0);
for (std::size_t i = 0; i < custody_reservation_limit; ++i) {
if (i >= result.reservation_count) { require(result.reservations[i] == 0); continue; }
require(result.reservations[i] > last_issued_reservation && result.reservations[i] < next_reservation_id_);
last_issued_reservation = result.reservations[i];
}
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);
// Effects are final outcomes, not per-material deltas. Distinct
// owners/stack IDs may legitimately share an item type. Zero counts
// describe consumption of a historical stack and remain valid.
for (std::size_t prior = 0; prior < i; ++prior) {
const auto& other = result.effects[prior];
require(effect.owner != other.owner || effect.stack != other.stack || effect.item != other.item);
}
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
-306
View File
@@ -1,306 +0,0 @@
#include "settlement/core/voxel_navigation.hpp"
#include <Void/Algorithms/Graph.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <limits>
#include <new>
#include <stdexcept>
namespace settlement {
namespace {
using Status = VoxelNavigationStatus;
struct NavigationFailure { Status status; };
std::optional<VoxelPosition> offset(VoxelPosition p, int x, int y, int z) noexcept {
const auto nx = std::int64_t{p.x} + x, ny = std::int64_t{p.y} + y, nz = std::int64_t{p.z} + z;
constexpr auto low = std::numeric_limits<std::int32_t>::min();
constexpr auto high = std::numeric_limits<std::int32_t>::max();
if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {};
return VoxelPosition{static_cast<std::int32_t>(nx), static_cast<std::int32_t>(ny), static_cast<std::int32_t>(nz)};
}
bool valid_bounds(const VoxelBounds& b, const VoxelBounds& region) noexcept {
return b.lower.x < b.upper.x && b.lower.y < b.upper.y && b.lower.z < b.upper.z &&
b.lower.x >= region.lower.x && b.lower.y >= region.lower.y && b.lower.z >= region.lower.z &&
b.upper.x <= region.upper.x && b.upper.y <= region.upper.y && b.upper.z <= region.upper.z;
}
class Queries {
public:
Queries(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelNavigationLimits limits, std::stop_token stop)
: world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} {
if (session.is_nil()) throw NavigationFailure{Status::InvalidInput};
if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded};
const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded};
reads.chunks.reserve(limits.max_dependencies);
}
VoxelSample sample(VoxelPosition p) {
if (stop_.stop_requested()) throw NavigationFailure{Status::Cancelled};
if (samples_ == limits_.max_samples) throw NavigationFailure{Status::LimitExceeded};
++samples_;
auto value = world_.sample(p);
auto at = std::lower_bound(reads.chunks.begin(), reads.chunks.end(), value.stamp.coordinate,
[](const auto& stamp, const auto& coordinate) { return stamp.coordinate < coordinate; });
if (at == reads.chunks.end() || at->coordinate != value.stamp.coordinate) {
if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded};
reads.chunks.insert(at, value.stamp);
}
return value;
}
Status standing(VoxelPosition foot) {
const auto above = offset(foot, 0, 0, 1), below = offset(foot, 0, 0, -1);
if (!above || !below) return Status::Unreachable;
const auto body = sample(foot), head = sample(*above), support = sample(*below);
// A known obstruction is conclusive even if another cell is unavailable.
if (body.availability == VoxelAvailability::Outside || head.availability == VoxelAvailability::Outside ||
support.availability == VoxelAvailability::Outside ||
(body.availability == VoxelAvailability::Loaded && voxel_blocks_passage(body.material)) ||
(head.availability == VoxelAvailability::Loaded && voxel_blocks_passage(head.material)) ||
(support.availability == VoxelAvailability::Loaded && !voxel_provides_support(support.material))) return Status::Unreachable;
if (body.availability == VoxelAvailability::Unavailable || head.availability == VoxelAvailability::Unavailable ||
support.availability == VoxelAvailability::Unavailable) return Status::Unavailable;
return Status::Reachable;
}
Status transition(VoxelPosition from, VoxelPosition to) {
const auto dx = std::int64_t{to.x} - from.x, dy = std::int64_t{to.y} - from.y;
const auto dz = std::int64_t{to.z} - from.z;
if (!((dx == -1 || dx == 1) && dy == 0) && !((dy == -1 || dy == 1) && dx == 0)) return Status::Unreachable;
if (dz < -1 || dz > 1) return Status::Unreachable;
const auto first = standing(from), second = standing(to);
Status swept = Status::Reachable;
if (dz != 0) {
const auto upper = offset(dz > 0 ? from : to, 0, 0, 2);
if (!upper) return Status::Unreachable;
const auto cell = sample(*upper);
if (cell.availability == VoxelAvailability::Outside ||
(cell.availability == VoxelAvailability::Loaded && voxel_blocks_passage(cell.material))) swept = Status::Unreachable;
else if (cell.availability == VoxelAvailability::Unavailable) swept = Status::Unavailable;
}
if (first == Status::Unreachable || second == Status::Unreachable || swept == Status::Unreachable) return Status::Unreachable;
if (first == Status::Unavailable || second == Status::Unavailable || swept == Status::Unavailable) return Status::Unavailable;
return Status::Reachable;
}
const VoxelRegion& world_;
VoxelNavigationLimits limits_;
std::stop_token stop_;
VoxelReadSet reads;
private:
std::size_t samples_ = 0;
};
struct NeighborList {
std::array<std::size_t, 12> values{};
std::size_t size = 0;
auto begin() const { return values.begin(); }
auto end() const { return values.begin() + static_cast<std::ptrdiff_t>(size); }
};
class WalkingGraph {
public:
WalkingGraph(Queries& queries, VoxelBounds bounds, std::size_t sx, std::size_t sy, std::size_t count)
: queries_(queries), bounds_(bounds), sx_(sx), sy_(sy), count_(count) {}
std::size_t vertex_count() const noexcept { return count_; }
std::size_t index(VoxelPosition p) const noexcept {
return static_cast<std::size_t>(std::int64_t{p.x} - bounds_.lower.x) + sx_ *
(static_cast<std::size_t>(std::int64_t{p.y} - bounds_.lower.y) + sy_ *
static_cast<std::size_t>(std::int64_t{p.z} - bounds_.lower.z));
}
VoxelPosition position(std::size_t i) const noexcept {
return {static_cast<std::int32_t>(bounds_.lower.x + static_cast<std::int64_t>(i % sx_)),
static_cast<std::int32_t>(bounds_.lower.y + static_cast<std::int64_t>((i / sx_) % sy_)),
static_cast<std::int32_t>(bounds_.lower.z + static_cast<std::int64_t>(i / (sx_ * sy_)))};
}
NeighborList neighbors(std::size_t i) const {
NeighborList result;
const auto from = position(i);
// This is lexicographic VoxelPosition order, including all step heights.
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
for (auto direction : directions) for (int dz = -1; dz <= 1; ++dz) {
const auto to = offset(from, direction[0], direction[1], dz);
if (!to) continue;
const auto state = queries_.transition(from, *to);
// Only inconclusive edges out of reached vertices can extend the
// search into missing data. Raw reads may already have been ruled
// out by a known wall, floor or obstructed swept body volume.
if (state == Status::Unavailable) unavailable = true;
if (state != Status::Reachable) continue;
if (!bounds_.contains(*to)) { boundary = true; continue; }
result.values[result.size++] = index(*to);
}
return result;
}
mutable bool boundary = false;
mutable bool unavailable = false;
private:
Queries& queries_;
VoxelBounds bounds_;
std::size_t sx_, sy_, count_;
};
VoxelPathResult search(Queries& queries, const VoxelPathRequest& request,
std::span<const VoxelPosition> goals, std::span<const VoxelPosition> omitted = {}) {
VoxelPathResult result;
if (goals.empty() && omitted.empty()) return result;
const auto& limits = request.limits;
if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) {
result.status = Status::LimitExceeded; return result;
}
for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result;
const auto sx = static_cast<std::size_t>(request.search_bounds.upper.x - request.search_bounds.lower.x);
const auto sy = static_cast<std::size_t>(request.search_bounds.upper.y - request.search_bounds.lower.y);
const auto sz = static_cast<std::size_t>(request.search_bounds.upper.z - request.search_bounds.lower.z);
const auto count = Void::Numeric::checked_mul(sx, sy).and_then(
[sz](auto xy) { return Void::Numeric::checked_mul(xy, sz); });
// Void BFS retains four size_t vectors plus visited. Route construction and
// the read-set reserve coexist with them. No adjacency matrix is allocated.
const auto vertex_bytes = count.and_then([](auto size) {
return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition));
});
const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes ||
*count > std::vector<std::size_t>{}.max_size() ||
*count > std::vector<std::uint8_t>{}.max_size() ||
*count > std::vector<VoxelPosition>{}.max_size()) {
result.status = Status::LimitExceeded; return result;
}
const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes);
if (!bytes || *bytes > limits.max_scratch_bytes) {
result.status = Status::LimitExceeded; return result;
}
const auto start_state = queries.standing(request.start);
if (start_state != Status::Reachable) { result.status = start_state; return result; }
WalkingGraph graph(queries, request.search_bounds, sx, sy, *count);
const Void::Algorithms::WorkLimits work{
limits.max_vertices, limits.max_steps, limits.max_scratch_bytes - *read_bytes, 1};
auto traversal = Void::Algorithms::bfs(graph, graph.index(request.start), work, queries.stop_);
if (!traversal) {
result.status = traversal.error().code == Void::Algorithms::AlgorithmError::Code::cancelled ? Status::Cancelled : Status::LimitExceeded;
return result;
}
result.visited = traversal->order.size();
std::size_t distance = Void::Algorithms::TraversalResult::npos;
bool possible_goal = false;
for (auto goal : goals) {
// Explicit validation also covers the library's start==target fast path.
const auto standing = queries.standing(goal);
possible_goal = possible_goal || standing != Status::Unreachable;
if (standing != Status::Reachable) continue;
const auto cost = traversal->depth[graph.index(goal)];
if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos &&
(!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; }
}
if (!result.goal) {
// Interaction contacts outside the selected window still matter to a
// global negative. Their feasibility cannot manufacture a frontier;
// BFS must also have reached a valid exit or an unresolved transition.
for (auto goal : omitted) {
const auto standing = queries.standing(goal);
possible_goal = possible_goal || standing != Status::Unreachable;
}
result.status = Status::Unreachable;
if (possible_goal) {
if (graph.unavailable) result.status = Status::Unavailable;
else if (graph.boundary) result.status = Status::SearchBoundary;
}
return result;
}
result.status = Status::Reachable;
result.cost = distance;
result.route.reserve(distance);
auto vertex = graph.index(*result.goal);
const auto start = graph.index(request.start);
while (vertex != start) {
result.route.push_back(graph.position(vertex));
vertex = traversal->parent[vertex];
}
std::reverse(result.route.begin(), result.route.end());
return result;
}
template<class Function>
VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelNavigationLimits limits, std::stop_token stop, Function&& function) {
VoxelTraversalResult result;
result.consulted = {world.descriptor().id, session, {}};
try {
Queries queries(world, session, limits, stop);
try { result.status = function(queries); }
catch (const NavigationFailure& failure) { result.status = failure.status; }
result.consulted = std::move(queries.reads);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
return result;
}
VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request,
std::optional<VoxelPosition> target, std::stop_token stop) {
VoxelPathResult result;
result.consulted = {world.descriptor().id, request.session, {}};
if (request.region != world.descriptor().id || request.session.is_nil() ||
!valid_bounds(request.search_bounds, world.descriptor().bounds) ||
!request.search_bounds.contains(request.start)) return result;
try {
Queries queries(world, request.session, request.limits, stop);
try {
if (target) {
const auto cell = queries.sample(*target);
if (cell.availability != VoxelAvailability::Loaded) {
result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput;
} else {
std::array<VoxelPosition, 10> goals{};
std::array<VoxelPosition, 10> omitted{};
std::size_t size = 0, omitted_size = 0;
const auto add_goal = [&](std::optional<VoxelPosition> goal) {
if (!goal) return;
if (request.search_bounds.contains(*goal)) goals[size++] = *goal;
else omitted[omitted_size++] = *goal;
};
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
for (auto direction : directions) for (int dz : {-1, 0}) {
add_goal(offset(*target, direction[0], direction[1], dz));
}
for (int dz : {-2, 1}) {
add_goal(offset(*target, 0, 0, dz));
}
result = search(queries, request, std::span(goals.data(), size),
std::span(omitted.data(), omitted_size));
}
} else result = search(queries, request, request.goals);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
result.consulted = std::move(queries.reads);
} catch (const NavigationFailure& failure) { result.status = failure.status; }
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
return result;
}
} // namespace
bool VoxelReadSet::current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept {
return region == world.descriptor().id && !session.is_nil() && epoch == session &&
std::all_of(chunks.begin(), chunks.end(), [&](const auto& stamp) { return world.matches(stamp); });
}
VoxelTraversalResult voxel_standing(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition foot, VoxelNavigationLimits limits, std::stop_token stop) {
return check(world, session, limits, stop, [&](Queries& queries) { return queries.standing(foot); });
}
VoxelTraversalResult voxel_transition(const VoxelRegion& world, const Void::Uuid::Uuid& session,
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits, std::stop_token stop) {
return check(world, session, limits, stop, [&](Queries& queries) { return queries.transition(from, to); });
}
VoxelPathResult find_voxel_path(const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop) {
return path(world, request, {}, stop);
}
VoxelPathResult find_voxel_interaction_path(const VoxelRegion& world, const VoxelPathRequest& request,
VoxelPosition target, std::stop_token stop) {
return path(world, request, target, stop);
}
} // namespace settlement
-383
View File
@@ -1,383 +0,0 @@
#include "settlement/core/voxel_region.hpp"
#include <Void/Binary/Writer.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <limits>
#include <new>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
constexpr auto coordinate_min = std::int64_t{std::numeric_limits<std::int32_t>::min()};
constexpr auto coordinate_end = std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1;
bool valid_interval(std::int64_t lower, std::int64_t upper) noexcept {
return lower >= coordinate_min && upper <= coordinate_end && lower < upper;
}
std::pair<std::int32_t, std::uint8_t> split_axis(std::int32_t value) noexcept {
auto chunk = value / voxel_chunk_side;
auto local = value % voxel_chunk_side;
if (local < 0) {
--chunk;
local += voxel_chunk_side;
}
return {chunk, static_cast<std::uint8_t>(local)};
}
VoxelEndpoint chunk_origin(ChunkCoordinate coordinate) noexcept {
return {std::int64_t{coordinate.x} * voxel_chunk_side,
std::int64_t{coordinate.y} * voxel_chunk_side,
std::int64_t{coordinate.z} * voxel_chunk_side};
}
bool overlapping_axis(std::int64_t origin, std::int64_t lower, std::int64_t upper) noexcept {
return origin < upper && origin + voxel_chunk_side > lower;
}
auto find_chunk(const VoxelDirectory& directory, ChunkCoordinate coordinate) noexcept {
return std::lower_bound(directory.begin(), directory.end(), coordinate,
[](const auto& entry, auto key) { return entry.coordinate < key; });
}
class PayloadBudget {
public:
explicit PayloadBudget(std::size_t limit) : remaining_(limit) {}
bool take(std::size_t count, std::size_t size) noexcept {
const auto bytes = Void::Numeric::checked_mul(count, size);
if (!bytes || *bytes > remaining_) return false;
remaining_ -= *bytes;
return true;
}
private:
std::size_t remaining_;
};
std::uint64_t terrain_hash(std::uint64_t seed, std::int64_t x, std::int64_t y) {
std::array<std::byte, 40> bytes{};
Void::Binary::Writer writer(bytes);
if (!writer.writeLittle(seed) || !writer.writeLittle(voxel_generator_version) ||
!writer.writeLittle(std::uint32_t{1}) || !writer.writeLittle(x) ||
!writer.writeLittle(y) || !writer.writeLittle(std::int64_t{0})) {
throw std::logic_error("voxel generator field layout exceeds its fixed buffer");
}
return Void::Hash::fnv1a64(writer.written());
}
std::int64_t surface_height(std::uint64_t seed, std::int32_t x, std::int32_t y) {
// Interpolate absolute lattice columns to keep adjacent heights within one
// voxel. Widened lattice endpoints also cover the final int32 column.
const auto lattice = [](std::int32_t value) {
std::int64_t quotient = value / 16;
if (value % 16 < 0) --quotient;
return quotient * 16;
};
const auto x0 = lattice(x), y0 = lattice(y);
const auto dx = std::int64_t{x} - x0, dy = std::int64_t{y} - y0;
const auto height = [seed](std::int64_t a, std::int64_t b) {
return static_cast<std::int64_t>(terrain_hash(seed, a, b) % 17) - 8;
};
const auto numerator = height(x0, y0) * (16 - dx) * (16 - dy) +
height(x0 + 16, y0) * dx * (16 - dy) +
height(x0, y0 + 16) * (16 - dx) * dy + height(x0 + 16, y0 + 16) * dx * dy;
auto result = numerator / 256;
if (numerator % 256 < 0) --result;
return result;
}
void add_neighbor(const VoxelRegion& region, std::vector<ChunkCoordinate>& dirty,
ChunkCoordinate coordinate, int axis, int delta) {
std::array<std::int64_t, 3> values{coordinate.x, coordinate.y, coordinate.z};
values[static_cast<std::size_t>(axis)] += delta;
if (values[static_cast<std::size_t>(axis)] < coordinate_min ||
values[static_cast<std::size_t>(axis)] >= coordinate_end) return;
const ChunkCoordinate neighbor{static_cast<std::int32_t>(values[0]),
static_cast<std::int32_t>(values[1]), static_cast<std::int32_t>(values[2])};
if (region.intersects(neighbor)) dirty.push_back(neighbor);
}
void canonicalize(std::vector<ChunkCoordinate>& coordinates) {
std::sort(coordinates.begin(), coordinates.end());
coordinates.erase(std::unique(coordinates.begin(), coordinates.end()), coordinates.end());
}
} // namespace
bool VoxelBounds::contains(VoxelPosition position) const noexcept {
return position.x >= lower.x && position.x < upper.x &&
position.y >= lower.y && position.y < upper.y &&
position.z >= lower.z && position.z < upper.z;
}
VoxelAddress split_voxel(VoxelPosition position) noexcept {
const auto [cx, lx] = split_axis(position.x);
const auto [cy, ly] = split_axis(position.y);
const auto [cz, lz] = split_axis(position.z);
return {{cx, cy, cz}, {lx, ly, lz}};
}
std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept {
if (local.x >= voxel_chunk_side || local.y >= voxel_chunk_side || local.z >= voxel_chunk_side) return {};
return std::size_t{local.x} + 32 * (std::size_t{local.y} + 32 * std::size_t{local.z});
}
std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept {
if (!voxel_index(local)) return {};
const auto origin = chunk_origin(chunk);
const auto x = origin.x + local.x, y = origin.y + local.y, z = origin.z + local.z;
if (x < coordinate_min || x >= coordinate_end || y < coordinate_min || y >= coordinate_end ||
z < coordinate_min || z >= coordinate_end) return {};
return VoxelPosition{static_cast<std::int32_t>(x), static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
}
bool valid_voxel_material(MaterialId material) noexcept {
return material >= MaterialId::Air && material <= MaterialId::DoorOpen;
}
bool voxel_blocks_passage(MaterialId material) noexcept {
return material == MaterialId::Soil || material == MaterialId::Stone || material == MaterialId::DoorClosed;
}
bool voxel_provides_support(MaterialId material) noexcept {
return material == MaterialId::Soil || material == MaterialId::Stone;
}
VoxelChunk::VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells)
: revision_(revision) {
std::copy(cells.begin(), cells.end(), cells_.begin());
}
PreparedVoxelChunk::PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
std::shared_ptr<const VoxelChunk> chunk)
: descriptor_(descriptor), coordinate_(coordinate), chunk_(std::move(chunk)) {}
VoxelRegion::VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits)
: descriptor_(descriptor), limits_(limits) {
const auto& bounds = descriptor.bounds;
if (!descriptor.id || descriptor.generator_version != voxel_generator_version ||
!valid_interval(bounds.lower.x, bounds.upper.x) || !valid_interval(bounds.lower.y, bounds.upper.y) ||
!valid_interval(bounds.lower.z, bounds.upper.z) || !limits.max_resident_chunks || !limits.max_edit_cells ||
limits.max_resident_bytes < sizeof(VoxelDirectory) || !limits.max_transaction_bytes) {
throw std::invalid_argument("invalid voxel region descriptor or limits");
}
directory_ = std::make_shared<const VoxelDirectory>();
}
std::size_t VoxelRegion::resident_bytes() const noexcept {
return sizeof(VoxelDirectory) + directory_->size() * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk));
}
bool VoxelRegion::intersects(ChunkCoordinate coordinate) const noexcept {
const auto origin = chunk_origin(coordinate);
const auto& bounds = descriptor_.bounds;
return overlapping_axis(origin.x, bounds.lower.x, bounds.upper.x) &&
overlapping_axis(origin.y, bounds.lower.y, bounds.upper.y) &&
overlapping_axis(origin.z, bounds.lower.z, bounds.upper.z);
}
ChunkStamp VoxelRegion::chunk_stamp(ChunkCoordinate coordinate) const noexcept {
ChunkStamp result{descriptor_.id, coordinate, VoxelAvailability::Outside, 0};
if (!intersects(coordinate)) return result;
const auto entry = find_chunk(*directory_, coordinate);
result.availability = VoxelAvailability::Unavailable;
if (entry != directory_->end() && entry->coordinate == coordinate) {
result.availability = VoxelAvailability::Loaded;
result.revision = entry->chunk->revision();
}
return result;
}
bool VoxelRegion::matches(const ChunkStamp& stamp) const noexcept {
return chunk_stamp(stamp.coordinate) == stamp;
}
VoxelSample VoxelRegion::sample(VoxelPosition position) const noexcept {
const auto address = split_voxel(position);
VoxelSample result{VoxelAvailability::Outside, MaterialId::Air, chunk_stamp(address.chunk)};
if (!descriptor_.bounds.contains(position)) return result;
result.availability = result.stamp.availability;
if (result.availability == VoxelAvailability::Loaded) {
result.material = find_chunk(*directory_, address.chunk)->chunk->cells()[*voxel_index(address.local)];
}
return result;
}
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_generated(ChunkCoordinate coordinate) const {
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
PayloadBudget budget(limits_.max_transaction_bytes);
if (!budget.take(1, sizeof(VoxelChunk)) || !budget.take(voxel_chunk_cells, sizeof(MaterialId))) {
return std::unexpected(VoxelError::LimitExceeded);
}
try {
std::array<MaterialId, voxel_chunk_cells> cells{};
const auto origin = chunk_origin(coordinate);
for (std::int32_t y = 0; y < voxel_chunk_side; ++y) {
for (std::int32_t x = 0; x < voxel_chunk_side; ++x) {
const auto px = static_cast<std::int32_t>(origin.x + x);
const auto py = static_cast<std::int32_t>(origin.y + y);
const auto height = surface_height(descriptor_.seed, px, py);
for (std::int32_t z = 0; z < voxel_chunk_side; ++z) {
const VoxelPosition position{px, py, static_cast<std::int32_t>(origin.z + z)};
if (!descriptor_.bounds.contains(position) || position.z > height) continue;
const auto material = position.z > height - 3 ? MaterialId::Soil : MaterialId::Stone;
const auto index = static_cast<std::size_t>(x + 32 * (y + 32 * z));
cells[index] = material;
}
}
}
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(1, cells));
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelError::AllocationFailed);
}
}
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_restored(
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const {
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
if (!revision) return std::unexpected(VoxelError::InvalidRevision);
if (cells.size() != voxel_chunk_cells) return std::unexpected(VoxelError::InvalidSource);
if (limits_.max_transaction_bytes < sizeof(VoxelChunk)) return std::unexpected(VoxelError::LimitExceeded);
for (std::size_t i = 0; i < cells.size(); ++i) {
if (!valid_voxel_material(cells[i])) return std::unexpected(VoxelError::InvalidMaterial);
const auto position = join_voxel(coordinate,
{static_cast<std::uint8_t>(i % 32), static_cast<std::uint8_t>((i / 32) % 32),
static_cast<std::uint8_t>(i / 1024)});
if (!position || (!descriptor_.bounds.contains(*position) && cells[i] != MaterialId::Air)) {
return std::unexpected(VoxelError::InvalidCoordinate);
}
}
try {
const std::span<const MaterialId, voxel_chunk_cells> fixed(cells.data(), voxel_chunk_cells);
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, fixed));
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelError::AllocationFailed);
}
}
std::expected<VoxelCommit, VoxelError> VoxelRegion::activate(std::span<const PreparedVoxelChunk> candidates) {
if (candidates.empty()) return VoxelCommit{};
if (candidates.size() > limits_.max_resident_chunks - directory_->size()) {
return std::unexpected(VoxelError::LimitExceeded);
}
const auto count = directory_->size() + candidates.size();
PayloadBudget resident(limits_.max_resident_bytes);
PayloadBudget staging(limits_.max_transaction_bytes);
const auto dirty_count = Void::Numeric::checked_mul(candidates.size(), std::size_t{7});
if (!dirty_count || !resident.take(1, sizeof(VoxelDirectory)) ||
!resident.take(count, sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) ||
!staging.take(1, sizeof(VoxelDirectory)) || !staging.take(count, sizeof(VoxelChunkEntry)) ||
!staging.take(candidates.size(), sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
return std::unexpected(VoxelError::LimitExceeded);
}
try {
auto next = std::make_shared<VoxelDirectory>();
next->reserve(count);
next->insert(next->end(), directory_->begin(), directory_->end());
VoxelCommit result;
result.changed_chunks.reserve(candidates.size());
result.dirty_chunks.reserve(*dirty_count);
for (const auto& candidate : candidates) {
if (candidate.descriptor_ != descriptor_ || !candidate.chunk_ || !intersects(candidate.coordinate_)) {
return std::unexpected(VoxelError::InvalidSource);
}
if (chunk_stamp(candidate.coordinate_).availability != VoxelAvailability::Unavailable) {
return std::unexpected(VoxelError::Stale);
}
next->push_back({candidate.coordinate_, candidate.chunk_});
result.changed_chunks.push_back({descriptor_.id, candidate.coordinate_,
VoxelAvailability::Loaded, candidate.chunk_->revision()});
result.dirty_chunks.push_back(candidate.coordinate_);
for (int axis = 0; axis < 3; ++axis) {
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, -1);
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, 1);
}
}
std::sort(next->begin(), next->end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
for (std::size_t i = 1; i < next->size(); ++i) {
if ((*next)[i - 1].coordinate == (*next)[i].coordinate) return std::unexpected(VoxelError::Duplicate);
}
std::sort(result.changed_chunks.begin(), result.changed_chunks.end(),
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
canonicalize(result.dirty_chunks);
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
directory_.swap(publication);
return result;
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelError::AllocationFailed);
}
}
std::expected<VoxelCommit, VoxelError> VoxelRegion::edit(std::span<const VoxelEdit> edits) {
if (edits.empty()) return VoxelCommit{};
if (edits.size() > limits_.max_edit_cells) return std::unexpected(VoxelError::LimitExceeded);
PayloadBudget staging(limits_.max_transaction_bytes);
if (!staging.take(edits.size(), sizeof(VoxelEdit))) return std::unexpected(VoxelError::LimitExceeded);
try {
std::vector<VoxelEdit> ordered(edits.begin(), edits.end());
std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
const auto ca = split_voxel(a.position).chunk, cb = split_voxel(b.position).chunk;
return ca == cb ? a.position < b.position : ca < cb;
});
std::size_t changed_pages = 0, changed_cells = 0;
std::optional<ChunkCoordinate> last_changed;
for (std::size_t i = 0; i < ordered.size(); ++i) {
const auto& change = ordered[i];
if (i && ordered[i - 1].position == change.position) return std::unexpected(VoxelError::Duplicate);
if (!valid_voxel_material(change.material)) return std::unexpected(VoxelError::InvalidMaterial);
const auto current = sample(change.position);
if (current.availability == VoxelAvailability::Outside) return std::unexpected(VoxelError::InvalidCoordinate);
if (current.availability == VoxelAvailability::Unavailable) return std::unexpected(VoxelError::Unavailable);
if (current.stamp.revision != change.expected_revision) return std::unexpected(VoxelError::Stale);
if (current.material == change.material) continue;
if (current.stamp.revision == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected(VoxelError::RevisionExhausted);
}
++changed_cells;
if (!last_changed || *last_changed != current.stamp.coordinate) {
++changed_pages;
last_changed = current.stamp.coordinate;
}
}
if (!changed_cells) return VoxelCommit{};
const auto dirty_count = Void::Numeric::checked_mul(changed_cells, std::size_t{4});
if (!dirty_count || !staging.take(1, sizeof(VoxelDirectory)) ||
!staging.take(directory_->size(), sizeof(VoxelChunkEntry)) ||
!staging.take(changed_pages, sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
!staging.take(voxel_chunk_cells, sizeof(MaterialId)) ||
!staging.take(changed_cells, sizeof(VoxelChange)) ||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
return std::unexpected(VoxelError::LimitExceeded);
}
auto next = std::make_shared<VoxelDirectory>(*directory_);
VoxelCommit result;
result.changed_cells.reserve(changed_cells);
result.changed_chunks.reserve(changed_pages);
result.dirty_chunks.reserve(*dirty_count);
for (std::size_t first = 0; first < ordered.size();) {
const auto coordinate = split_voxel(ordered[first].position).chunk;
auto last = first + 1;
while (last < ordered.size() && split_voxel(ordered[last].position).chunk == coordinate) ++last;
const auto old = find_chunk(*directory_, coordinate);
std::array<MaterialId, voxel_chunk_cells> cells;
std::copy(old->chunk->cells().begin(), old->chunk->cells().end(), cells.begin());
const auto count_before = result.changed_cells.size();
for (auto i = first; i < last; ++i) {
const auto& change = ordered[i];
const auto local = split_voxel(change.position).local;
auto& material = cells[*voxel_index(local)];
if (material == change.material) continue;
result.changed_cells.push_back({change.position, material, change.material});
material = change.material;
result.dirty_chunks.push_back(coordinate);
const std::array<std::uint8_t, 3> axes{local.x, local.y, local.z};
for (int axis = 0; axis < 3; ++axis) {
if (axes[static_cast<std::size_t>(axis)] == 0) add_neighbor(*this, result.dirty_chunks, coordinate, axis, -1);
if (axes[static_cast<std::size_t>(axis)] == 31) add_neighbor(*this, result.dirty_chunks, coordinate, axis, 1);
}
}
if (result.changed_cells.size() != count_before) {
const auto revision = old->chunk->revision() + 1;
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, cells));
const auto index = static_cast<std::size_t>(old - directory_->begin());
(*next)[index].chunk = std::move(chunk);
result.changed_chunks.push_back({descriptor_.id, coordinate, VoxelAvailability::Loaded, revision});
}
first = last;
}
std::sort(result.changed_cells.begin(), result.changed_cells.end(),
[](const auto& a, const auto& b) { return a.position < b.position; });
canonicalize(result.dirty_chunks);
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
directory_.swap(publication);
return result;
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelError::AllocationFailed);
}
}
} // namespace settlement
+208 -74
View File
@@ -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 {
@@ -428,12 +429,15 @@ AgentId World::spawn_agent(GridPosition position) {
if (!is_walkable(position)) {
throw std::invalid_argument("agent spawn cell is not walkable");
}
const AgentId id = next_agent_id_++;
const AgentId id = next_agent_id_;
const auto successor = Void::Numeric::checked_add(id, AgentId{1});
if (id == 0 || !successor) throw std::overflow_error("resident identities exhausted");
Agent agent;
agent.id = id;
agent.position = position;
if (hunger_enabled_) agent.hunger = initial_hunger(id);
agents_.push_back(std::move(agent));
next_agent_id_ = *successor;
return id;
}
@@ -444,8 +448,11 @@ JobId World::add_job(GridPosition position, std::uint32_t work_required) {
if (work_required == 0) {
throw std::invalid_argument("work duration must be greater than zero");
}
const JobId id = next_job_id_++;
const JobId id = next_job_id_;
const auto successor = Void::Numeric::checked_add(id, JobId{1});
if (id == 0 || !successor) throw std::overflow_error("job identities exhausted");
jobs_.push_back(WorkJob{id, position, work_required, work_required, JobState::Available});
next_job_id_ = *successor;
return id;
}
@@ -497,8 +504,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 +584,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 +603,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 +765,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 +1332,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 +1369,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 +1398,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 +1416,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 +1467,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 +1491,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 +1516,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 +1533,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 +1545,23 @@ 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 = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Eat,
amount && meals ? CustodyStatus::Accepted : CustodyStatus::Overflow));
if (!receipt) return;
receipt->result.terminal = amount && meals;
receipt->result.effects[0] = {{OwnerKind::Resident, agent.id}, agent.inventory.stack_id(ItemType::Berries), ItemType::Berries,
amount && meals ? 0U : 1U};
receipt->result.effect_count = 1;
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 +1622,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 +1637,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 +1650,101 @@ 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;
for (const auto& material : order.materials) {
const auto& original_store = storage_by_id(material.storage_id);
StackId consumed_id = 0;
std::uint32_t remaining = 0;
StockOwner owner{OwnerKind::Production, order.id};
if (delivered) { consumed_id = order.input.stack_id(material.type); remaining = input.item_count(material.type); }
else {
owner = {OwnerKind::Storage, material.storage_id};
for (const auto& stack : original_store.items) if (stack.type == material.type) consumed_id = stack.id;
for (const auto& store : stores) if (store.id == material.storage_id) remaining = store.item_count(material.type);
}
// Several source lines can have merged into one physical site stack.
// Record its final outcome once, retaining the first material order.
const auto end = receipt->result.effects.begin() + receipt->result.effect_count;
const bool recorded = std::any_of(receipt->result.effects.begin(), end, [&](const auto& effect) {
return effect.owner == owner && effect.stack == consumed_id && effect.item == material.type;
});
if (!recorded) receipt->result.effects[receipt->result.effect_count++] = {owner, consumed_id, material.type, remaining};
}
if (output_id) {
receipt->result.effects[receipt->result.effect_count++] = {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)};
}
}
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 +1755,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 +1817,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 +1872,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 +1894,14 @@ 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 = std::const_pointer_cast<CustodyReceipt>(prepare_custody(agent, CustodyOperation::Tend, growth ? CustodyStatus::Accepted : CustodyStatus::Overflow, node.id));
if (!receipt) continue;
receipt->result.terminal = growth.has_value();
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 +1909,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, node.id));
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 +1941,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();
+358 -9
View File
@@ -18,10 +18,20 @@ 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;
// The wire limit is independent of decoded C++ layout: an old byte-light agent
// now includes an execution/claim array. Cover every bounded top-level pool,
// nested vectors (maximum element expansion <4x wire), and the receipt ring.
// This is an accounting ceiling, never a reserve() request from untrusted input.
constexpr std::size_t record_pool_bytes = sizeof(Agent) + sizeof(WorkJob) +
sizeof(ResourceNode) + sizeof(Storage) + sizeof(ProductionOrder);
static_assert(record_pool_bytes <= (std::numeric_limits<std::size_t>::max() -
4 * max_save_bytes - custody_receipt_limit * (sizeof(CustodyReceipt) + 32)) / max_records);
constexpr std::size_t max_decode_allocation_bytes = max_records * record_pool_bytes +
4 * max_save_bytes + custody_receipt_limit * (sizeof(CustodyReceipt) + 32);
void require_save(bool condition, const char* error) {
if (!condition) throw std::runtime_error(error);
@@ -86,6 +96,11 @@ public:
}
}
void allocate(std::size_t count, std::size_t size) {
require_save(count <= max_decode_allocation_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 +119,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_decode_allocation_bytes, max_decode_allocation_bytes, 64}};
bool legacy_footer_ = true;
std::uint64_t legacy_digest_ = Void::Hash::fnv1a64_offset_basis;
};
@@ -115,6 +131,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 +388,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,
"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_;
@@ -445,8 +644,8 @@ void WorldSaveCodec::validate(const World& world) {
const auto storage_index = [&](StorageId id) { return record_index(world.storages_, id); };
const auto node_index = [&](ResourceNodeId id) { return record_index(world.resource_nodes_, id); };
std::vector<ItemCounts> reserved_items(world.storages_.size());
std::vector<ItemCounts> expected_cargo(world.production_orders_.size());
std::vector<ItemCounts> reserved_items(modern ? 0 : world.storages_.size());
std::vector<ItemCounts> expected_cargo(modern ? 0 : world.production_orders_.size());
std::vector<AgentId> bed_owners;
for (std::size_t i = 0; i < world.production_orders_.size(); ++i) {
const auto& order = world.production_orders_[i];
@@ -466,6 +665,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 +765,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 +780,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 +790,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 +876,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 +894,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 +1028,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 +1051,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 +1068,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;
}
+3 -3
View File
@@ -180,8 +180,8 @@ Test CheckpointTests::test_authentic_v1_import_and_authenticated_schema_body_pai
}
auto imported = decoded(old_checkpoint(0), catalog);
auto current = encoded(*imported.world, rules);
require(static_cast<unsigned char>(current[8]) == 2 &&
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 14,
require(static_cast<unsigned char>(current[8]) == 3 &&
static_cast<unsigned char>(current[layout(current).body_begin + 8]) == 15,
"new checkpoint lacks the current schema/body pair");
auto false_legacy = current;
change(false_legacy, 8, std::uint32_t{1}); rehash(false_legacy);
@@ -211,7 +211,7 @@ Test CheckpointTests::test_round_trip_preserves_identity_and_legacy_world_bytes(
require(saved_state(*restored.world) == before && saved_state(world) == before,
"checkpoint changed the original or restored canonical state");
std::ostringstream modern(std::ios::binary);
world.write_save(modern, WorldSaveFormat::Current14);
world.write_save(modern, WorldSaveFormat::Current15);
require(bytes.substr(layout(bytes).body_begin, modern.str().size()) == modern.str(),
"checkpoint did not use the current world serialization");
require(before.substr(0, 8) == "SETTLERS" && static_cast<unsigned char>(before[8]) == 13,
+431
View File
@@ -0,0 +1,431 @@
#include "settlement/core/checkpoint.hpp"
#include "fixtures/custody_v14/fixtures.hpp"
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
std::string unhex(std::string_view hex) {
const auto digit = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
std::string result;
for (std::size_t i = 0; i < hex.size(); i += 2) result.push_back(static_cast<char>(digit(hex[i]) * 16 + digit(hex[i + 1])));
return result;
}
std::string raw(const World& world, WorldSaveFormat format = WorldSaveFormat::Current15) {
std::ostringstream stream(std::ios::binary); world.write_save(stream, format); return stream.str();
}
WorldCheckpoint load(std::string_view bytes, std::size_t workers = 1) {
const auto catalog = builtin_rule_packages();
auto result = decode_checkpoint(bytes, *catalog, workers,
workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel);
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string save(const WorldCheckpoint& saved) {
auto result = encode_checkpoint(*saved.world, saved.world_id, saved.city, saved.rules);
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
const custody_v14::Fixture& fixture(std::string_view name) {
for (const auto& entry : custody_v14::fixtures) if (entry.name == name) return entry;
throw std::runtime_error("missing historical fixture");
}
std::size_t body_begin(std::string_view bytes) {
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(), bytes.size()}).subspan(12));
return 24 + reader.readLittle<std::uint32_t>().value();
}
template<class T> void change(std::string& bytes, std::size_t offset, T value) {
Void::Binary::Writer writer(std::as_writable_bytes(std::span{bytes.data(), bytes.size()}).subspan(offset));
if constexpr(std::is_enum_v<T>) require(writer.writeLittle(static_cast<std::underlying_type_t<T>>(value)).has_value(), "mutation exceeded frame");
else require(writer.writeLittle(value).has_value(), "mutation exceeded frame");
}
void rehash(std::string& bytes) {
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
require(hasher && hasher->update(std::string_view(bytes).substr(0,bytes.size()-32)), "hash failed");
auto digest = hasher->finalize(); require(digest.has_value(), "hash finalization failed");
std::memcpy(bytes.data()+bytes.size()-32, digest->data(), 32);
}
void reject(std::string bytes, std::string_view message="authenticated malformed custody was accepted") {
rehash(bytes);
auto catalog = builtin_rule_packages();
require(!decode_checkpoint(bytes,*catalog,1,ExecutionMode::SerialReference), message);
}
struct CustodyOffsets {
std::size_t extension, agent_state, agent_timer, first_execution, receipts;
std::vector<std::size_t> node_reserved, storage_reserved;
std::vector<std::pair<std::size_t,std::size_t>> entries;
};
CustodyOffsets offsets(const World& world, const std::string& bytes) {
CustodyOffsets result{};
const auto body=body_begin(bytes);
Void::Binary::Reader prefix(std::as_bytes(std::span{bytes.data(),bytes.size()}));
const auto skip=[&](std::size_t n){require(prefix.skip(n).has_value(),"incomplete historical prefix");};
const auto count=[&]{return prefix.readLittle<std::uint32_t>().value();};
const auto route_fields=[&]{const auto n=count();skip(static_cast<std::size_t>(n)*8);};
skip(body+109+static_cast<std::size_t>(world.width())*world.height());
const auto agents=count();
for(std::uint32_t i=0;i<agents;++i){skip(25);route_fields();skip(28+4*item_type_count);route_fields();skip(14);}
const auto jobs=count();skip(static_cast<std::size_t>(jobs)*25);
const auto nodes=count();
for(std::uint32_t i=0;i<nodes;++i){result.node_reserved.push_back(prefix.position()+25);skip(39);}
const auto stores=count();
for(std::uint32_t i=0;i<stores;++i){result.storage_reserved.push_back(prefix.position()+20);skip(25);const auto items=count();skip(static_cast<std::size_t>(items)*9);}
const auto orders=count();
for(std::uint32_t i=0;i<orders;++i){skip(18);const auto materials=count();skip(static_cast<std::size_t>(materials)*13);const auto stops=count();for(std::uint32_t j=0;j<stops;++j){skip(8);route_fields();}skip(18);}
skip(37);result.extension=prefix.position();
result.first_execution=result.extension+24+8*item_type_count+9;
for(const auto& store:world.storages())result.first_execution+=8*store.items.size();
Void::Binary::Reader reader(std::as_bytes(std::span{bytes.data(),bytes.size()}));
require(reader.skip(body+109+static_cast<std::size_t>(world.width())*world.height()+4+16).has_value(),"missing agent state");
result.agent_state=reader.position();
require(reader.skip(9).has_value(),"missing agent route");
const auto route=reader.readLittle<std::uint32_t>().value();
require(reader.skip(static_cast<std::size_t>(route)*8+8).has_value(),"missing agent timer");
result.agent_timer=reader.position();
std::size_t extension_size=24+world.production_orders().size()*(12*item_type_count+1)+64*item_type_count;
for(const auto& store:world.storages()) extension_size+=store.items.size()*8;
for(const auto& agent:world.agents()) extension_size+=8*item_type_count+9+
(agent.execution?43+47*agent.execution->reservation_count:0);
result.receipts=result.extension+extension_size;
Void::Binary::Reader receipts(std::as_bytes(std::span{bytes.data(),bytes.size()}).subspan(result.receipts));
const auto receipt_count=receipts.readLittle<std::uint32_t>().value();
for(std::uint32_t i=0;i<receipt_count;++i){
const auto request=result.receipts+receipts.position();
const auto request_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(request_size).has_value(),"bad request fixture");
const auto response=result.receipts+receipts.position();
const auto result_size=receipts.readLittle<std::uint16_t>().value();require(receipts.skip(result_size).has_value(),"bad result fixture");
result.entries.emplace_back(request,response);
}
return result;
}
void legacy_reject(const World& world) {
for (auto format : {WorldSaveFormat::Legacy13, WorldSaveFormat::Current14}) {
std::ostringstream out(std::ios::binary);
bool failed = false;
try { world.write_save(out,format); } catch (const UnsupportedLegacyState&) { failed=true; }
require(failed && out.str().empty(), "unsupported projection wrote a prefix or lost typed error");
}
}
WorldCheckpoint split_carpenter() {
auto metadata=load(unhex(fixture("carpenter-output").checkpoint));
metadata.world=std::make_unique<World>(43,24,24,1,ExecutionMode::SerialReference);
auto& world=*metadata.world;world.start_scenario({2,2});
const auto a=world.add_storage({3,3},20),b=world.add_storage({8,3},20);
world.stock_storage(a,ItemType::Wood,1);world.stock_storage(b,ItemType::Wood,1);
const auto actor=world.spawn_agent({1,3});
require(world.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},actor}).status==CommandStatus::Accepted,"carpenter assignment failed");
world.queue_production({2,2},RecipeId::CraftWoodenDoor);
return metadata;
}
struct [[= Void::Testing::name("CustodyMigrationTests")]] CustodyMigrationTests : Void::Testing::Suite<CustodyMigrationTests> {
[[= Void::Testing::tag("custody-migration")]] Test authentic_historical_phases_keep_eighty_tick_projection();
[[= Void::Testing::tag("custody-migration")]] Test opening_stock_and_admission_are_reconstructed_without_receipts();
[[= Void::Testing::tag("custody-migration")]] Test modern_frames_reject_identity_balance_and_pair_corruption();
[[= Void::Testing::tag("custody-migration")]] Test cancellation_is_durable_and_legacy_refusal_is_before_output();
[[= Void::Testing::tag("custody-migration")]] Test completed_receipts_keep_retired_stock_and_order_references();
[[= Void::Testing::tag("custody-migration")]] Test single_finished_material_and_partial_return_use_modern_format();
[[= Void::Testing::tag("custody-migration")]] Test suspended_sites_and_zero_completion_use_modern_format();
[[= Void::Testing::tag("custody-mutation")]] Test authenticated_phase_and_receipt_mutations_are_rejected();
[[= Void::Testing::tag("custody-mutation")]] Test retired_zero_effect_and_bounded_receipt_fields();
[[= Void::Testing::tag("custody-migration")]] Test truncated_collection_counts_allocate_incrementally();
[[= Void::Testing::tag("custody-mutation")]] Test full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals();
[[= Void::Testing::tag("custody-mutation")]] Test admission_result_reservations_are_distinct();
[[= Void::Testing::tag("custody-mutation")]] Test result_effects_are_unique_with_retired_and_distinct_owners();
[[= Void::Testing::tag("custody-mutation")]] Test source_less_harvesting_and_reserved_return_destination_are_rejected();
};
Test CustodyMigrationTests::authentic_historical_phases_keep_eighty_tick_projection() {
for (const auto& original : custody_v14::fixtures) {
const auto bytes=unhex(original.checkpoint);
const auto digest=Void::Crypto::sha256(std::string_view(bytes));
require(digest.has_value(), "fixture hashing failed");
const auto expected_digest=unhex(original.sha256);
require(std::ranges::equal(*digest,std::as_bytes(std::span{expected_digest.data(),expected_digest.size()})), "historical fixture SHA differs");
for (auto workers : {1U,2U,6U,12U}) {
auto restored=load(bytes,workers);
require(raw(*restored.world,WorldSaveFormat::Current14)==bytes.substr(body_begin(bytes),bytes.size()-body_begin(bytes)-32), original.name);
for (std::size_t tick=0;tick<original.ticks.size();++tick) {
require(Void::Hash::fnv1a64(raw(*restored.world,WorldSaveFormat::Legacy13))==original.ticks[tick],
std::string(original.name)+" historical tick "+std::to_string(tick));
const auto modern=save(restored);
auto roundtrip=load(modern,workers);
require(save(roundtrip)==modern,"modern migration roundtrip changed canonical bytes");
restored.world->step();
roundtrip.world->step();
require(raw(*roundtrip.world)==raw(*restored.world), "modern continuation diverged");
}
}
}
}
Test CustodyMigrationTests::opening_stock_and_admission_are_reconstructed_without_receipts() {
for(const auto& original:custody_v14::fixtures) {
auto restored=load(unhex(original.checkpoint)); const auto& world=*restored.world;
world.validate_custody();
require(world.custody_receipts().empty(),"migration invented historical receipts");
const auto& actor=world.agents().front();
require(actor.execution && actor.next_admission==2 && actor.execution->next_operation==1,"active legacy admission was not marked consumed");
CustodyRequest retry;retry.key={CustodyKeyKind::Admission,actor.id,1};
require(restored.world->custody_request(retry).status==CustodyStatus::Stale,"migrated admission was executed again");
if(original.name=="cabin-working") {
const auto& input=world.production_orders().front().input;
require(input.item_count(ItemType::Plank)==3&&input.item_count(ItemType::StoneBlock)==2&&actor.inventory.empty(),"implicit worksite stock was not restored");
require(world.item_balances()[2].opening==3&&world.item_balances()[3].opening==2,"opening was measured before worksite restoration");
}
if(original.name.starts_with("direct-")) require(world.production_orders().front().input.empty(),"direct recipe debited input during migration");
}
}
Test CustodyMigrationTests::modern_frames_reject_identity_balance_and_pair_corruption() {
auto restored=load(unhex(fixture("cabin-before-pickup").checkpoint));
const auto good=save(restored), before=raw(*restored.world);
const auto extension=body_begin(good)+raw(*restored.world,WorldSaveFormat::Current14).size();
for(auto offset:{extension,extension+8,extension+16}) {
auto bad=good;change(bad,offset,std::uint64_t{0});reject(std::move(bad));
}
auto duplicate=good;change(duplicate,extension+24+8,std::uint64_t{1});reject(std::move(duplicate));
auto bad_balance=good; // Last 11*64 bytes before receipt count are the balance ledger.
const auto balance=good.size()-32-4-item_type_count*64;
change(bad_balance,balance,std::uint64_t{1});reject(std::move(bad_balance));
for(auto schema:{1U,2U}){auto bad=good;change(bad,8,schema);reject(std::move(bad));}
auto false_three=unhex(fixture("cabin-working").checkpoint);change(false_three,8,3U);reject(std::move(false_three));
require(raw(*restored.world)==before,"decoding corrupt candidate mutated active owner");
}
Test CustodyMigrationTests::cancellation_is_durable_and_legacy_refusal_is_before_output() {
for(auto name:{"cabin-between-stops","cabin-to-site","cabin-working"}) {
auto restored=load(unhex(fixture(name).checkpoint));
const auto id=restored.world->production_orders().front().id;
require(restored.world->cancel_production(id)==CommandStatus::Accepted,"cancel refused historical active construction");
legacy_reject(*restored.world);
const auto bytes=save(restored);auto loaded=load(bytes);
require(save(loaded)==bytes,"return cargo lost in modern checkpoint");
for(int tick=0;tick<80;++tick){restored.world->step();loaded.world->step();require(raw(*restored.world)==raw(*loaded.world),"return differed after restore");}
}
}
Test CustodyMigrationTests::completed_receipts_keep_retired_stock_and_order_references() {
auto restored=load(unhex(fixture("cabin-working").checkpoint));
require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"fixture active order removal failed");
require(!restored.world->custody_receipts().empty(),"fixture did not create cancellation receipt");
const auto remembered=restored.world->custody_receipts().back();
for(int tick=0;tick<80;++tick)restored.world->step();
const auto bytes=save(restored);auto loaded=load(bytes);
require(loaded.world->custody_request(remembered->request)==remembered->result,"historical result was lost after referenced stock/order retirement");
}
Test CustodyMigrationTests::single_finished_material_and_partial_return_use_modern_format() {
for (auto item : {ItemType::Plank, ItemType::StoneBlock}) {
auto metadata = load(unhex(fixture("cabin-working").checkpoint));
auto world = std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
const auto first=world->add_storage({3,3},20), second=world->add_storage({8,3},20);
world->stock_storage(first,item,1);
world->stock_storage(second,ItemType::Plank,item==ItemType::Plank?2:3);
world->stock_storage(second,ItemType::StoneBlock,item==ItemType::StoneBlock?1:2);
static_cast<void>(world->spawn_agent({1,3}));world->queue_production({14,3},RecipeId::BuildCabin);
for(int tick=0;tick<10&&world->agents().front().inventory.empty();++tick)world->step();
require(world->agents().front().inventory.item_count(item)==1,"fixture missed single-item pickup");
require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"single cargo cancellation failed");
legacy_reject(*world);metadata.world=std::move(world);
const auto encoded=save(metadata);require(save(load(encoded))==encoded,"single finished material did not roundtrip");
}
for (bool partial : {false,true}) {
auto restored=load(unhex(fixture("cabin-working").checkpoint));
restored.world->stock_storage(restored.world->storages()[0].id,ItemType::Wood,partial?19:20);
restored.world->stock_storage(restored.world->storages()[1].id,ItemType::Wood,20);
require(restored.world->cancel_production(restored.world->production_orders().front().id)==CommandStatus::Accepted,"full-store cancellation failed");
for(int tick=0;tick<40;++tick)restored.world->step();
require(restored.world->agents().front().inventory.item_count(ItemType::Plank)==(partial?2U:3U),"return did not respect exact available capacity");
require(restored.world->agents().front().inventory.item_count(ItemType::StoneBlock)==2,"mixed return dropped second item");
legacy_reject(*restored.world);const auto encoded=save(restored);require(save(load(encoded))==encoded,"partial or blocked return did not roundtrip");
}
}
Test CustodyMigrationTests::suspended_sites_and_zero_completion_use_modern_format() {
for(bool bed:{false,true}) {
auto metadata=load(unhex(fixture("cabin-working").checkpoint));
auto world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
world->start_scenario({2,2});const auto storage=world->add_storage({3,3},20);
world->stock_storage(storage,ItemType::Wood,bed?1:2);static_cast<void>(world->spawn_agent({1,3}));
if(bed)require(world->apply_command({1,1,CommandKind::PlaceBed,{6,3}}).status==CommandStatus::Accepted,"bed placement failed");
else world->queue_production({6,3},RecipeId::BuildLoom);
for(int tick=0;tick<45;++tick)world->step();
require(world->cancel_production(world->production_orders().front().id)==CommandStatus::Accepted,"residual site cancellation failed");
require(world->production_orders().front().suspended,"residual site was not suspended");
legacy_reject(*world);metadata.world=std::move(world);
const auto encoded=save(metadata);auto loaded=load(encoded);require(save(loaded)==encoded,"suspended site did not roundtrip");
require(loaded.world->resume_production(loaded.world->production_orders().front().id)==CommandStatus::Accepted,"suspended site cannot resume after restore");
}
auto metadata=load(unhex(fixture("cabin-working").checkpoint));
auto encoded=save(metadata);
// The historical prefix is kept in raw15. Parse its first agent timer rather
// than relying on native object layout; this is a valid pending completion.
const auto body=body_begin(encoded);
Void::Binary::Reader reader(std::as_bytes(std::span{encoded.data(),encoded.size()}).subspan(body));
require(reader.skip(20).has_value(),"missing dimensions");
const auto width=reader.readLittle<std::uint32_t>().value(),height=reader.readLittle<std::uint32_t>().value();
require(reader.skip(81+static_cast<std::size_t>(width)*height+4+25).has_value(),"missing first agent");
const auto route=reader.readLittle<std::uint32_t>().value();
require(reader.skip(static_cast<std::size_t>(route)*8+8).has_value(),"missing first route");
change(encoded,body+reader.position(),std::uint32_t{0});rehash(encoded);
auto pending=load(encoded);legacy_reject(*pending.world);
require(save(pending)==encoded,"pending zero timer did not roundtrip");
pending.world->step();pending.world->validate_custody();
}
Test CustodyMigrationTests::authenticated_phase_and_receipt_mutations_are_rejected() {
auto metadata=load(unhex(fixture("cabin-before-pickup").checkpoint));
metadata.world->step();
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
require(location.entries.size()==1,"pickup should produce one retained operation");
require(save(load(good))==good,"authentic active pickup original was rejected");
const auto [request,result]=location.entries.front();
auto wrong_transfer=good;
change(wrong_transfer,location.extension+16,std::uint64_t{3});
change(wrong_transfer,result+3,std::uint64_t{2});reject(std::move(wrong_transfer),"mismatched receipt transfer accepted");
auto terminal=good;change(terminal,result+13,std::uint8_t{1});reject(std::move(terminal),"terminal historical receipt for active transfer accepted");
auto future=good;change(future,request+11,std::numeric_limits<std::uint64_t>::max());reject(std::move(future),"future live operation accepted");
auto source=good;change(source,request+29,std::numeric_limits<std::uint64_t>::max());reject(std::move(source),"out-of-range historical source accepted");
auto fetching=load(unhex(fixture("cabin-before-pickup").checkpoint));
const auto fetching_bytes=save(fetching);const auto fetching_location=offsets(*fetching.world,fetching_bytes);
require(save(load(fetching_bytes))==fetching_bytes,"authentic fetching original was rejected");
auto travelling=fetching_bytes;change(travelling,fetching_location.agent_state,AgentState::Travelling);
reject(std::move(travelling),"delivery actor with remaining source stops accepted as Travelling");
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
static_cast<void>(metadata.world->spawn_agent({1,3}));
const auto idle_storage=metadata.world->add_storage({3,3},10);
const auto idle=save(metadata); const auto idle_locations=offsets(*metadata.world,idle);
for(auto state:{AgentState::Travelling,AgentState::Working,AgentState::Gathering,AgentState::FetchingMaterials}) {
auto bad=idle;change(bad,idle_locations.agent_state,state);reject(std::move(bad));
}
auto timer=idle;change(timer,idle_locations.agent_timer,std::uint32_t{1});reject(std::move(timer),"idle resident with work timer accepted");
auto storage=idle;change(storage,idle_locations.agent_timer+12,idle_storage);reject(std::move(storage),"idle resident with live storage link accepted");
}
Test CustodyMigrationTests::retired_zero_effect_and_bounded_receipt_fields() {
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
for(int tick=0;tick<8;++tick)metadata.world->step();
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
require(!location.entries.empty(),"meal did not produce historical result");
const auto [request,result]=location.entries.back();
auto loaded=load(good);
const auto receipt=metadata.world->custody_receipts().back();
require(receipt->result.effect_count==1&&receipt->result.effects[0].count==0,"terminal consumption lost retired zero-count effect");
require(loaded.world->custody_request(receipt->request)==receipt->result,"zero-count historical effect changed after restore");
auto oversized=good;change(oversized,request,std::uint16_t{1025});reject(std::move(oversized));
auto too_many=good;change(too_many,location.receipts,std::uint32_t{4097});reject(std::move(too_many));
auto bad_item=good;change(bad_item,result+2+12+17,ItemType::None);reject(std::move(bad_item));
auto bad_owner=good;change(bad_owner,result+2+12,OwnerKind::None);reject(std::move(bad_owner));
auto count=good;change(count,result+2+10,std::uint8_t{12});reject(std::move(count));
}
Test CustodyMigrationTests::truncated_collection_counts_allocate_incrementally() {
auto original=unhex(fixture("cabin-before-pickup").checkpoint);
const auto begin=body_begin(original);
std::string body=original.substr(begin,original.size()-begin-32);
constexpr std::size_t agents_count=109+20*8;
body.resize(agents_count+4);
for(auto count:{1'000'000U,1'000'001U}) {
change(body,agents_count,count);
std::istringstream input(body,std::ios::binary);
bool failed=false;
try{static_cast<void>(World::read_save(input,1,ExecutionMode::SerialReference));}
catch(const std::runtime_error&){failed=true;}
require(failed,"truncated huge agent declaration was accepted");
}
// Many byte-light historical agents remain valid despite larger modern
// in-memory Agent records; the wire ceiling does not become a sizeof cap.
World world(43,3,3,1,ExecutionMode::SerialReference);
for(int i=0;i<2000;++i)static_cast<void>(world.spawn_agent({1,1}));
const auto bytes=raw(world,WorldSaveFormat::Current14);
std::istringstream input(bytes,std::ios::binary);
auto loaded=World::read_save(input,1,ExecutionMode::SerialReference);
require(loaded->agents().size()==2000&&raw(*loaded,WorldSaveFormat::Current14)==bytes,"byte-light history failed migration");
}
Test CustodyMigrationTests::full_receipt_ring_preserves_exact_results_and_evicts_old_ordinals() {
auto metadata=load(unhex(fixture("meal-eating").checkpoint));
metadata.world=std::make_unique<World>(43,20,8,1,ExecutionMode::SerialReference);
const auto storage=metadata.world->add_storage({3,3},2050);
metadata.world->stock_storage(storage,ItemType::Wood,2050);
static_cast<void>(metadata.world->spawn_agent({3,3}));
for(int i=0;i<2050;++i)metadata.world->queue_production({3,3},RecipeId::SawPlank);
for(int tick=0;tick<30000&&metadata.world->custody_receipts().size()<4096;++tick)metadata.world->step();
require(metadata.world->custody_receipts().size()==4096,"real production did not fill global receipt ring");
const auto remembered=metadata.world->custody_receipts().front();
const auto full=save(metadata);auto loaded=load(full);
require(save(loaded)==full&&loaded.world->custody_receipts().size()==4096,"full receipt ring was truncated or reordered");
require(full.size()<2*1024*1024,"typed receipt ring exceeded its proven wire budget");
require(loaded.world->custody_request(remembered->request)==remembered->result,"full ring lost exact replay");
auto conflicting=remembered->request;conflicting.destination=0;
require(loaded.world->custody_request(conflicting).status==CustodyStatus::Conflict,"exact request conflict was not detected");
for(int tick=0;tick<30;++tick)loaded.world->step();
require(loaded.world->custody_request(remembered->request).status==CustodyStatus::Stale,"evicted admission was eligible for replay");
const auto wrapped=save(loaded);auto copy=load(wrapped);
require(save(copy)==wrapped&&copy.world->custody_request(remembered->request).status==CustodyStatus::Stale,"wrapped ring changed order or stale fence on restore");
}
Test CustodyMigrationTests::admission_result_reservations_are_distinct() {
auto metadata=split_carpenter();metadata.world->step();
require(metadata.world->custody_receipts().size()==1,"expected real admission before pickup");
const auto receipt=metadata.world->custody_receipts().front();
require(receipt->request.key.kind==CustodyKeyKind::Admission&&receipt->result.reservation_count==4,"split carpenter admission lost its claims");
for(std::size_t i=1;i<receipt->result.reservation_count;++i)require(receipt->result.reservations[i-1]<receipt->result.reservations[i],"issued reservation order is not canonical");
const auto good=save(metadata); const auto location=offsets(*metadata.world,good);
auto duplicate=good;
change(duplicate,location.entries.front().second+14+8,receipt->result.reservations[0]);
reject(std::move(duplicate),"duplicate historical admission reservation accepted");
}
Test CustodyMigrationTests::result_effects_are_unique_with_retired_and_distinct_owners() {
auto metadata=split_carpenter();
for(int tick=0;tick<80&&metadata.world->production_orders().front().state!=JobState::Completed;++tick)metadata.world->step();
const auto receipt=metadata.world->custody_receipts().back();
require(receipt->request.operation==CustodyOperation::Complete,"carpenter did not reach actual completion");
require(receipt->result.effect_count==2,"split input emitted repeated final stock effects");
require(receipt->result.effects[0].owner.kind==OwnerKind::Production&&receipt->result.effects[0].count==0&&
receipt->result.effects[1].owner.kind==OwnerKind::Resident&&receipt->result.effects[1].count==1,"completion lost retired input or distinct output owner");
const auto good=save(metadata);const auto location=offsets(*metadata.world,good);
auto restored=load(good);
require(save(restored)==good&&restored.world->custody_request(receipt->request)==receipt->result,"mixed-owner historical result did not roundtrip");
const auto first=location.entries.back().second+14+8*receipt->result.reservation_count;
auto duplicate=good;duplicate.replace(first+22,22,good.substr(first,22));
reject(std::move(duplicate),"duplicate historical effect accepted");
}
Test CustodyMigrationTests::source_less_harvesting_and_reserved_return_destination_are_rejected() {
auto gathering=load(unhex(fixture("harvest-gathering").checkpoint));
const auto original=save(gathering); const auto location=offsets(*gathering.world,original);
require(save(load(original))==original,"authentic harvesting original was rejected");
auto missing=original;
change(missing,location.agent_timer+4,std::uint64_t{0});
change(missing,location.first_execution+17,std::uint64_t{0});
change(missing,location.node_reserved.front(),std::uint32_t{0});
// Remove the source claim together with its cached worker count, keeping the
// real destination capacity. A mere cache mismatch must not explain refusal.
require(gathering.world->agents().front().execution->reservations[0].kind==ReservationKind::Harvest,"source claim fixture changed");
missing.replace(location.first_execution+43,47,47,'\0');
reject(std::move(missing),"Gathering without source or source claim accepted");
auto returning=load(unhex(fixture("cabin-working").checkpoint));
require(returning.world->cancel_production(returning.world->production_orders().front().id)==CommandStatus::Accepted,"return fixture cancellation failed");
const auto good=save(returning);const auto cancelled=offsets(*returning.world,good);
require(save(load(good))==good,"authentic cancellation original was rejected");
require(returning.world->agents().front().execution->reservation_count==0,"cancel did not release all reservations");
Void::Binary::Reader counter(std::as_bytes(std::span{good.data(),good.size()}).subspan(cancelled.extension+8));
const auto next=counter.readLittle<std::uint64_t>().value();
const auto destination=returning.world->storages().front().id;
auto reserved=good;
change(reserved,cancelled.extension+8,next+1);
change(reserved,cancelled.first_execution+25,destination);
change(reserved,cancelled.first_execution+42,std::uint8_t{1});
change(reserved,cancelled.storage_reserved.front(),std::uint32_t{1});
std::string capacity(47,'\0');
change(capacity,0,next);change(capacity,8,ReservationKind::Capacity);
change(capacity,9,OwnerKind::Storage);change(capacity,10,destination);change(capacity,27,std::uint32_t{1});
reserved.insert(cancelled.first_execution+43,capacity);
change(reserved,16,static_cast<std::uint64_t>(reserved.size()-32-body_begin(reserved)));
reject(std::move(reserved),"Returning retained a destination and matching capacity reservation");
}
} // namespace
+416
View File
@@ -0,0 +1,416 @@
#include "settlement/core/world.hpp"
#include <Void/Testing/Suite.hpp>
#include <stdexcept>
#include <sstream>
#include <limits>
#include <chrono>
#include <algorithm>
#include <iostream>
namespace {
using namespace settlement;
using Void::Testing::Test;
void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
void ticks(World& world, int count) { for (int i = 0; i < count; ++i) { world.step(); world.validate_custody(); } }
std::unique_ptr<World> cabin(std::uint32_t stock = 3) {
auto w = std::make_unique<World>(7, 32, 32, 1, ExecutionMode::SerialReference);
auto storage = w->add_storage({3, 3}, 50);
w->stock_storage(storage, ItemType::Plank, stock);
w->stock_storage(storage, ItemType::StoneBlock, 2);
(void)w->spawn_agent({1, 3});
w->queue_production({16, 3}, RecipeId::BuildCabin);
return w;
}
struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::Suite<CustodyTests> {
[[= Void::Testing::tag("custody")]] Test ownership_delivery_and_consumption();
[[= Void::Testing::tag("custody")]] Test cancel_site_returns_all_types();
[[= Void::Testing::tag("custody")]] Test split_merge_and_snapshot();
[[= Void::Testing::tag("custody")]] Test exact_receipt_and_conflict();
[[= Void::Testing::tag("custody")]] Test original_colony_continuous_balance();
[[= Void::Testing::tag("custody")]] Test five_sources();
[[= Void::Testing::tag("custody")]] Test retained_result_uniqueness_and_canonical_operands();
[[= Void::Testing::tag("custody")]] Test active_terminal_and_delivery_phase_are_rejected();
[[= Void::Testing::tag("custody")]] Test harvest_source_and_return_capacity_are_required_by_phase();
[[= Void::Testing::tag("custody")]] Test merged_carpentry_effects_keep_distinct_owners();
[[= Void::Testing::tag("custody")]] Test blocked_return_retains_every_item();
[[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume();
[[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction();
[[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance();
[[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims();
[[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion();
[[= Void::Testing::tag("custody")]] Test resident_and_job_id_allocation_is_checked();
[[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry();
[[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics();
};
Test CustodyTests::ownership_delivery_and_consumption() {
auto w = cabin();
const auto plank = w->storages()[0].items[0].id;
ticks(*w, 2);
require(w->agents()[0].inventory.stack_id(ItemType::Plank) == plank, "whole pickup changed ID");
for (int i = 0; i < 20 && w->agents()[0].state != AgentState::Working; ++i) ticks(*w, 1);
require(w->production_orders()[0].input.stack_id(ItemType::Plank) == plank, "site lost ID");
require(w->production_orders()[0].input.item_count(ItemType::Plank) == 3, "site lost physical count");
ticks(*w, 40);
require(w->production_orders()[0].state == JobState::Completed, "construction incomplete");
require(w->item_balances()[2].installation == 3, "installation sink missing");
}
Test CustodyTests::cancel_site_returns_all_types() {
auto w = cabin();
ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
w->validate_custody();
require(w->agents()[0].state == AgentState::Returning && !w->legacy_representable(), "cancel phase lost");
ticks(*w, 40);
require(w->agents()[0].inventory.empty() && w->storages()[0].item_count(ItemType::Plank) == 3 &&
w->storages()[0].item_count(ItemType::StoneBlock) == 2, "return lost cargo");
}
Test CustodyTests::split_merge_and_snapshot() {
auto w = cabin(5);
const auto original = w->storages()[0].items[0].id;
auto snapshot = w->capture();
ticks(*w, 2);
require(w->storages()[0].items[0].id == original && w->agents()[0].inventory.stack_id(ItemType::Plank) != original, "split identity wrong");
require(snapshot->storages()[0].item_count(ItemType::Plank) == 5 && snapshot->custody_receipts().empty(), "snapshot mutated");
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
ticks(*w, 10);
require(w->storages()[0].items[0].id == original && w->storages()[0].item_count(ItemType::Plank) == 5, "merge identity wrong");
}
Test CustodyTests::exact_receipt_and_conflict() {
auto w = cabin(); ticks(*w, 1);
auto receipt = *w->custody_receipts().front();
require(w->custody_request(receipt.request) == receipt.result, "exact retry differed");
++receipt.request.destination;
require(w->custody_request(receipt.request).status == CustodyStatus::Conflict, "changed retry accepted");
receipt.request.key.ordinal += 100;
require(w->custody_request(receipt.request).status == CustodyStatus::Future, "future retry accepted");
ticks(*w, 60);
}
Test CustodyTests::original_colony_continuous_balance() {
auto w = make_first_colony(1, BedConstructionMode::Staged, ExecutionMode::SerialReference);
w->validate_custody();
ticks(*w, 1000);
}
Test CustodyTests::five_sources() {
auto w = std::make_unique<World>(7, 32, 32, 1, ExecutionMode::SerialReference);
for (int i = 0; i < 5; ++i) {
const auto store = w->add_storage({3 + i, 3}, 10);
w->stock_storage(store, i < 3 ? ItemType::Plank : ItemType::StoneBlock, 1);
}
(void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin);
ticks(*w, 1);
require(w->custody_receipts()[0]->request.line_count == 5, "admission omitted sources");
ticks(*w, 80);
require(w->production_orders()[0].state == JobState::Completed, "five-source cabin incomplete");
const auto completion = std::find_if(w->custody_receipts().begin(), w->custody_receipts().end(),
[](const auto& receipt) { return receipt->request.operation == CustodyOperation::Complete; });
require(completion != w->custody_receipts().end() && (*completion)->result.effect_count == 2,
"merged site inputs repeated the same final stack outcome");
require((*completion)->result.effects[0].item == ItemType::Plank && (*completion)->result.effects[1].item == ItemType::StoneBlock &&
(*completion)->result.effects[0].count == 0 && (*completion)->result.effects[1].count == 0,
"consumed outcomes lost first material order or zero counts");
std::ostringstream saved; w->write_save(saved, WorldSaveFormat::Current15);
std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
require(resumed->custody_request((*completion)->request) == (*completion)->result, "merged historical effect changed after restore");
}
Test CustodyTests::blocked_return_retains_every_item() {
auto w = cabin(); ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
auto& store = const_cast<Storage&>(w->storages()[0]); store.capacity = 1;
ticks(*w, 40);
require(w->agents()[0].state == AgentState::Returning && w->agents()[0].execution &&
w->agents()[0].execution->blocked == CustodyStatus::NoDestination, "blocked return lost execution");
require(w->agents()[0].inventory.item_count(ItemType::Plank) == 2 &&
w->agents()[0].inventory.item_count(ItemType::StoneBlock) == 2, "partial return lost items");
auto id = w->add_storage({4, 3}, 20);
ticks(*w, 20);
require(w->agents()[0].inventory.empty() && w->find_storage(id)->total_items() == 4, "unblocked return incomplete");
}
Test CustodyTests::suspended_bed_and_loom_resume() {
World w(9, 20, 20, 1, ExecutionMode::SerialReference);
const auto store = w.add_storage({2, 2}, 30);
w.stock_storage(store, ItemType::Wood, 4); w.stock_storage(store, ItemType::Cloth, 2);
const auto actor = w.spawn_agent({2, 2}); (void)actor; w.start_scenario({8, 8});
require(w.apply_command({1, 1, CommandKind::PlaceBed, {4, 2}}).status == CommandStatus::Accepted, "bed placement refused");
const auto id = w.production_orders()[0].id;
for (int i = 0; i < 80 && w.find_production(id)->bed_stage == BedStage::Foundation; ++i) ticks(w, 1);
require(w.find_production(id)->bed_stage == BedStage::Bedding, "bed foundation absent");
require(w.cancel_production(id) == CommandStatus::Accepted && w.find_production(id)->suspended, "partial bed not suspended");
ticks(w, 20); require(!w.legacy_representable(), "suspended bed projected");
require(w.resume_production(id) == CommandStatus::Accepted, "resume refused");
ticks(w, 100); require(w.find_production(id)->state == JobState::Completed, "bed resumed wrong stage");
require(w.item_balances()[0].installation == 1 && w.item_balances()[5].installation == 2, "bed installed twice");
require(w.cancel_production(id) == CommandStatus::Busy, "completed bed canceled");
w.queue_production({6, 2}, RecipeId::WeaveCloth); const auto loom = w.production_orders().back().id;
require(w.cancel_production(loom) == CommandStatus::Accepted && w.find_production(loom)->suspended, "loom not retained");
w.stock_storage(store, ItemType::Flax, 1);
require(w.resume_production(loom) == CommandStatus::Accepted, "loom resume refused");
ticks(w, 60); require(w.find_storage(store)->item_count(ItemType::Cloth) == 1, "loom failed after resume");
}
Test CustodyTests::admission_exhaustion_and_receipt_eviction() {
auto w = cabin();
auto& actor = const_cast<Agent&>(w->agents()[0]); actor.next_admission = std::numeric_limits<std::uint64_t>::max();
ticks(*w, 2);
require(!actor.execution && w->custody_receipts().empty() && w->storages()[0].items[0].reserved == 0, "exhausted admission mutated stock");
World loom(1, 16, 16, 1, ExecutionMode::SerialReference);
const auto store = loom.add_storage({2, 2}, 4000); loom.stock_storage(store, ItemType::Flax, 3000);
(void)loom.spawn_agent({3, 2}); loom.queue_production({3, 2}, RecipeId::WeaveCloth);
loom.step(); auto first = *loom.custody_receipts()[0]; auto snapshot = loom.capture();
for (int i = 0; i < 26000; ++i) loom.step();
loom.validate_custody();
require(loom.custody_receipts().size() == custody_receipt_limit &&
loom.custody_request(first.request).status == CustodyStatus::Stale, "evicted admission not stale");
require(snapshot->custody_receipts()[0]->request == first.request && snapshot->custody_receipts()[0]->result == first.result,
"retained snapshot receipt mutated");
for (const auto& receipt : loom.custody_receipts()) require(loom.custody_request(receipt->request) == receipt->result, "retained replay differed");
}
Test CustodyTests::recipes_meals_and_harvest_balance() {
World w(1, 20, 20, 1, ExecutionMode::SerialReference);
const auto store = w.add_storage({2, 2}, 100);
const auto pantry = w.add_storage({2, 3}, 20, StorageKind::Pantry);
w.stock_storage(store, ItemType::Wood, 10); w.stock_storage(store, ItemType::Stone, 3);
w.stock_storage(pantry, ItemType::Berries, 4);
(void)w.spawn_agent({2, 2}); (void)w.add_resource_node({3, 3}, ItemType::Wood, 5);
w.queue_production({4, 2}, RecipeId::SawPlank); w.queue_production({5, 2}, RecipeId::CutStoneBlock);
w.enable_hunger(); ticks(w, 300);
require(w.meals_eaten() > 0 && w.item_balances()[0].harvest == 5 && w.item_balances()[0].recipe_input == 1 &&
w.item_balances()[2].recipe_output == 1 && w.item_balances()[3].recipe_output == 1, "recipe/source/sink path omitted");
}
Test CustodyTests::snapshot_metrics() {
for (bool full : {false, true}) {
World w(1, 512, 512, 1, ExecutionMode::SerialReference);
if (full) {
auto store = w.add_storage({1, 1}, 4000); w.stock_storage(store, ItemType::Flax, 3000);
(void)w.spawn_agent({2, 1}); w.queue_production({2, 1}, RecipeId::WeaveCloth);
for (int i = 0; i < 26000; ++i) w.step();
}
while (w.agents().size() < 500) (void)w.spawn_agent({1, 1});
for (int i = 0; i < 1000; ++i) {
auto store = w.add_storage({i % 500, i / 500 + 5}, 1000);
for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast<ItemType>(j) != ItemType::Berries)
w.stock_storage(store, static_cast<ItemType>(j), 1);
}
while (w.production_orders().size() < 2000) {
const auto i = static_cast<std::int32_t>(w.production_orders().size());
w.queue_production({i % 100 + 3, i / 100 + 10}, RecipeId::SawPlank);
}
w.validate_custody();
std::vector<double> samples;
for (int i = 0; i < 101; ++i) {
const auto begin = std::chrono::steady_clock::now(); auto snapshot = w.capture();
samples.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
}
std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes);
std::ostringstream modern; w.write_save(modern, WorldSaveFormat::Current15);
std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size()
<< " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size()
<< " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n';
std::vector<double> validation, serialization, advancement;
for (int i = 0; i < 21; ++i) {
auto begin = std::chrono::steady_clock::now(); w.validate_custody();
validation.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
begin = std::chrono::steady_clock::now(); std::ostringstream encoded; w.write_save(encoded, WorldSaveFormat::Current15);
serialization.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
begin = std::chrono::steady_clock::now(); w.step();
advancement.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count());
}
w.validate_custody();
for (auto pair : {std::pair{"validate", &validation}, std::pair{"serialize15", &serialization}, std::pair{"step", &advancement}}) {
std::sort(pair.second->begin(), pair.second->end());
std::cout << "custody metrics initial_receipts=" << (full ? 4096 : 0) << ' ' << pair.first
<< "_ms_p50=" << (*pair.second)[10] << " p95=" << (*pair.second)[19] << '\n';
}
}
}
Test CustodyTests::rejects_missing_execution_and_claims() {
auto w = cabin(); ticks(*w, 1);
const auto rejects = [&] { try { w->validate_custody(); } catch (const std::runtime_error&) { return true; } return false; };
auto& actor = const_cast<Agent&>(w->agents()[0]); auto execution = actor.execution;
actor.execution.reset(); require(rejects(), "active actor without execution accepted"); actor.execution = execution;
actor.execution->reservations[0] = {}; require(rejects(), "missing material reservation accepted"); actor.execution = execution;
actor.execution->reservations[1].id = actor.execution->reservations[0].id;
require(rejects(), "duplicate claim ID accepted"); actor.execution = execution;
auto& order = const_cast<ProductionOrder&>(w->production_orders()[0]); ++order.materials[0].count;
require(rejects(), "different recipe quantity accepted"); --order.materials[0].count;
w->validate_custody();
}
Test CustodyTests::modern_roundtrip_cancel_and_exact_retry() {
auto w = cabin(); ticks(*w, 16);
require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
std::ostringstream encoded; w->write_save(encoded, WorldSaveFormat::Current15);
std::istringstream input(encoded.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
for (const auto& receipt : w->custody_receipts()) require(resumed->custody_request(receipt->request) == receipt->result, "restored exact receipt differed");
std::ostringstream legacy;
bool refused = false; try { w->write_save(legacy); } catch (const UnsupportedLegacyState&) { refused = true; }
require(refused && legacy.str().empty(), "legacy refusal wrote bytes");
for (int i = 0; i < 40; ++i) {
ticks(*w, 1); ticks(*resumed, 1);
std::ostringstream a,b; w->write_save(a, WorldSaveFormat::Current15); resumed->write_save(b, WorldSaveFormat::Current15);
require(a.str() == b.str(), "modern return continuation changed");
}
}
Test CustodyTests::persistent_counter_boundaries_and_pending_completion() {
const auto restored_counter = [](const World& world, std::size_t counter, std::uint64_t value) {
std::ostringstream old, modern;
world.write_save(old, WorldSaveFormat::Current14); world.write_save(modern, WorldSaveFormat::Current15);
auto bytes = modern.str(); const auto offset = old.str().size() + counter * 8;
require(offset + 8 <= bytes.size(), "custody extension missing");
for (std::size_t i = 0; i < 8; ++i) bytes[offset + i] = static_cast<char>((value >> (i * 8)) & 255U);
std::istringstream input(bytes); return World::read_save(input, 1, ExecutionMode::SerialReference);
};
auto initial = cabin();
for (std::size_t counter = 0; counter < 3; ++counter) {
bool invalid = false; try { auto ignored = restored_counter(*initial, counter, 0); } catch (const std::runtime_error&) { invalid = true; }
require(invalid, "zero durable highwater accepted");
if (counter == 0) continue;
auto exhausted = restored_counter(*initial, counter, std::numeric_limits<std::uint64_t>::max());
ticks(*exhausted, 3);
require(!exhausted->agents()[0].execution && exhausted->custody_receipts().empty() &&
exhausted->storages()[0].items[0].reserved == 0, "exhausted admission acquired claims");
}
World saw(1, 10, 10, 1, ExecutionMode::SerialReference);
const auto store = saw.add_storage({2, 2}, 10); saw.stock_storage(store, ItemType::Wood, 1);
(void)saw.spawn_agent({3, 2}); saw.queue_production({3, 2}, RecipeId::SawPlank);
auto exhausted = restored_counter(saw, 0, std::numeric_limits<std::uint64_t>::max());
ticks(*exhausted, 12);
const auto& actor = exhausted->agents()[0];
require(actor.state == AgentState::Working && actor.work_remaining == 0 && actor.execution->blocked == CustodyStatus::Exhausted,
"completion did not preserve pending zero timer");
require(exhausted->storages()[0].item_count(ItemType::Wood) == 1 && exhausted->storages()[0].item_count(ItemType::Plank) == 0,
"refused completion partially consumed input");
const auto ordinal = actor.execution->next_operation;
ticks(*exhausted, 3);
require(actor.work_remaining == 0 && actor.execution->next_operation == ordinal + 3 && !exhausted->legacy_representable(),
"pending retry underflowed timer or reused ordinal");
std::ostringstream saved; exhausted->write_save(saved, WorldSaveFormat::Current15);
std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference);
ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero");
}
Test CustodyTests::resident_and_job_id_allocation_is_checked() {
const auto bytes = [](const World& world) { std::ostringstream stream; world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); };
for (std::size_t kind = 0; kind < 2; ++kind) {
World empty(1, 10, 10, 1, ExecutionMode::SerialReference);
auto encoded = bytes(empty);
// Signature/version/seed/dimensions, five u64 counters, hunger flag.
const std::size_t offset = 28 + 5 * 8 + 1 + kind * 8;
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = static_cast<char>(255);
std::istringstream input(encoded); auto restored = World::read_save(input, 1, ExecutionMode::SerialReference);
const auto before = bytes(*restored);
bool exhausted = false;
try { if (kind == 0) (void)restored->spawn_agent({1,1}); else (void)restored->add_job({1,1}, 1); }
catch (const std::overflow_error&) { exhausted = true; }
require(exhausted && bytes(*restored) == before, "exhausted resident/job allocation changed state");
for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = 0;
bool rejected = false; try { std::istringstream zero(encoded); auto ignored = World::read_save(zero,1,ExecutionMode::SerialReference); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected, "zero resident/job counter accepted");
const auto valid_before = bytes(empty);
try { if (kind == 0) (void)empty.spawn_agent({-1,-1}); else (void)empty.add_job({1,1}, 0); }
catch (const std::invalid_argument&) {}
require(bytes(empty) == valid_before, "invalid insertion consumed ID");
}
World idle(1, 10, 10, 1, ExecutionMode::SerialReference); (void)idle.spawn_agent({1,1});
const_cast<Agent&>(idle.agents()[0]).work_remaining = 1;
bool rejected = false; try { idle.validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
require(rejected, "idle timer escaped phase validation");
}
Test CustodyTests::retained_result_uniqueness_and_canonical_operands() {
auto w = cabin(); ticks(*w, 60);
require(!w->agents()[0].execution, "test requires retired transfer");
auto& receipts = const_cast<std::vector<std::shared_ptr<const CustodyReceipt>>&>(w->custody_receipts());
const auto rejects = [&](std::size_t index, auto mutation) {
const auto original = receipts[index];
auto modified = std::make_shared<CustodyReceipt>(*original);
mutation(*modified); receipts[index] = modified;
bool rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "noncanonical historical result accepted"); w->validate_custody();
};
rejects(0, [](auto& r) { r.result.reservations[1] = r.result.reservations[0]; });
rejects(0, [](auto& r) { std::swap(r.result.reservations[0], r.result.reservations[1]); });
rejects(0, [](auto& r) { r.request.source = 1; });
const auto completion = std::find_if(receipts.begin(), receipts.end(), [](const auto& r) { return r->request.operation == CustodyOperation::Complete; });
require(completion != receipts.end() && (*completion)->result.effect_count == 2, "missing multi-input completion");
const auto index = static_cast<std::size_t>(completion - receipts.begin());
rejects(index, [](auto& r) { r.result.effects[1] = r.result.effects[0]; });
rejects(index, [](auto& r) { r.result.effects[1] = r.result.effects[0]; r.result.effects[1].count = 1; });
rejects(index, [](auto& r) { r.request.source = 1; });
require(w->custody_request((*completion)->request) == (*completion)->result, "valid retired result no longer replays");
}
Test CustodyTests::merged_carpentry_effects_keep_distinct_owners() {
World world(3, 20, 20, 1, ExecutionMode::SerialReference);
const auto first = world.add_storage({3,3}, 10), second = world.add_storage({5,3}, 10);
world.stock_storage(first, ItemType::Wood, 1); world.stock_storage(second, ItemType::Wood, 1);
const auto actor = world.spawn_agent({1,3}); world.start_scenario({8,3});
require(world.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},actor}).status == CommandStatus::Accepted,
"carpenter setup refused");
world.queue_production({8,3}, RecipeId::CraftWoodenDoor);
const auto production = world.production_orders()[0].id;
for (int i = 0; i < 80 && world.find_production(production)->state != JobState::Completed; ++i) ticks(world,1);
require(world.find_production(production)->state == JobState::Completed, "two-source carpenter did not complete");
const auto completion = std::find_if(world.custody_receipts().begin(), world.custody_receipts().end(),
[](const auto& r) { return r->request.operation == CustodyOperation::Complete; });
require(completion != world.custody_receipts().end() && (*completion)->result.effect_count == 2, "merged carpenter input duplicated");
const auto& input = (*completion)->result.effects[0]; const auto& output = (*completion)->result.effects[1];
require(input.owner == StockOwner{OwnerKind::Production,production} && input.item == ItemType::Wood && input.count == 0 &&
output.owner == StockOwner{OwnerKind::Resident,actor} && output.item == ItemType::WoodenDoor && output.count == 1 && input.stack != output.stack,
"consumed site input or distinct resident output lost");
std::ostringstream saved; world.write_save(saved, WorldSaveFormat::Current15);
std::istringstream bytes(saved.str()); auto restored = World::read_save(bytes,1,ExecutionMode::SerialReference);
require(restored->custody_request((*completion)->request) == (*completion)->result, "carpentry result changed after restore");
ticks(*restored, 20);
}
Test CustodyTests::active_terminal_and_delivery_phase_are_rejected() {
auto w = cabin(); ticks(*w, 1);
auto& actor = const_cast<Agent&>(w->agents()[0]);
require(actor.state == AgentState::FetchingMaterials, "test needs uncollected first stop");
actor.state = AgentState::Travelling;
bool rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
actor.state = AgentState::FetchingMaterials;
require(rejected, "delivery source stop allowed generic Travelling transition");
ticks(*w, 1);
auto& receipts = const_cast<std::vector<std::shared_ptr<const CustodyReceipt>>&>(w->custody_receipts());
const auto index = receipts.size() - 1; const auto original = receipts[index];
require(original->request.operation == CustodyOperation::Pickup && actor.execution, "test needs active pickup receipt");
auto altered = std::make_shared<CustodyReceipt>(*original); altered->result.terminal = true; receipts[index] = altered;
rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "active pickup was allowed to terminate transfer history");
ticks(*w, 60);
receipts[index] = altered;
rejected = false; try { w->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
receipts[index] = original;
require(rejected, "retired history accepted premature pickup terminal"); w->validate_custody();
}
Test CustodyTests::harvest_source_and_return_capacity_are_required_by_phase() {
World harvest(1,10,10,1,ExecutionMode::SerialReference);
(void)harvest.add_storage({4,3},10); (void)harvest.add_resource_node({2,3},ItemType::Wood,2);
(void)harvest.spawn_agent({2,3}); ticks(harvest,1);
auto& actor = const_cast<Agent&>(harvest.agents()[0]);
auto& node = const_cast<ResourceNode&>(harvest.resource_nodes()[0]);
const auto original = actor; const auto original_node = node;
require(actor.state == AgentState::Gathering, "test needs live gather phase");
actor.resource_node_id = 0; actor.execution->source = 0;
for (auto& claim : actor.execution->reservations) if (claim.kind == ReservationKind::Harvest) claim = {};
node.reserved_workers = 0;
bool rejected = false; try { harvest.validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
actor = original; node = original_node;
require(rejected, "gathering with no source or source claim was accepted"); ticks(harvest,10);
auto returning = cabin(); ticks(*returning,16);
require(returning->cancel_production(returning->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused");
auto& carrier = const_cast<Agent&>(returning->agents()[0]); auto& store = const_cast<Storage&>(returning->storages()[0]);
carrier.execution->destination = store.id; carrier.execution->reservation_count = 1;
carrier.execution->reservations[0] = {1,ReservationKind::Capacity,{OwnerKind::Storage,store.id},0,{},1};
++store.reserved_slots;
rejected = false; try { returning->validate_custody(); } catch (const std::runtime_error&) { rejected = true; }
carrier.execution->destination = 0; carrier.execution->reservation_count = 0; carrier.execution->reservations[0] = {}; --store.reserved_slots;
require(rejected, "cancellation return kept a destination capacity claim"); ticks(*returning,40);
}
}
+7
View File
@@ -0,0 +1,7 @@
# Frozen schema 2 migration corpus
`fixtures.hpp` contains 13 authentic checkpoints and FNV-1a hashes of 80 subsequent raw13 states for each. They were emitted by `capture.cpp`, compiled exclusively against source and headers at `f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e`, using the pinned VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, Windows x64 GCC 16.2 and Wine 11. Each fixture includes its full SHA-256. These bytes were captured before the custody implementation and are never regenerated by the current writer.
Seed is 43. UUID is `91020304-0506-4708-890a-0b0c0d0e0f10`, city 7, built-in rules. The probe records exact states before pickup, between stops, approaching the worksite, Working with implicit consumed delivery, three direct recipes, finished carpenter cargo without a production link, harvesting, harvested cargo, both meal phases and tending. The `.continuation13` probe output stores 80 length-prefixed raw13 frames (32-bit little-endian lengths).
Reproduce in a separate historical checkout at that exact commit, build its `settlement_core`, then compile this probe with that checkout's headers and library. Pass an existing directory prefix including its trailing separator. Do not use current headers or objects with the historical probe. The generated fixture header retains only checkpoints and per-tick hashes; complete raw frames and build logs are verification artifacts outside the repository.
+59
View File
@@ -0,0 +1,59 @@
#include "settlement/core/checkpoint.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <set>
using namespace settlement;
constexpr Void::Uuid::Uuid uuid{{0x91,2,3,4,5,6,0x47,8,0x89,10,11,12,13,14,15,16}};
std::string prefix;
void capture(const World& world, const std::string& name) {
auto rules=default_rules_manifest(); auto data=encode_checkpoint(world,uuid,7,*rules);
if(!data) throw std::runtime_error(data.error().message);
std::ofstream(prefix+name+".checkpoint",std::ios::binary).write(data->data(),data->size());
std::ofstream raw(prefix+name+".raw14",std::ios::binary); world.write_save(raw,WorldSaveFormat::Current14);raw.close();
std::ofstream legacy(prefix+name+".raw13",std::ios::binary); world.write_save(legacy,WorldSaveFormat::Legacy13);legacy.close();
const auto&a=world.agents().front();
std::cout<<name<<" tick="<<world.tick()<<" agent_state="<<int(a.state)<<" production="<<a.production_id<<" inventory=";
for(unsigned i=1;i<=item_type_count;++i)std::cout<<a.inventory.item_count(ItemType(i))<<',';
std::cout<<" stops="<<(world.production_orders().empty()?0:world.production_orders().front().delivery_stops.size())<<"\n";
std::ostringstream frozen(std::ios::binary); world.write_save(frozen,WorldSaveFormat::Current14); std::istringstream input(frozen.str(),std::ios::binary); auto copy=World::read_save(input,1,ExecutionMode::SerialReference); std::ofstream continuation(prefix+name+".continuation13",std::ios::binary);
for(unsigned i=0;i<80;++i){std::ostringstream frame(std::ios::binary); copy->write_save(frame,WorldSaveFormat::Legacy13); const auto bytes=frame.str(); std::uint32_t count=bytes.size(); continuation.write(reinterpret_cast<const char*>(&count),4); continuation.write(bytes.data(),bytes.size()); copy->step();}
}
int main(int argc,char**argv){
if(argc!=2)return 2;prefix=argv[1];
World w(43,20,8,1,ExecutionMode::SerialReference);
auto a=w.add_storage({3,3},20),b=w.add_storage({8,3},20);
w.stock_storage(a,ItemType::Plank,3);w.stock_storage(b,ItemType::StoneBlock,2);
(void)w.spawn_agent({1,3}); w.queue_production({14,3},RecipeId::BuildCabin);
std::set<std::string> seen;
for(unsigned i=0;i<80;++i){w.step();const auto&agent=w.agents().front();const auto&o=w.production_orders().front();
std::string name;
if(agent.state==AgentState::FetchingMaterials)name="cabin-before-pickup";
if(agent.state==AgentState::Hauling&&o.collected_stops==1)name="cabin-between-stops";
if(agent.state==AgentState::Hauling&&o.collected_stops==2)name="cabin-to-site";
if(agent.state==AgentState::Working)name="cabin-working";
if(!name.empty()&&seen.insert(name).second)capture(w,name);
}
for(auto recipe:{RecipeId::SawPlank,RecipeId::CutStoneBlock,RecipeId::WeaveCloth}){
World d(43,20,8,1,ExecutionMode::SerialReference);auto s=d.add_storage({3,3},20);
d.stock_storage(s,recipe==RecipeId::SawPlank?ItemType::Wood:recipe==RecipeId::CutStoneBlock?ItemType::Stone:ItemType::Flax,1);
(void)d.spawn_agent({2,3});d.queue_production({6,3},recipe);
for(int i=0;i<40;++i){d.step();if(d.agents().front().state==AgentState::Working){capture(d,"direct-"+std::to_string(int(recipe)));break;}}
}
World c(43,24,24,1,ExecutionMode::SerialReference);c.start_scenario({2,2});auto s=c.add_storage({3,3},20);c.stock_storage(s,ItemType::Wood,5);
const auto carpenter=c.spawn_agent({2,3}); (void)c.apply_command({1,1,CommandKind::AssignProfession,{},static_cast<std::uint8_t>(Profession::Carpenter),{},carpenter});c.queue_production(*c.carpenter_workshop(),RecipeId::CraftWoodenDoor);
for(int i=0;i<120;++i){c.step();if(c.agents().front().state==AgentState::Hauling&&c.agents().front().production_id==0&&c.agents().front().inventory.item_count(ItemType::WoodenDoor)){capture(c,"carpenter-output");break;}}
World h(43,20,8,1,ExecutionMode::SerialReference);(void)h.add_storage({14,3},20);(void)h.add_resource_node({3,3},ItemType::Wood,1);(void)h.spawn_agent({1,3});
bool gathering=false,hauling=false;
for(int i=0;i<60;++i){h.step();if(!gathering&&h.agents().front().state==AgentState::Gathering){capture(h,"harvest-gathering");gathering=true;}if(!hauling&&h.agents().front().state==AgentState::Hauling){capture(h,"harvest-hauled");hauling=true;}}
World m(43,20,8,1,ExecutionMode::SerialReference);auto pantry=m.add_storage({14,3},20,StorageKind::Pantry);m.stock_storage(pantry,ItemType::Berries,5);(void)m.spawn_agent({1,3});m.enable_hunger();
bool going=false,eating=false;
for(int i=0;i<220;++i){m.step();if(!going&&m.agents().front().state==AgentState::GoingToEat){capture(m,"meal-going");going=true;}if(!eating&&m.agents().front().state==AgentState::Eating){capture(m,"meal-eating");eating=true;}}
World t(43,20,8,1,ExecutionMode::SerialReference);t.start_scenario({2,2});(void)t.spawn_agent({1,3});(void)t.apply_command({1,1,CommandKind::PlaceTreePlot,{5,3}});
bool tending=false;
for(int i=0;i<60;++i){t.step();if(t.agents().front().state==AgentState::Gathering&&t.agents().front().storage_id==0){capture(t,"tending");tending=true;break;}}
return seen.size()==4&&gathering&&hauling&&going&&eating&&tending?0:3;
}
+541
View File
@@ -0,0 +1,541 @@
// Frozen output of f6493e2d1cdb9e07eb18b9901fd8878b5d3fa51e; see capture.cpp.
#pragma once
#include <array>
#include <cstdint>
#include <string_view>
namespace custody_v14 {
struct Fixture { std::string_view name, sha256, checkpoint; std::array<std::uint64_t,80> ticks; };
inline constexpr std::array<Fixture,13> fixtures{{
{"cabin-before-pickup", "6fb53ddaf7d666a5e5b0e899ffbad1d7137dea4e7a037fcf824f521cf5f0b531",
"53544843484b505402000000b6000000cf020000000000009102030405064708890a0b0c0d0e0f1007000000000000000100"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000001000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000500000000"
"00000000020000000200000003000000030000000300000001000000000000001c0000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0100000000000000000000000000000000000000000002000000010000000000000003000000030000001400000000000000"
"0001000000030300000003000000020000000000000008000000030000001400000000000000000100000004020000000200"
"00000100000001000000000000000e0000000300000002010200000001000000000000000303000000020000000000000004"
"0200000002000000010000000000000005000000040000000300000005000000030000000600000003000000070000000300"
"0000080000000300000002000000000000000600000009000000030000000a000000030000000b000000030000000c000000"
"030000000d000000030000000e00000003000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000089063e25ca59b04935ace8779f45e200ab2acbca2dc88fec7e"
"c5f3504eda9248"
, {
0x599836ebcd30a29fULL, 0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL,
0x1df54a0c813e02d9ULL, 0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL,
0x8373c6a20d010194ULL, 0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL,
0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL,
0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL,
0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL,
0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL,
0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL,
0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL,
0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL,
0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL,
0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL,
0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL,
0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL,
0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL,
0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL,
0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL,
0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL,
0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL,
0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL,
}},
{"cabin-between-stops", "daca83d48f48b53f986305655017c01e4d40a73e7085d81088e5f71f7073ef4b",
"53544843484b505402000000b6000000b6020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000"
"0000000005000000040000000300000005000000030000000600000003000000070000000300000008000000030000000000"
"0000000000001c00000000000000000000000000000000000000000000000000000003000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000002000000"
"0100000000000000030000000300000014000000000000000000000000020000000000000008000000030000001400000000"
"00000000010000000402000000020000000100000001000000000000000e0000000300000002010200000001000000000000"
"0003030000000200000000000000040200000002000000010000000000000000000000020000000000000006000000090000"
"00030000000a000000030000000b000000030000000c000000030000000d000000030000000e000000030000000100000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"bfc296aeae849041ff62087240ac2f981e75d1791610f8f7c3bcc5e9792e6320"
, {
0xcaac4531bb7bcf12ULL, 0xe100830a1464be03ULL, 0x027cbdd51f3b01c8ULL, 0x1df54a0c813e02d9ULL,
0x770d4f71d98b81f6ULL, 0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL,
0xadddce31831e3cabULL, 0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL,
0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL,
0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL,
0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL,
0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL,
0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL,
0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL,
0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL,
0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL,
0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL,
0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL,
0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL,
0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL,
0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL,
0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL,
0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL,
0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL,
0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL,
}},
{"cabin-to-site", "86b61386600533badf032b4a17ac75c38a302f4c2b78fed37a38a76232360178",
"53544843484b505402000000b600000085020000000000009102030405064708890a0b0c0d0e0f1007000000000000000700"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000007000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000008000000030000000400000000"
"000000000600000009000000030000000a000000030000000b000000030000000c000000030000000d000000030000000e00"
"00000300000000000000000000001c0000000000000000000000000000000000000000000000000000000300000002000000"
"0000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000"
"0000000002000000010000000000000003000000030000001400000000000000000000000002000000000000000800000003"
"000000140000000000000000000000000100000001000000000000000e000000030000000201020000000100000000000000"
"0303000000020000000000000004020000000200000001000000000000000000000002000000000000000000000002000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"00232dd846a1a33102aa254a632f5ad28dd7c9da49baab15e4af6c417b21fe8b28"
, {
0x1a291bf5fa80794eULL, 0xd66ea3ba081db91dULL, 0x8373c6a20d010194ULL, 0xadddce31831e3cabULL,
0x17dcacae773a6e1aULL, 0xb7dcf72a67c28f09ULL, 0x2b7379835239007dULL, 0xb581902af1f964a5ULL,
0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL, 0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL,
0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL, 0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL,
0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL, 0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL,
0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL, 0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL,
0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL, 0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL,
0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL, 0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL,
0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL, 0x6681875fe5343f60ULL, 0xe9be99df149af205ULL,
0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL, 0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL,
0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL, 0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL,
0x259190664a78239aULL, 0x324e15c71a395c77ULL, 0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL,
0x1eb3f4656731424eULL, 0xffb3418445bf349bULL, 0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL,
0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL, 0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL,
0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL, 0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL,
0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL, 0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL,
0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL, 0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL,
0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL, 0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL,
0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL, 0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL,
0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL, 0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL,
}},
{"cabin-working", "f443380bc6ff9c74d2a24d80d0261b6cd9f7560796ae76548f2b7aa24e3ef505",
"53544843484b505402000000b60000003d020000000000009102030405064708890a0b0c0d0e0f1007000000000000000d00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000000d000000000000000500000000000000"
"2300000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000003"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000200000000"
"000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000"
"0000000000000200000001000000000000000300000003000000140000000000000000000000000200000000000000080000"
"0003000000140000000000000000000000000100000001000000000000000e00000003000000020102000000010000000000"
"0000030300000002000000000000000402000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000009318a0b695a881878b8800d4ac312fa11b89fe3b0"
"62514839b4bc0b5ac25594"
, {
0x2b7379835239007dULL, 0xb581902af1f964a5ULL, 0xe6bb81ec4d2a4351ULL, 0xc9af37bf6bd67281ULL,
0xc3565d7aa175849dULL, 0x4d6474224135e8c5ULL, 0xcea8c74d08b63769ULL, 0xfc9083bebbf8ed39ULL,
0x94f2e4644ed7432dULL, 0x27ca7a848c14c2a5ULL, 0xa2268d43d90f4401ULL, 0xcbf17ad8282e5291ULL,
0xdbb636c9dfd9f8edULL, 0x6e8dccea1d177865ULL, 0xefd22014e497c709ULL, 0x92c8073c7dcaac39ULL,
0x8e8a57a7244dff5dULL, 0xa38a4398de1e3425ULL, 0xd4c4355a394f12d1ULL, 0xb32f60f8bad1de21ULL,
0xacd686b3f070f03dULL, 0xc1d672a5aa412505ULL, 0x431ac5d071c173a9ULL, 0xe610acf80af458d9ULL,
0x0964e2e7b7e27f6dULL, 0x9c3c7907f51ffee5ULL, 0x8ba6b67d280aafa1ULL, 0x4063795b91398ed1ULL,
0x6681875fe5343f60ULL, 0xe9be99df149af205ULL, 0xc48ba8b0a8d56182ULL, 0xeaacd0ee5560795fULL,
0x44d6d03be494df34ULL, 0xe2e0fdde315410b9ULL, 0x7d59e1a2ab98dc56ULL, 0x96639e9fe22a5203ULL,
0x75f2d8f87f7c8c38ULL, 0xc2d8882fdfd29b5dULL, 0x259190664a78239aULL, 0x324e15c71a395c77ULL,
0x6f153cf79c35aaecULL, 0xa12dd10bdf333b31ULL, 0x1eb3f4656731424eULL, 0xffb3418445bf349bULL,
0xdf427bdce3116ed0ULL, 0xd1ff457831b6a835ULL, 0x14556cf5e3bd2eb2ULL, 0x3a7695339048468fULL,
0x94a094811f7cac64ULL, 0xcb21a9774e6fc6e9ULL, 0xf61ad61fa9760bc6ULL, 0x3cc530cc6eb4baf3ULL,
0x1c546b250c06f528ULL, 0x01b101b04e90ed4dULL, 0x646a09e6b936758aULL, 0x01a6d82b69b927a7ULL,
0x1576cf2428c013dcULL, 0xb70f1a548afc2ae1ULL, 0x5d8c6de5d5ef943eULL, 0x15948accf188244bULL,
0xf523c5258eda5e80ULL, 0x7860d7a4be411125ULL, 0x532de676527b80a2ULL, 0x794f0eb3ff06987fULL,
0xd3790e018e3afe54ULL, 0x71833ba3dafa2fd9ULL, 0x0bfc1f68553efb76ULL, 0x2505dc658bd07123ULL,
0x049516be2922ab58ULL, 0x517ac5f58978ba7dULL, 0xb433ce2bf41e42baULL, 0xc0f0538cc3df7b97ULL,
0xfdb77abd45dbca0cULL, 0x2fd00ed188d95a51ULL, 0xad56322b10d7616eULL, 0x8e557f49ef6553bbULL,
0x6de4b9a28cb78df0ULL, 0x60a1833ddb5cc755ULL, 0xa2f7aabb8d634dd2ULL, 0xc918d2f939ee65afULL,
}},
{"carpenter-output", "6a401e39d87c97a16fbe4e7bc4a5d7cc88f6f26b176b2551102e66aa14ace446",
"53544843484b505402000000b6000000bf030000000000009102030405064708890a0b0c0d0e0f1007000000000000001100"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000180000001800000011000000000000000400000000000000"
"0b00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000100000000"
"0000000200000002000000040000000000000000020000000300000002000000030000000300000000000000000000000000"
"0000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000001000000"
"0000000000000000000000000000000000000000000000003600110000050000000000000000010000000100000000000000"
"0300000003000000140000000100000000010000000103000000000000000100000001000000000000000200000002000000"
"0e02000000000000000000000000000000000000000000000000000001000000020000000200000001000000000000000000"
"000000000000010000000000000001abbc5e54e4c970fef93640a799432f9b3e1e0a0c462351d36c6d1bb3992b331b"
, {
0xa6ec0093d932ebd8ULL, 0x87baf2e646efc9a5ULL, 0x1ab6ff5ac2d06a08ULL, 0x5b21ac6329697a51ULL,
0x892f269f06860362ULL, 0x0ce6c8acfd0548abULL, 0x10128ab0047f29e4ULL, 0xcc8b9971929bb83dULL,
0xb18f7c65729d2eaeULL, 0x6cff10cc2991c957ULL, 0xee671e7028e38f80ULL, 0x836fd8346ea210a9ULL,
0x3b1e5c33e40d38baULL, 0xe2891c128cba04c3ULL, 0xab7996b49c542e9cULL, 0xfce08ee5878a2fb5ULL,
0xc8857c8fb93a4a66ULL, 0x5bcafda5a7a0d4cfULL, 0x9068789e8a217ab8ULL, 0x731f33f4164b9621ULL,
0xb33de24022b9c652ULL, 0x6bd1afe2193ce33bULL, 0xa1f25e81be2bc454ULL, 0x401ed1b4b68ba8cdULL,
0xbf6fdd789c7567deULL, 0x277fa8b37cd738a7ULL, 0xe79f2e754b0372b0ULL, 0x5e5b4caafb0549f9ULL,
0xede1e8920bdd2beaULL, 0x2545a8b9b6961593ULL, 0x68186f9c92fabe0cULL, 0xd7cc035c13ed6905ULL,
0x85245577afe0d9d6ULL, 0x0bf76d05f70a191fULL, 0x016493e3d5aabc68ULL, 0x4e0aa86aa2aecf71ULL,
0x6fdcbb28196055c2ULL, 0xb6fb2618e466474bULL, 0x68e55ff0b8ae7ec4ULL, 0x61f7a5cf724460ddULL,
0x0a6251a626cc838eULL, 0x026b1d2a093a71f7ULL, 0xe1501a77a228e4a0ULL, 0x7658d43be7e765c9ULL,
0x2e07583b5d528ddaULL, 0xd572181a05ff59e3ULL, 0xb30ae3ca1d51d9bcULL, 0xca772914473b3355ULL,
0x03131d7a6972f2c6ULL, 0x296197d46751d86fULL, 0xcaf619893a5a2318ULL, 0x71139dc19b0aeac1ULL,
0x443b4551b6f17632ULL, 0x69c619af9dfc37dbULL, 0xac222fcda9561bb4ULL, 0x86e7da1dcd2f53edULL,
0x3bc4ef7c28f4c1beULL, 0xe06df1d434cfe647ULL, 0x275b095bac0978d0ULL, 0x9e1727915c0b5019ULL,
0x34aaf0fb2280d70aULL, 0x6c0eb122cd39c0b3ULL, 0xaee17805a99e692cULL, 0xa5629d8ad39e6ca5ULL,
0xbfb1f66260198236ULL, 0x90b9689924d6c63fULL, 0x0b94652fc0d513c8ULL, 0x4bff1238276e2411ULL,
0x00da1e39ad9805a2ULL, 0x8491c047a4174aebULL, 0xe53a71f4452dd8a4ULL, 0x1ae5eef02a3d0e7dULL,
0x86b763a9b34bdd6eULL, 0xbb59664ac1331f97ULL, 0x9a3e63985a219240ULL, 0x2f471d5c9fe01369ULL,
0x2bfbc208e211e27aULL, 0xd36681e78abeae83ULL, 0xf9d3ec3333f584dcULL, 0x170e96d694ff8575ULL,
}},
{"direct-0", "ae9fb9da88ee94c6e06905ab4dbedc291ad42fd81dfd8f5e7c1d23ffbe5b0ad4",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000101000000010000000100000001000000000000000600000003000000"
"0001010000000100000000000000010100000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000007a31faff08de99b99ec1e7f1a71b99f6c6bbf004087d"
"dd0b81acf4ca14acd130"
, {
0xcb3aa5dfb03965c9ULL, 0xeabf911762701811ULL, 0x3267ff311c8f5285ULL, 0xc9a54b382b66e91dULL,
0x3eadc9b41b6a79c1ULL, 0x88d52de6de23fa69ULL, 0xda6625e9c8402245ULL, 0xdf431e91a4cc8a4dULL,
0x88968629292726d9ULL, 0x90616d8a80511ad1ULL, 0xefc3df7a957d1395ULL, 0x1e8ec6e4dc12bf8eULL,
0xdaf77dfbd58cb967ULL, 0x611d034605ba46f0ULL, 0x2fe16de272eb1379ULL, 0xd3cfbd66bb79843aULL,
0x91b047e412719a33ULL, 0x1a8b985c61eb123cULL, 0xf23946c97dcc7825ULL, 0x3f4e05a9cdb2c0f6ULL,
0xbcc048eb14dcb00fULL, 0x08ff6dc7f49a22f8ULL, 0x4b90993f02ab24c1ULL, 0xb5988855fac97ae2ULL,
0x737912d351c190dbULL, 0xfc54634ba13b08e4ULL, 0xd40211b8bd1c6ecdULL, 0x2116d0990d02b79eULL,
0x514c488aa75ce6b7ULL, 0x63a50cfa36aa3f00ULL, 0xa636387144bb40c9ULL, 0xd657c71aec697c4aULL,
0x9438519843619243ULL, 0x1d13a21092db0a4cULL, 0xf4c1507daebc7035ULL, 0xb5a2d0389f82ee46ULL,
0x33151379e6acdd5fULL, 0x7f543856c66a5048ULL, 0x4e18a2f3339b1cd1ULL, 0xb820920a2bb972f2ULL,
0x76011c8782b188ebULL, 0xfedc6cffd22b00f4ULL, 0xd68a1b6cee0c66ddULL, 0x976b9b27ded2e4eeULL,
0x53d4523ed84cdec7ULL, 0xd9f9d789087a6c50ULL, 0xa8be422575ab38d9ULL, 0x4cac91a9be39a99aULL,
0x0a8d1c271531bf93ULL, 0x93686c9f64ab379cULL, 0x6b161b0c808c9d85ULL, 0xb82ad9ecd072e656ULL,
0x359d1d2e179cd56fULL, 0x81dc420af75a4858ULL, 0xc46d6d82056b4a21ULL, 0x2e755c98fd89a042ULL,
0xec55e7165481b63bULL, 0x7531378ea3fb2e44ULL, 0x4cdee5fbbfdc942dULL, 0x99f3a4dc0fc2dcfeULL,
0xe6b5cbc19f1c7697ULL, 0xf90e90312e69cee0ULL, 0x3b9fbba83c7ad0a9ULL, 0x6bc14a51e4290c2aULL,
0x29a1d4cf3b212223ULL, 0xb27d25478a9a9a2cULL, 0x8a2ad3b4a67c0015ULL, 0x4b0c536f97427e26ULL,
0xc87e96b0de6c6d3fULL, 0x14bdbb8dbe29e028ULL, 0xe382262a2b5aacb1ULL, 0x4d8a1541237902d2ULL,
0x0b6a9fbe7a7118cbULL, 0x9445f036c9ea90d4ULL, 0x6bf39ea3e5cbf6bdULL, 0x2cd51e5ed69274ceULL,
0xe93dd575d00c6ea7ULL, 0x6f635ac00039fc30ULL, 0x3e27c55c6d6ac8b9ULL, 0xe21614e0b5f9397aULL,
}},
{"direct-1", "452313012591f9337c1410095355887d778a47c225d09b3fe550d9f8ec2cc67a",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000f00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000201000000010000000100000001000000000000000600000003000000"
"0101010000000100000000000000020100000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000d4e59fb1f410d7b6ab8e531ff066559d5d44677d61c6"
"544d069a18fd0269e030"
, {
0x37ae3152f9978e76ULL, 0x57331c8aabce40beULL, 0x1351af3574563b7aULL, 0xaa8efb3c832dd212ULL,
0xc09abf5a0172a736ULL, 0xdfcf4f278ad81e4eULL, 0xa5d66bbb835d0672ULL, 0xd5a638c8993d780aULL,
0xf50a119c72854f86ULL, 0xfcd4f8fdc9af437eULL, 0xd0ad8f7eed43fc8aULL, 0x5030d7afa10ed4d2ULL,
0x3d54d6a175847066ULL, 0x44cf6298a3dd292eULL, 0x0ad67f2c9c621152ULL, 0xcd445e1c36765956ULL,
0x1d1b333928ab77cbULL, 0x8f20ad074bb134a4ULL, 0xf8c4a61402cfa309ULL, 0x2f038e4a264230aaULL,
0x29580d1fd74f61dfULL, 0x9c67a99332277128ULL, 0x5bdb109eaa1bb50dULL, 0xaf0d290b75c64ffeULL,
0xfee3fe2867fb6e73ULL, 0x70e977f68b012b4cULL, 0xda8d7103421f99b1ULL, 0x10cc593965922752ULL,
0xbde40cbf69cf9887ULL, 0xf70d48c574378d30ULL, 0xb680afd0ec2bd115ULL, 0xcfcc67d067665166ULL,
0x1fa33ced599b6fdbULL, 0x91a8b6bb7ca12cb4ULL, 0xfb4cafc833bf9b19ULL, 0xa55858d8f8125dfaULL,
0x9facd7aea91f8f2fULL, 0x12bc742203f79e78ULL, 0x5e631a52db0bad1dULL, 0xb19532bfa6b6480eULL,
0x016c07dc98eb6683ULL, 0x737181aabbf1235cULL, 0xdd157ab7730f91c1ULL, 0x872123c8376254a2ULL,
0xc06c16739abf9097ULL, 0x6d6213544607ba80ULL, 0xb908b9851d1bc925ULL, 0x4621325f39367eb6ULL,
0x95f8077c2b6b9d2bULL, 0x07fd814a4e715a04ULL, 0x71a17a57058fc869ULL, 0xa7e0628d2902560aULL,
0xa234e162da0f873fULL, 0x15447dd634e79688ULL, 0xd4b7e4e1acdbda6dULL, 0x27e9fd4e7886755eULL,
0x77c0d26b6abb93d3ULL, 0xe9c64c398dc150acULL, 0x536a454644dfbf11ULL, 0x89a92d7c68524cb2ULL,
0x534d8ff6618f2867ULL, 0x8c76cbfc6bf71d10ULL, 0x4bea3307e3eb60f5ULL, 0x6535eb075f25e146ULL,
0xb50cc024515affbbULL, 0x271239f27460bc94ULL, 0x90b632ff2b7f2af9ULL, 0x3ac1dc0fefd1eddaULL,
0x35165ae5a0df1f0fULL, 0xa825f758fbb72e58ULL, 0xf3cc9d89d2cb3cfdULL, 0x46feb5f69e75d7eeULL,
0x96d58b1390aaf663ULL, 0x08db04e1b3b0b33cULL, 0x727efdee6acf21a1ULL, 0x1c8aa6ff2f21e482ULL,
0x55d599aa927f2077ULL, 0x02cb968b3dc74a60ULL, 0x4e723cbc14db5905ULL, 0xdb8ab59630f60e96ULL,
}},
{"direct-4", "34fddc7587d05b995c207d9db896146154ace52dc152e62004efac370c1258ec",
"53544843484b505402000000b60000003c020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000"
"0900000000000000000000000000000000000000000000000002000000000000000100000000000000010000000000000002"
"0000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000006000000030000000200000000"
"0000000004000000030000000300000004000000030000000500000003000000060000000300000004000000000000000b00"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000001000000000000000000000000000000000000000000010000000100000000000000"
"0300000003000000140000000000000000010000000701000000010000000100000001000000000000000600000003000000"
"0401010000000100000000000000070100000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000db4ee0a01a3bdbe2c73bce9fb3c27baca13e5aaa12a1"
"d06e25ec370dcebd6e75"
, {
0x390c415e34d0166aULL, 0x554a4dca2da2d072ULL, 0x0a6d78876d939f76ULL, 0x3746c232f2e153feULL,
0x1dac5cc0bc01befaULL, 0x2230655659c7bab2ULL, 0xc98216266ea8b8ceULL, 0xcb18300291d12896ULL,
0x8c028e6e517d8faaULL, 0x15e0477b18051b22ULL, 0xcb03723857f5ea26ULL, 0x550bb6fd219fa238ULL,
0x6cf696b2deed2d21ULL, 0xb5fe1220613db27aULL, 0x134d258ced91df3bULL, 0xca82240862b0591cULL,
0x9e3eceaeb9118035ULL, 0xf8bc7d34089f3e3eULL, 0xd1d2bf535ea84f7fULL, 0xb666fe781169bcf0ULL,
0x0e2358ec20130a79ULL, 0x572ad459a2638fd2ULL, 0xb479e7c62eb7bc93ULL, 0x6baee641a3d63674ULL,
0x3f6b90e7fa375d8dULL, 0x6002defff95500f6ULL, 0xace5e1f9f03e4777ULL, 0x5793c0b1528f9a48ULL,
0xe34b6141b0bd5a71ULL, 0xb8861bd4922daa8aULL, 0x15d52f411e81d74bULL, 0xcd0a2dbc93a0512cULL,
0xa0c6d862ea017845ULL, 0xfb4486e8398f364eULL, 0x482789e230787ccfULL, 0x2cbbc906e339ea40ULL,
0x8478237af1e337c9ULL, 0x59b2de0dd35387e2ULL, 0xb701f17a5fa7b4a3ULL, 0x6e36eff5d4c62e84ULL,
0x41f39a9c2b27559dULL, 0xd657a98ecb252e46ULL, 0xaf6debae212e3f87ULL, 0xcde88b40245fc798ULL,
0xe5d36af5e1ad5281ULL, 0x2edae66363fdd7daULL, 0x8c29f9cff052049bULL, 0x435ef84b65707e7cULL,
0x171ba2f1bbd1a595ULL, 0x719951770b5f639eULL, 0x4aaf9396616874dfULL, 0x2f43d2bb1429e250ULL,
0x87002d2f22d32fd9ULL, 0xd007a89ca523b532ULL, 0x2d56bc093177e1f3ULL, 0xe48bba84a6965bd4ULL,
0xb848652afcf782edULL, 0xd8dfb342fc152656ULL, 0x25c2b63cf2fe6cd7ULL, 0xd07094f4554fbfa8ULL,
0x78b4e478a87cea51ULL, 0x4def9f0b89ed3a6aULL, 0xab3eb2781641672bULL, 0x6273b0f38b5fe10cULL,
0x36305b99e1c10825ULL, 0x90ae0a1f314ec62eULL, 0xdd910d1928380cafULL, 0xc2254c3ddaf97a20ULL,
0x19e1a6b1e9a2c7a9ULL, 0xef1c6144cb1317c2ULL, 0x4c6b74b157674483ULL, 0x03a0732ccc85be64ULL,
0xd75d1dd322e6e57dULL, 0x6bc12cc5c2e4be26ULL, 0x44d76ee518edcf67ULL, 0x63520e771c1f5778ULL,
0x7b3cee2cd96ce261ULL, 0xc444699a5bbd67baULL, 0x21937d06e811947bULL, 0xd8c87b825d300e5cULL,
}},
{"harvest-gathering", "2983ac00f777101dd7d71bd7379764ac32aa2330608fed9a4bf4dc1f2ee01426",
"53544843484b505402000000b600000069020000000000009102030405064708890a0b0c0d0e0f1007000000000000000200"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000002000000000000000200000000000000"
"0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000300000000"
"0000000002000000020000000300000003000000030000000200000000000000020000000100000000000000010000000000"
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b000000"
"0400000003000000050000000300000006000000030000000700000003000000080000000300000009000000030000000a00"
"0000030000000b000000030000000c000000030000000d000000030000000e00000003000000000000000000000000000000"
"0000000000000100000001000000000000000300000003000000010100000001000000010000000100000000000000000001"
"00000001000000000000000e0000000300000014000000010000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000000000000000000006719c2fed4abf63ffe4456b03d95b13c12ef3078097d13e1a1b74a"
"bb30b5cf17"
, {
0x4034a5761e22ecabULL, 0xf78178bf59b905d9ULL, 0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL,
0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL, 0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL,
0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL, 0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL,
0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL, 0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL,
0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL, 0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL,
0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL, 0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL,
0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL, 0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL,
0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL, 0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL,
0x06f612cf620661bfULL, 0x15690f824ab457aaULL, 0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL,
0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL, 0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL,
0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL, 0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL,
0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL, 0xb8717ed084a5c46dULL, 0x9933663e11318928ULL,
0x1b7d4c9043036defULL, 0x29f049432bb163daULL, 0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL,
0x06c520a39d652a33ULL, 0x15381d568613201eULL, 0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL,
0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL, 0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL,
0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL, 0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL,
0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL, 0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL,
0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL, 0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL,
0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL, 0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL,
0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL, 0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL,
}},
{"harvest-hauled", "038b7ae299004c672e20cefb6c50ab9bacd6f83606ceca83d9d5edd20ff8cfad",
"53544843484b505402000000b600000059020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000200000000000000"
"0f00000000000000000000000000000000000000000000000002000000000000000100000000000000020000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000003000000030000000400000000"
"000000000b000000040000000300000005000000030000000600000003000000070000000300000008000000030000000900"
"0000030000000a000000030000000b000000030000000c000000030000000d000000030000000e0000000300000000000000"
"0000000000000000000000000000000001000000000000000100000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000"
"0000030000000300000001000000000100000000000000010000000000000000000100000001000000000000000e00000003"
"0000001400000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000df9205984b13c7ea46ccd323ab458977e4ea273b047760dbebb30e7fd311d16f"
, {
0x5fd5644d1fa59357ULL, 0xaa768617a1b90374ULL, 0x6ceeba0f2fe9089dULL, 0xee339afe091ed342ULL,
0xaeb06ae4ea87af53ULL, 0x7b6079611fd6a880ULL, 0xbbc9c0a6facb2499ULL, 0xe75c76afc2037eceULL,
0xec829e3d4f72762fULL, 0x07bfb4a042a471ecULL, 0x55e6cc33aa390f75ULL, 0x3e52625e8b2045b6ULL,
0x4f7d9d5bcf978d4dULL, 0x303f84c95c235208ULL, 0xb2896b1b8df536cfULL, 0xc0fc67ce76a32cbaULL,
0x421810bd51ac0c71ULL, 0x32d353a79afcd8dcULL, 0x9dd13f2ee856f313ULL, 0xac443be1d104e8feULL,
0x61a1fa6a365c4a35ULL, 0xd6d4e506f73bbaf0ULL, 0x51cc2c0b015adcd7ULL, 0x603f28bdea08d2c2ULL,
0x543c6dcbb870c959ULL, 0xfdbfa374e6fab424ULL, 0x44669f6c836f5bfbULL, 0x52d99c1f6c1d51e6ULL,
0x6404d71cb094997dULL, 0x44c6be8a3d205e38ULL, 0x06f612cf620661bfULL, 0x15690f824ab457aaULL,
0x9684b87125bd3761ULL, 0x873ffb5b6f0e03ccULL, 0xb25878efc953ff43ULL, 0xc0cb75a2b201f52eULL,
0x7629342b17595665ULL, 0x2b418cbacb4ce5e0ULL, 0x665365cbe257e907ULL, 0x74c6627ecb05def2ULL,
0xa8a9157f8c81f449ULL, 0x522c4b28bb0bdf14ULL, 0x98d34720578086ebULL, 0xa74643d3402e7cd6ULL,
0xb8717ed084a5c46dULL, 0x9933663e11318928ULL, 0x1b7d4c9043036defULL, 0x29f049432bb163daULL,
0xab0bf23206ba4391ULL, 0x9bc7351c500b0ffcULL, 0x06c520a39d652a33ULL, 0x15381d568613201eULL,
0xca95dbdeeb6a8155ULL, 0x3fc8c67bac49f210ULL, 0xbac00d7fb66913f7ULL, 0xc9330a329f1709e2ULL,
0xbd304f406d7f0079ULL, 0x66b384e99c08eb44ULL, 0xad5a80e1387d931bULL, 0xbbcd7d94212b8906ULL,
0x292932be9169f41dULL, 0x09eb1a2c1df5b8d8ULL, 0xcc1a6e7142dbbc5fULL, 0xda8d6b242b89b24aULL,
0x5ba9141306929201ULL, 0x4c6456fd4fe35e6cULL, 0x777cd491aa2959e3ULL, 0x85efd14492d74fceULL,
0x3b4d8fccf82eb105ULL, 0xf065e85cac224080ULL, 0x2b77c16dc32d43a7ULL, 0x39eabe20abdb3992ULL,
0x6dcd71216d574ee9ULL, 0x1750a6ca9be139b4ULL, 0x5df7a2c23855e18bULL, 0x6c6a9f752103d776ULL,
0x7d95da72657b1f0dULL, 0x5e57c1dff206e3c8ULL, 0xe0a1a83223d8c88fULL, 0xef14a4e50c86be7aULL,
}},
{"meal-eating", "6ef841c3978ffb1cc6c622485ae00f612b8df62e728a00998dff39c4cb23dd86",
"53544843484b505402000000b6000000e3010000000000009102030405064708890a0b0c0d0e0f1007000000000000009b00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000009b000000000000000100000000000000"
"0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000100000001000000000000000e000000030000000700000000"
"0000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000000"
"000001000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000"
"0000000000000100000001000000000000000e00000003000000140000000000000001010000000504000000000000000000"
"000000000000000000000000000000000000000000000000000000000000000000000000000000cbca12e9de2b541fa0a67c"
"950419717981e249938bede98f7bc5ac8b21bb41e4"
, {
0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL,
0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL,
0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL,
0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL,
0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL,
0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL,
0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL,
0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL,
0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL,
0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL,
0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL,
0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL,
0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL,
0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL,
0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL,
0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL,
0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL,
0x39a161fc06355f21ULL, 0x8aa4af24c1c5cba9ULL, 0xb69ae0e9115a8c35ULL, 0x98d2751a6199af9dULL,
0x739dd8bc06858621ULL, 0x6ff7c3243fcc3dc9ULL, 0x33672a0549825cfdULL, 0x287badb017120c85ULL,
0x40244d5729444f21ULL, 0x96fbccd72f6d4719ULL, 0x02d76c8e72162665ULL, 0x11aedb91264d5afdULL,
}},
{"meal-going", "2bf42eb752cdbb6d06a69cfe3f7eb68cbf0686d5ec855b986599b2f4b589390d",
"53544843484b505402000000b60000004b020000000000009102030405064708890a0b0c0d0e0f1007000000000000008f00"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b0000000000000014000000080000008f000000000000000100000000000000"
"0e00000000000000000000000000000000000000000000000102000000000000000100000000000000010000000000000002"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000002000000030000000600000000"
"000000000d000000020000000300000003000000030000000400000003000000050000000300000006000000030000000700"
"000003000000080000000300000009000000030000000a000000030000000b000000030000000c000000030000000d000000"
"030000000e000000030000000100000000000000000000000000000000000000010000000000000000000000000000000000"
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b4000000"
"000000000000000000000100000001000000000000000e000000030000001400000000000000010100000005050000000100"
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000919d8854127c30"
"0dbea118a7d16c7f0c3044dd54f2148b20800d6204105412e3"
, {
0xfd9dfc2a0c96299dULL, 0x055fa24bd46f74c7ULL, 0xc3a99a4764c3bac9ULL, 0x788d6816d3b41547ULL,
0xabaedc2e42067cddULL, 0xad632a0f1d2c4b17ULL, 0xc9b73d3b4e831031ULL, 0x7d5bc37e22cdc2f7ULL,
0xcc366163e21db0fdULL, 0xe24026ad5ef92427ULL, 0xa4867348eeb2b129ULL, 0x165dc919e3326217ULL,
0x0eae6cbd44a5eb4cULL, 0x666bd2a801c60dc5ULL, 0xaa5ed34a6065dbaaULL, 0x0de79ba8983d3fb3ULL,
0x99ab26421b611ba8ULL, 0xc09e84ec6875f729ULL, 0xec94b6b0b80ab7b5ULL, 0xf98239f36dc2c19dULL,
0xd44d9d9512ae9821ULL, 0xa5f198ebe67c6949ULL, 0x6960ffccf032887dULL, 0x892b7289233b1e85ULL,
0xa0d41230356d6121ULL, 0xccf5a29ed61d7299ULL, 0x38d1425618c651e5ULL, 0x47a8b158ccfd867dULL,
0x227414fa71e95d01ULL, 0x997c1739f8dc3b99ULL, 0xb78777324f6d4d5dULL, 0x7cb5f0d7359af0d5ULL,
0x07c728f9efefcf21ULL, 0xce1cfa5e52220209ULL, 0x84c0a7e6fb14fc35ULL, 0x91ae2b29b0cd061dULL,
0x6c798ecb55b8dca1ULL, 0xb3700e5dd0287429ULL, 0x018cf103333cccfdULL, 0x96a9e7fb0ce72965ULL,
0x390003667877a5a1ULL, 0x652193d51927b719ULL, 0x464fb7c802725cc5ULL, 0xdfd4a28f1007cafdULL,
0xbaa00630b4f3a181ULL, 0x31a808703be68019ULL, 0x4fb36868927791ddULL, 0x14e1e20d78a53555ULL,
0x9ff31a3032fa13a1ULL, 0x44f1d52f88f4cf69ULL, 0x70e806f3d8898ff5ULL, 0x7dd58a368e4199ddULL,
0x6dfbe560e5e9e3a1ULL, 0x3f9fe0b7b9b7b4c9ULL, 0x030f4798c36dd3fdULL, 0x0d7ec2cc43b9f6c5ULL,
0x3a8259fc08a8aca1ULL, 0x5148f2e1f69c4ad9ULL, 0xd27f8a21ec019d65ULL, 0xe156f924a038d1fdULL,
0xa6c7653d92683541ULL, 0x1dcf677d195b13d9ULL, 0x3bdac7756fec259dULL, 0x166438a308d63c55ULL,
0xa17570c5c32b1aa1ULL, 0x67cb422a255d4d89ULL, 0x0913f82a1b93d475ULL, 0x16017b6cd14bde5dULL,
0x0627d69728f42821ULL, 0x37c35ea0f0a74c69ULL, 0x9b3b38cf0678187dULL, 0x30582fc6e02274e5ULL,
0xd2ae4b324bb2f121ULL, 0xe974e41839a68f59ULL, 0xcaa3080b22f13505ULL, 0x7982ea5ae343167dULL,
0x3ef35673d57279c1ULL, 0xb5fb58b35c655859ULL, 0xd406b8abb2f66a1dULL, 0xae9029d94be080d5ULL,
}},
{"tending", "3827f807449b4eef713945b5e196e082e48e10d7971587e8281f3f858f76c475",
"53544843484b505402000000b600000004020000000000009102030405064708890a0b0c0d0e0f1007000000000000000400"
"00000000000006d39e42fa79f06859b9bee1dcb08088142cb83e8cdcf72dc0984cfc62cd83d1020000001100736574746c65"
"6d656e742e636f6c6f6e790500312e302e3008e18a58989430c5435a2de6fb8f6a27a912b4d2970c1b965282408880d2c089"
"0f00736574746c656d656e742e636f72650500312e302e3061b36b8a230eebbe862e696603e021ace7151a9faf0ab3c069ab"
"7124188d337f534554544c4552530e0000002b00000000000000140000000800000004000000000000000100000000000000"
"0500000000000000000000000000000000000000000000000102000000000000000100000000000000020000000000000001"
"0000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000001000000010000000000000005000000030000000300000000"
"0000000004000000020000000300000003000000030000000400000003000000050000000300000004000000000000000500"
"0000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000002900040000000000000001000000010000000000000005000000"
"0300000001000000000600000001000000010200000000000000000000000000000000010000000200000002000000010000"
"00000000000000000000000000010000000000000001b4030ca9d1f16481a8e535b4d15d5386c3373d95462d4d421acb8c39"
"bffd838c"
, {
0x40e38438faf94b0bULL, 0x14761863e62e2a4dULL, 0xe6cd2e9002d72edbULL, 0x05e511dfedbab179ULL,
0xa31d1be8a64993d3ULL, 0x2689b1c58ae359daULL, 0x0a35fc84aa4f48c7ULL, 0xfcb493ac0b7a9ca0ULL,
0xa5b6852baae0b5d5ULL, 0x475c01f9c9b77106ULL, 0x8f687924c6abc753ULL, 0xda1797bdf654a5fcULL,
0x06e3f4bcdb5865e1ULL, 0xcfc208819fd468a2ULL, 0x8f5cf81cd325dcefULL, 0xab87d8ad5efdc448ULL,
0x9596d5a2eab7763dULL, 0xc5aea624fbd7c04eULL, 0xd450e36c43ad31dbULL, 0xa28d719e4a7f7b04ULL,
0x9397942622050189ULL, 0xed40d75b33713baaULL, 0x8b456815cce24137ULL, 0x914e242111a8c7d0ULL,
0x2ccbce0483ab8405ULL, 0xbbfc27d8b7020bb6ULL, 0x332345807b3a2dc3ULL, 0x9762664544b614ecULL,
0x80116ad6bde724d1ULL, 0x68fb7be5021b5cf2ULL, 0xfc7eb3a74944f05fULL, 0x67bda54ab54433f8ULL,
0x58e78171ef50baedULL, 0x88ff51f4007104feULL, 0x59ed9f385b844e8bULL, 0x3d906a7dcfbe2e34ULL,
0x1aacdcfefacfcfb9ULL, 0x7d5eec1f9d8fca7aULL, 0x4d8111fad96086a7ULL, 0x55025b12df1abec0ULL,
0xc29ec7a141fddb35ULL, 0x8c1fa47cb9bc6066ULL, 0xd42c1ba7b6b0b6b3ULL, 0x0a89ff17710cfe1cULL,
0x3d5c395e0c4893c1ULL, 0x130d1df7cee5a682ULL, 0xb9c9822e97a65f4fULL, 0xc26a3ddb3fe313e8ULL,
0xcc0f1a441ba7a41dULL, 0xfc26eac62cc7ee2eULL, 0xefc098d519d6a5bbULL, 0xdfd2a9ccc358e324ULL,
0xb07fd69bb92226e9ULL, 0x519a59517381094aULL, 0xa6b51d7ea30bb517ULL, 0xb43c43de5efdc2f0ULL,
0x7016e37ab2bcc1e5ULL, 0xff473d4ee6134996ULL, 0x766e5af6aa4b6ba3ULL, 0xaccc3e6664a7b30cULL,
0xc302fb492ed47b31ULL, 0x1fc6fc206a2749d2ULL, 0xb34a33e2b150dd3fULL, 0x6f49b0cbe9ae8d98ULL,
0x8e54ca4832dab44dULL, 0x0caacdd834d6e0deULL, 0x810f8a2cdff9866bULL, 0xab721e2bcde3c154ULL,
0x9d91429d9d844719ULL, 0xe0ad724af039639aULL, 0x74a2fcef5dd5be87ULL, 0xc2e40ec0dd4051e0ULL,
0x5e61b8a44f430e15ULL, 0xb3418f713e319846ULL, 0x3c07f20dfe9e7413ULL, 0xa04712d2c81a5b3cULL,
0x72c982344fd28d21ULL, 0x2caac15025f78162ULL, 0x558c7331a4eb922fULL, 0xfc64d6ec78b13188ULL,
}},
}};
} // namespace custody_v14
+91 -8
View File
@@ -20,7 +20,7 @@ struct Context {
inline std::string canonical(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
world.write_save(stream, WorldSaveFormat::Current15);
return stream.str();
}
@@ -29,6 +29,7 @@ template<class T> std::string value(T item) {
else return std::to_string(item);
}
inline std::string value(GridPosition p) { return "(" + value(p.x) + "," + value(p.y) + ")"; }
inline std::string value(StockOwner owner) { return value(owner.kind) + ":" + value(owner.id); }
inline std::string value(const std::vector<GridPosition>& route) {
std::string text = "[";
for (auto p : route) text += value(p) + ",";
@@ -37,11 +38,13 @@ inline std::string value(const std::vector<GridPosition>& route) {
// Diagnostic projection of public domain objects, never a save parser or an
// alternate equality oracle. Unknown/private fields retain the byte fallback.
using Facts = std::map<std::string, std::string>;
// Prefer visible stock/job changes, then durable identities, retained results
// and accounting. A secondary balance change must not hide the changed stock.
using Facts = std::map<std::pair<unsigned, std::string>, std::string>;
inline Facts facts(const World& world) {
Facts out;
const auto put = [&](const std::string& owner, const char* field, const auto& item) {
out[owner + " field=" + field] = value(item);
const auto put = [&](const std::string& owner, const char* field, const auto& item, unsigned priority = 0) {
out[{priority, owner + " field=" + field}] = value(item);
};
for (const auto& a : world.agents()) {
const auto key = "agent id=" + value(a.id);
@@ -52,9 +55,35 @@ inline Facts facts(const World& world) {
AGENT_FIELD(production_id); AGENT_FIELD(hunger); AGENT_FIELD(fatigue);
AGENT_FIELD(resting_on_ground); AGENT_FIELD(profession);
#undef AGENT_FIELD
put(key, "next_admission", a.next_admission, 1);
put(key, "transfer_id", a.execution ? a.execution->id : 0, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
put("stock owner=agent:" + value(a.id) + " item=" + value(item), "count",
const auto stock = "stock owner=agent:" + value(a.id) + " item=" + value(item);
put(stock, "count",
a.inventory.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", a.inventory.stack_id(static_cast<ItemType>(item)), 1);
}
if (a.execution) {
const auto& transfer = *a.execution;
const auto transfer_key = "transfer id=" + value(transfer.id) + " owner=agent:" + value(a.id);
put(transfer_key, "kind", transfer.kind, 1);
put(transfer_key, "production", transfer.production, 1);
put(transfer_key, "source", transfer.source, 1);
put(transfer_key, "destination", transfer.destination, 1);
put(transfer_key, "next_operation", transfer.next_operation, 1);
put(transfer_key, "blocked", transfer.blocked, 1);
put(transfer_key, "reservation_count", transfer.reservation_count, 1);
for (const auto& claim : transfer.reservations) {
if (!claim.id) continue;
const auto claim_key = "reservation id=" + value(claim.id) + " transfer=" + value(transfer.id);
put(claim_key, "kind", claim.kind, 1);
put(claim_key, "owner", claim.owner, 1);
put(claim_key, "stack_id", claim.stack, 1);
put(claim_key, "item", claim.item, 1);
put(claim_key, "count", claim.count, 1);
put(claim_key, "backing", claim.backing, 1);
put(claim_key, "origin_storage", claim.origin_storage, 1);
}
}
}
for (const auto& j : world.jobs()) {
@@ -67,6 +96,12 @@ inline Facts facts(const World& world) {
put(key, "position", p.position); put(key, "recipe", p.recipe); put(key, "state", p.state);
put(key, "collected_stops", p.collected_stops); put(key, "bed_owner", p.bed_owner);
put(key, "bed_base", p.bed_base); put(key, "bed_stage", p.bed_stage);
put(key, "suspended", p.suspended, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto stock = "stock owner=production:" + value(p.id) + " item=" + value(item);
put(stock, "count", p.input.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", p.input.stack_id(static_cast<ItemType>(item)), 1);
}
for (const auto& m : p.materials) {
put(key + " material owner=storage:" + value(m.storage_id) + " item=" + value(m.type),
"count", m.count);
@@ -84,8 +119,56 @@ inline Facts facts(const World& world) {
for (const auto& stack : s.items) {
const auto stock = "stock owner=storage:" + value(s.id) + " item=" + value(stack.type);
put(stock, "count", stack.count); put(stock, "reserved", stack.reserved);
put(stock, "stack_id", stack.id, 1);
}
}
// Keys identify logical results independently of the ring's backing slots.
for (const auto& receipt : world.custody_receipts()) {
const auto& request = receipt->request;
const auto& result = receipt->result;
const auto key = "custody receipt kind=" + value(request.key.kind) + " id=" + value(request.key.id) +
" ordinal=" + value(request.key.ordinal);
put(key, "operation", request.operation, 2);
put(key, "kind", request.kind, 2);
put(key, "production", request.production, 2);
put(key, "source", request.source, 2);
put(key, "destination", request.destination, 2);
put(key, "line_count", request.line_count, 2);
for (std::size_t i = 0; i < request.line_count; ++i) {
const auto line_key = key + " line=" + value(i);
put(line_key, "storage", request.lines[i].storage, 2);
put(line_key, "item", request.lines[i].item, 2);
put(line_key, "count", request.lines[i].count, 2);
}
put(key, "status", result.status, 2);
put(key, "transfer_id", result.transfer, 2);
put(key, "terminal", result.terminal, 2);
put(key, "reservation_count", result.reservation_count, 2);
put(key, "effect_count", result.effect_count, 2);
for (std::size_t i = 0; i < result.reservation_count; ++i) {
put(key + " reservation=" + value(i), "id", result.reservations[i], 2);
}
for (std::size_t i = 0; i < result.effect_count; ++i) {
const auto effect_key = key + " effect=" + value(i);
const auto& effect = result.effects[i];
put(effect_key, "owner", effect.owner, 2);
put(effect_key, "stack_id", effect.stack, 2);
put(effect_key, "item", effect.item, 2);
put(effect_key, "count", effect.count, 2);
}
}
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto key = "balance item=" + value(item);
const auto& balance = world.item_balances()[item - 1];
put(key, "opening", balance.opening, 3);
put(key, "grant", balance.grant, 3);
put(key, "harvest", balance.harvest, 3);
put(key, "recipe_output", balance.recipe_output, 3);
put(key, "recipe_input", balance.recipe_input, 3);
put(key, "meal", balance.meal, 3);
put(key, "installation", balance.installation, 3);
put(key, "demolition", balance.demolition, 3);
}
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
put("command player=" + value(player), "next_sequence", world.next_command_sequence(player));
}
@@ -105,13 +188,13 @@ inline std::string difference(const World& expected, const World& actual, const
auto ai = a.begin(), bi = b.begin();
while (ai != a.end() || bi != b.end()) {
if (bi == b.end() || (ai != a.end() && ai->first < bi->first)) {
return context(expected, c) + ai->first + " expected=" + ai->second + " actual=<absent>";
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=<absent>";
}
if (ai == a.end() || bi->first < ai->first) {
return context(expected, c) + bi->first + " expected=<absent> actual=" + bi->second;
return context(expected, c) + bi->first.second + " expected=<absent> actual=" + bi->second;
}
if (ai->second != bi->second) {
return context(expected, c) + ai->first + " expected=" + ai->second + " actual=" + bi->second;
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=" + bi->second;
}
++ai; ++bi;
}
+135 -3
View File
@@ -1,4 +1,5 @@
#include "settlement/core/world.hpp"
#include "settlement/core/checkpoint.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
@@ -44,9 +45,7 @@ void require(bool condition, std::string_view message) {
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
return replay_diagnostics::canonical(world);
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
@@ -128,6 +127,8 @@ private:
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
[[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders();
[[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics();
[[= Void::Testing::tag("replay")]] Test test_modern_custody_exposes_legacy_projection_blindness();
[[= Void::Testing::tag("replay")]] Test test_cancelled_partial_cargo_checkpoint_replay();
[[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world();
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
@@ -294,6 +295,137 @@ Test ReplayTests::test_semantic_divergence_diagnostics() {
"unprojected canonical field lost byte fallback");
}
Test ReplayTests::test_modern_custody_exposes_legacy_projection_blindness() {
const auto legacy = [](const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
};
const replay_diagnostics::Context context{2, 1, "custody", "legacy-import", 4096};
World stock(107, 12, 12, 1, ExecutionMode::SerialReference);
const auto storage = stock.add_storage({2, 2}, 10);
// Issued identities follow grants, while historical migration reconstructs
// them from the canonically sorted item rows.
stock.stock_storage(storage, ItemType::StoneBlock, 2);
stock.stock_storage(storage, ItemType::Plank, 3);
auto imported = load_state(legacy(stock), execution_configs.front());
require(legacy(stock) == legacy(*imported), "legacy stock projection changed on import");
auto report = replay_diagnostics::difference(stock, *imported, context);
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
report.find("field=stack_id expected=2 actual=1") != std::string::npos,
"modern comparison missed reconstructed stack identity: " + report);
std::cout << report << '\n';
World accounting(108, 12, 12, 1, ExecutionMode::SerialReference);
const auto store = accounting.add_storage({2, 2}, 10);
accounting.stock_storage(store, ItemType::Wood, 2);
imported = load_state(legacy(accounting), execution_configs.front());
require(legacy(accounting) == legacy(*imported), "legacy accounting projection changed on import");
report = replay_diagnostics::difference(accounting, *imported, context);
require(report.find("balance item=1 field=grant expected=2 actual=0") != std::string::npos,
"modern comparison missed opening/grant distinction: " + report);
World active(109, 32, 32, 1, ExecutionMode::SerialReference);
const auto materials = active.add_storage({3, 3}, 5);
active.stock_storage(materials, ItemType::Plank, 3);
active.stock_storage(materials, ItemType::StoneBlock, 2);
static_cast<void>(active.spawn_agent({1, 3}));
active.queue_production({16, 3}, RecipeId::BuildCabin);
active.step();
imported = load_state(legacy(active), execution_configs.front());
require(legacy(active) == legacy(*imported), "legacy active projection changed on import");
require(!active.custody_receipts().empty() && imported->custody_receipts().empty(),
"fixture did not distinguish real and reconstructed history");
report = replay_diagnostics::difference(active, *imported, context);
require(report.find("custody receipt kind=0 id=1 ordinal=1") != std::string::npos &&
report.find("actual=<absent>") != std::string::npos,
"modern comparison missed retained admission result: " + report);
std::cout << report << '\n';
const auto facts = replay_diagnostics::facts(active);
const auto& transfer = *active.agents().front().execution;
const auto& reservation = transfer.reservations.front();
require(facts.at({1, "transfer id=" + std::to_string(transfer.id) + " owner=agent:1 field=next_operation"}) == "1" &&
facts.at({1, "reservation id=" + std::to_string(reservation.id) + " transfer=" +
std::to_string(transfer.id) + " field=stack_id"}) == std::to_string(reservation.stack),
"active transfer/reservation diagnostics lost durable identities");
}
Test ReplayTests::test_cancelled_partial_cargo_checkpoint_replay() {
World reference(113, 32, 32, 1, ExecutionMode::SerialReference);
const auto source = reference.add_storage({3, 3}, 5);
reference.stock_storage(source, ItemType::Plank, 3);
reference.stock_storage(source, ItemType::StoneBlock, 2);
static_cast<void>(reference.spawn_agent({1, 3}));
reference.queue_production({16, 3}, RecipeId::BuildCabin);
const auto order = reference.production_orders().front().id;
for (int tick = 0; tick < 30 && reference.agents().front().state != AgentState::Working; ++tick) reference.step();
require(reference.agents().front().state == AgentState::Working, "cabin delivery did not reach the site");
const auto transfer = reference.agents().front().execution->id;
require(reference.cancel_production(order) == CommandStatus::Accepted, "live construction cancellation failed");
reference.stock_storage(source, ItemType::Wood, 5);
const auto partial = reference.add_storage({4, 3}, 1);
for (int tick = 0; tick < 40; ++tick) reference.step();
const auto& actor = reference.agents().front();
require(actor.state == AgentState::Returning && actor.execution && actor.execution->id == transfer &&
actor.execution->blocked == CustodyStatus::NoDestination &&
actor.inventory.item_count(ItemType::Plank) == 2 && actor.inventory.item_count(ItemType::StoneBlock) == 2 &&
reference.find_storage(partial)->item_count(ItemType::Plank) == 1,
"partial return did not retain the same transfer and remaining cargo");
const auto admission = *reference.custody_receipts().front();
const auto cancelled = std::find_if(reference.custody_receipts().begin(), reference.custody_receipts().end(),
[](const auto& receipt) { return receipt->request.operation == CustodyOperation::Cancel; });
require(cancelled != reference.custody_receipts().end(), "cancel result was not retained");
const std::array retained{admission, **cancelled};
Void::Uuid::Uuid world_id;
world_id.bytes.back() = 113;
const auto rules = default_rules_manifest();
const auto catalog = builtin_rule_packages();
require(rules.has_value() && catalog.has_value(), "default rules unavailable");
const auto checkpoint = encode_checkpoint(reference, world_id, 7, *rules);
require(checkpoint.has_value(), "partial cargo checkpoint failed");
std::vector<std::unique_ptr<World>> candidates;
for (const auto config : execution_configs) {
auto loaded = decode_checkpoint(*checkpoint, *catalog, config.workers, config.mode);
require(loaded.has_value(), "partial cargo checkpoint was not decoded");
require(loaded->world_id == world_id && loaded->city == 7, "checkpoint identity changed");
const auto repeated = encode_checkpoint(*loaded->world, loaded->world_id, loaded->city, loaded->rules);
require(repeated.has_value() && *repeated == *checkpoint, "partial checkpoint roundtrip changed bytes");
candidates.push_back(std::move(loaded->world));
}
const auto repeat_without_effect = [&](World& world) {
const auto before = saved_state(world);
for (const auto& receipt : retained) {
require(world.custody_request(receipt.request) == receipt.result, "retained result changed after reload");
auto conflict = receipt.request;
++conflict.destination;
require(world.custody_request(conflict).status == CustodyStatus::Conflict,
"changed payload reused an accepted transfer step");
}
require(saved_state(world) == before, "retry repeated a physical transfer or consumed an ordinal");
};
repeat_without_effect(reference);
for (auto& world : candidates) repeat_without_effect(*world);
for (std::uint64_t attempt = 0; attempt < 40; ++attempt) {
if (attempt == 5) {
static_cast<void>(reference.add_storage({6, 3}, 20));
for (auto& world : candidates) static_cast<void>(world->add_storage({6, 3}, 20));
}
reference.step();
for (std::size_t i = 0; i < candidates.size(); ++i) {
candidates[i]->step();
const auto report = replay_diagnostics::difference(reference, *candidates[i],
{attempt, execution_configs[i].workers, "cancel-return", "checkpoint", 4096});
require(report.empty(), report);
repeat_without_effect(*candidates[i]);
}
}
require(reference.agents().front().inventory.empty() && !reference.agents().front().execution &&
reference.item_balances()[2].installation == 0 && reference.item_balances()[3].installation == 0,
"return duplicated consumption or retained finished cargo");
repeat_without_effect(reference);
}
Test ReplayTests::test_execution_configuration_and_empty_world() {
World initial(20261202, 5, 5);
const auto bytes = saved_state(initial);
+1 -3
View File
@@ -21,9 +21,7 @@ constexpr TrustedClient host{1};
constexpr TrustedClient guest{2};
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
return replay_diagnostics::canonical(world);
}
WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {
+1 -1
View File
@@ -28,7 +28,7 @@ static_assert(!std::is_copy_constructible_v<World>);
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
world.write_save(stream, WorldSaveFormat::Current15);
return stream.str();
}
-325
View File
@@ -1,325 +0,0 @@
// Exercise the real two-window handlers without an alternate rendering path.
#define SETTLEMENT_FRAME_TEST
#include "../app/viewer_win32.cpp"
#include <d3d11.h>
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <sstream>
using namespace std::chrono_literals;
namespace {
bool probe_device(D3D_DRIVER_TYPE driver) {
ID3D11Device* device = nullptr;
if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, 0, nullptr, 0,
D3D11_SDK_VERSION, &device, nullptr, nullptr))) return false;
IDXGIDevice* dxgi = nullptr;
if (SUCCEEDED(device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi)))) {
IDXGIAdapter* adapter = nullptr;
if (SUCCEEDED(dxgi->GetAdapter(&adapter))) {
DXGI_ADAPTER_DESC desc{};
if (SUCCEEDED(adapter->GetDesc(&desc))) std::printf("DEVICE %s: %ls\n",
driver == D3D_DRIVER_TYPE_WARP ? "WARP" : "hardware", desc.Description);
adapter->Release();
}
dxgi->Release();
}
device->Release(); return true;
}
void require_frame(bool value, const char* message) {
if (!value) throw std::runtime_error(message);
}
struct Gate {
std::mutex mutex;
std::condition_variable changed;
bool entered = false, released = false;
void block() {
std::unique_lock lock(mutex);
entered = true; changed.notify_all();
if (!changed.wait_for(lock, 30s, [&] { return released; })) throw std::runtime_error("gate deadline");
}
void wait() {
std::unique_lock lock(mutex);
require_frame(changed.wait_for(lock, 10s, [&] { return entered; }), "gate did not enter");
}
void release() { std::lock_guard lock(mutex); released = true; changed.notify_all(); }
};
template<class Predicate> void wait_for_frame(Predicate done) {
const auto deadline = std::chrono::steady_clock::now() + 10s;
while (!done()) {
require_frame(std::chrono::steady_clock::now() < deadline, "frame wait deadline");
std::this_thread::yield();
}
}
std::string canonical(const settlement::World& value) {
std::ostringstream stream(std::ios::binary);
value.write_save(stream, settlement::WorldSaveFormat::Current14);
return stream.str();
}
void frame_only(HWND window) {
SendMessageW(window, WM_TIMER, frame_timer_id, 0);
UpdateWindow(window);
if (scene_window) UpdateWindow(scene_window);
}
void event_and_frame(HWND window) {
SendMessageW(window, WM_TIMER, timer_id, 0);
frame_only(window);
}
std::vector<std::uint32_t> capture_frame(settlement::viewer::D3DScene& renderer,
const std::shared_ptr<const PreparedFrame>& frame) {
std::vector<std::uint32_t> pixels;
require_frame(frame && frame->content && renderer.render(frame->content->geometry, frame->view, &pixels), "capture frame");
return pixels;
}
void drag(HWND window, bool left, int dx, int dy) {
const auto start = MAKELPARAM(420, 220), finish = MAKELPARAM(420 + dx, 220 + dy);
SendMessageW(window, left ? WM_LBUTTONDOWN : WM_MBUTTONDOWN, 0, start);
SendMessageW(window, WM_MOUSEMOVE, left ? MK_LBUTTON : MK_MBUTTON, finish);
SendMessageW(window, left ? WM_LBUTTONUP : WM_MBUTTONUP, 0, finish);
}
}
int main() {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto worker = std::make_shared<Gate>(), writer = std::make_shared<Gate>(), installer = std::make_shared<Gate>();
auto reader = std::make_shared<Gate>();
std::atomic<bool> block_worker{false}, block_install{false}, block_reader{false};
std::atomic<DWORD> worker_thread{0};
HWND window = nullptr;
std::unique_ptr<settlement::SaveService> saves;
wchar_t temporary[MAX_PATH]{}; GetTempPathW(MAX_PATH, temporary);
const auto folder = std::filesystem::path(temporary) / (L"settlement-frames-" + std::to_wstring(GetCurrentProcessId()));
std::filesystem::create_directories(folder);
SetEnvironmentVariableW(L"LOCALAPPDATA", folder.c_str());
try {
auto colony = settlement::make_first_colony(2);
std::istringstream input(canonical(*colony), std::ios::binary);
settlement::WorkerPoolOptions workers;
workers.before_execute = [&](std::size_t) {
if (block_worker.exchange(false)) { worker_thread = GetCurrentThreadId(); worker->block(); }
};
auto owned = settlement::World::read_save(input, 2, settlement::ExecutionMode::Parallel, std::move(workers));
auto id = Void::Uuid::try_v4(); auto rules = settlement::default_rules_manifest();
require_frame(id.has_value() && rules.has_value(), "fixture identity/rules");
settlement::viewer::ViewerSessionOptions options;
options.runtime.clock = clock;
options.runtime.observer = [&](settlement::RuntimePhase phase) {
if (phase == settlement::RuntimePhase::BeforeInstallCapture && block_install.exchange(false)) installer->block();
};
options.files.read_observer = [&](settlement::CheckpointReadPhase phase) {
if (phase == settlement::CheckpointReadPhase::BeforeRead && block_reader.exchange(false)) reader->block();
};
session = std::make_unique<settlement::viewer::ViewerSession>(
settlement::WorldCheckpoint{std::move(owned), *id, 1, *rules}, 2, std::move(options));
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls);
WNDCLASSEXW klass{}; klass.cbSize = sizeof(klass); klass.hInstance = GetModuleHandleW(nullptr);
klass.lpfnWndProc = window_proc; klass.lpszClassName = window_class;
require_frame(RegisterClassExW(&klass) != 0, "register viewer");
window = CreateWindowExW(0, window_class, L"Prepared frame regression", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
0, 0, 1120, 752, nullptr, nullptr, klass.hInstance, nullptr);
require_frame(window != nullptr && scene_window != nullptr, "real main and scene windows");
ShowWindow(window, SW_SHOW);
KillTimer(window, timer_id); KillTimer(window, frame_timer_id); // Test drives each timer explicitly.
world = session->world(); has_session = true; show_title_screen(window, false);
const bool warp_device = probe_device(D3D_DRIVER_TYPE_WARP);
const bool hardware_device = probe_device(D3D_DRIVER_TYPE_HARDWARE);
if (!graphics.ready()) {
require_frame(!warp_device && !hardware_device, "renderer failed despite available D3D device");
std::puts("SKIP D3D11 hardware and WARP unavailable; real frame assertions require a backend");
DestroyWindow(window); session.reset(); std::filesystem::remove_all(folder); return 77;
}
event_and_frame(window);
require_frame(prepared_frame && prepared_frame->content && graphics.frames() > 0, "first real child render");
settlement::viewer::D3DScene offscreen;
const bool warp = offscreen.initialize(nullptr, true);
if (!warp) {
require_frame(!warp_device, "WARP renderer failed despite available device");
require_frame(offscreen.initialize(nullptr), "offscreen hardware fallback");
}
std::printf("BACKEND offscreen %s; visible D3D11 swap chain\n", warp ? "WARP" : "hardware");
// Ensure ticking has been admitted before holding an actual World worker.
event_and_frame(window);
auto sync = session->runtime().synchronize();
require_frame(sync.admission == settlement::RuntimeAdmission::Accepted && sync.completion.wait_for(10s) == std::future_status::ready, "owner synchronized");
event_and_frame(window);
block_worker = true; require_frame(clock->advance(50ms).has_value(), "clock advance");
session->runtime().notify_clock(); worker->wait();
require_frame(worker_thread != GetCurrentThreadId(), "worker is not UI thread");
const auto original = session->runtime().latest();
const auto original_bytes = canonical(*original->world);
auto encoded = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
require_frame(encoded.has_value(), "encode full snapshot");
settlement::SaveServiceOptions save_options;
save_options.fault_hook = [&](settlement::SavePhase phase) -> std::uint32_t {
if (phase == settlement::SavePhase::WriteStage) writer->block();
return 0;
};
saves = std::make_unique<settlement::SaveService>(std::move(save_options));
const auto path = folder / L"held.settlement";
auto saved = saves->try_submit({path, original->world->tick(), original->identity.session, [original] {
auto bytes = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
if (!bytes) throw std::runtime_error("encode save");
return *bytes;
}});
require_frame(saved.admission == settlement::SaveAdmission::Accepted, "writer admitted"); writer->wait();
const auto initial = prepared_frame;
const auto pixels = capture_frame(offscreen, initial);
const auto uploads = graphics.uploads(), frames = graphics.frames();
POINT anchor{420, 220}; ClientToScreen(window, &anchor);
SendMessageW(window, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), MAKELPARAM(anchor.x, anchor.y));
frame_only(window);
require_frame(prepared_frame->view.scale != initial->view.scale && graphics.frames() > frames, "frame timer alone presents wheel");
require_frame(prepared_frame->content->geometry == initial->content->geometry && graphics.uploads() == uploads, "zoom reuses CPU/GPU geometry");
require_frame(capture_frame(offscreen, prepared_frame) != pixels, "zoom changes rendered pixels");
const auto before_drag = prepared_frame;
drag(window, false, 35, 18); frame_only(window);
require_frame(prepared_frame->view.origin_x != before_drag->view.origin_x, "middle drag changes frame");
const auto before_left = prepared_frame;
drag(window, true, -24, 16); frame_only(window);
require_frame(prepared_frame->view.origin_y != before_left->view.origin_y, "left drag changes frame");
require_frame(graphics.uploads() == uploads && prepared_frame->content->geometry == initial->content->geometry, "both drags reuse upload");
const auto prior_building_view = prepared_frame->content->geometry;
SendMessageW(window, WM_COMMAND, building_view_id, 0); frame_only(window);
require_frame(prepared_frame->content->geometry != prior_building_view, "building visibility invalidates geometry");
const auto stable_frames = graphics.frames();
frame_only(window); frame_only(window);
require_frame(graphics.frames() == stable_frames, "unchanged frame timer does no rendering");
require_frame(session->runtime().latest() == original && canonical(*original->world) == original_bytes, "blocked world snapshot/tick unchanged");
std::puts("PASS wheel and both real drags/rendered pixels while World worker and WriteStage held; frame timer independent; geometry/upload reused");
// Dirty work arriving inside a nested paint must survive the outer paint.
bool nested = false;
frame_test_during_paint = [&] {
if (nested) return; nested = true;
camera.pan(9, 0); invalidate_scene(window);
SendMessageW(scene_window, WM_PAINT, 0, 0);
};
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
require_frame(frame_requests != sampled_request, "nested paint leaves dirty request pending");
frame_only(window); require_frame(frame_requests == sampled_request, "next frame consumes nested dirty request");
// An exposure paint can nest without changing camera or world content.
frame_test_during_paint = [&] { SendMessageW(scene_window, WM_PAINT, 0, 0); };
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
const auto exposed_frames = graphics.frames();
frame_only(window);
require_frame(graphics.frames() > exposed_frames, "nested unchanged exposure is repainted");
// Owned overlay data and old geometry survive later edits/publications.
blueprint.push_back({{6, 10}, settlement::RecipeId::BuildBed});
room_blueprints.push_back({{20, 20}, {23, 23}, settlement::RoomSide::North});
selected_resident = world->agents().front().id;
invalidate_scene(window); frame_only(window);
const auto overlay = prepared_frame;
const auto old_pixels = capture_frame(offscreen, overlay);
blueprint.clear(); room_blueprints.clear(); selected_resident.reset();
invalidate_scene(window); frame_only(window);
require_frame(prepared_frame->content->geometry != overlay->content->geometry, "overlay invalidates geometry");
capture_frame(offscreen, prepared_frame);
require_frame(capture_frame(offscreen, overlay) == old_pixels && overlay->view.blueprint.size() == 1 && overlay->view.room_blueprints.size() == 1,
"retained old packet owns overlays and reuploads correct mesh");
worker->release(); writer->release();
require_frame(saved.completion.wait_for(10s) == std::future_status::ready && saved.completion.get().succeeded(), "held save completes");
saves.reset();
std::ifstream saved_file(path, std::ios::binary);
const std::string saved_bytes{std::istreambuf_iterator<char>(saved_file), {}}; saved_file.close();
require_frame(saved_bytes == *encoded, "saved bytes match full captured World and metadata");
std::puts("PASS nested paints retain pending dirt; retained packet/overlays; saved full canonical World and checkpoint metadata");
// A real file reader can remain blocked while the old presentation moves.
block_reader = true; handle_save_menu(window, false, path); reader->wait();
const auto before_read = prepared_frame;
drag(window, false, 12, 8); frame_only(window);
require_frame(session->changing_world() && prepared_frame->content == before_read->content &&
prepared_frame->view.origin_x != before_read->view.origin_x, "camera while file reader held");
reader->release();
std::puts("PASS real asynchronous file reader held while camera presents the prior packet");
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
// Deterministically publish between poll_changes' not-ready check and
// pump_session's world fetch, including nested paints in that interval.
auto install_race = [&](bool absent) {
installer = std::make_shared<Gate>(); block_install = true;
if (absent) { world.reset(); prepared_frame.reset(); }
const auto prior_world = world;
const auto prior_frame = prepared_frame;
session->new_colony();
event_and_frame(window); installer->wait();
const auto prior_session = session->runtime().latest()->identity.session;
bool injected = false;
frame_test_after_poll = [&] {
if (injected) return; injected = true;
require_frame(session->changing_world(), "poll still changing before install completion");
installer->release();
wait_for_frame([&] { return session->runtime().latest()->identity.session != prior_session; });
SendMessageW(window, WM_PAINT, 0, 0);
SendMessageW(scene_window, WM_PAINT, 0, 0);
};
SendMessageW(window, WM_TIMER, timer_id, 0);
frame_test_after_poll = {};
frame_only(window);
require_frame(world == prior_world, "pre-Replaced published candidate must not escape, including null");
require_frame(!prepared_frame->content || (prior_frame && prepared_frame->content == prior_frame->content), "old presentation content remains pinned");
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
require_frame(world == session->world() && prepared_frame->content->world == world &&
blueprint.empty() && room_blueprints.empty() && !selected_resident && camera.scale() == 1.0, "Replaced clears overlays/selection/camera before release");
};
install_race(false); install_race(true);
std::puts("PASS real publication race after poll/not-ready, nested main/child paints, old/null fence and Replaced reset");
const auto visible = prepared_frame;
const auto visible_frames = graphics.frames();
ShowWindow(window, SW_HIDE); drag(window, false, 10, 10); frame_only(window);
require_frame(prepared_frame == visible && graphics.frames() == visible_frames, "hidden suppresses preparation/render");
const auto hidden_command = session->submit(settlement::CommandPayload{settlement::CommandKind::SetPriority, {}, 2});
require_frame(hidden_command.has_value(), "hidden command admitted");
wait_for_frame([&] { event_and_frame(window); return !session->pending(*hidden_command); });
require_frame(prepared_frame == visible && world != visible->content->world, "hidden retains packet while world publishes");
ShowWindow(window, SW_SHOW); frame_only(window);
require_frame(prepared_frame->content->world == world, "restore presents latest accepted snapshot");
ShowWindow(window, SW_MINIMIZE); const auto minimized = prepared_frame;
invalidate_scene(window); frame_only(window);
require_frame(prepared_frame == minimized, "minimized suppresses preparation");
ShowWindow(window, SW_RESTORE); frame_only(window);
show_title_screen(window, true); const auto title_frame = prepared_frame;
invalidate_scene(window); frame_only(window); require_frame(prepared_frame == title_frame, "title suppresses preparation");
show_title_screen(window, false); frame_only(window);
const auto restore = prepared_frame;
const auto size_uploads = graphics.uploads();
SetWindowPos(window, nullptr, 0, 0, 1200, 800, SWP_NOMOVE | SWP_NOZORDER); frame_only(window);
require_frame(prepared_frame->content->geometry == restore->content->geometry && graphics.uploads() > size_uploads, "resize reuses CPU mesh and invalidates upload");
const auto zero_frames = graphics.frames();
SetWindowPos(scene_window, nullptr, 0, map_top, 0, 0, SWP_NOZORDER);
InvalidateRect(scene_window, nullptr, FALSE); SendMessageW(scene_window, WM_PAINT, 0, 0);
require_frame(graphics.frames() == zero_frames, "zero-sized real viewport suppresses render");
layout_scene(window); frame_only(window);
auto zero_view = prepared_frame->view; zero_view.height = 0;
require_frame(!offscreen.render(prepared_frame->content->geometry, zero_view), "zero viewport rejected");
auto bad_frame = std::make_shared<PreparedFrame>(*prepared_frame); bad_frame->view.height = 0;
prepared_frame = bad_frame;
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_only(window);
require_frame(!graphics.ready() && !prepared_frame->backend_ready, "render failure reaches current error HUD");
show_title_screen(window, true); show_title_screen(window, false); frame_only(window);
require_frame(graphics.ready() && prepared_frame->backend_ready, "menu retry recovers backend");
const auto reset_uploads = offscreen.uploads();
offscreen.reset(); require_frame(offscreen.initialize(nullptr, warp), "recreate offscreen backend");
require_frame(capture_frame(offscreen, overlay) == old_pixels && offscreen.uploads() > reset_uploads, "backend reset reuploads retained packet");
std::puts("PASS hidden/minimized/title/restore, resize, zero viewport, error HUD/recovery and backend reset");
const auto final_frames = graphics.frames();
frame_test_during_paint = [&] { DestroyWindow(window); };
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
window_proc(window, WM_TIMER, frame_timer_id, 0); window_proc(window, WM_TIMER, timer_id, 0);
require_frame(viewer_destroyed && !prepared_frame && !graphics.ready() && graphics.frames() == final_frames, "queued timers after destruction ignored");
window = nullptr; session.reset(); std::filesystem::remove_all(folder);
std::puts("PASS destruction and queued timers; no physical refresh-rate claim");
return 0;
} catch (const std::exception& error) {
frame_test_after_poll = {}; frame_test_during_paint = {};
worker->release(); writer->release(); installer->release(); reader->release();
saves.reset(); if (window) DestroyWindow(window); session.reset();
std::fprintf(stderr, "FAIL %s\n", error.what()); return 1;
}
}
+6 -7
View File
@@ -87,16 +87,18 @@ bool has(const std::vector<ViewerEvent>& events, ViewerEventKind kind) {
return std::any_of(events.begin(), events.end(), [kind](const auto& event) { return event.kind == kind; });
}
void flush_owner(ViewerSession& session) {
void flush_owner(ViewerSession& session, RuntimeOutcome expected = RuntimeOutcome::Completed) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
for (;;) {
auto sync = session.runtime().synchronize();
if (sync.admission == RuntimeAdmission::Busy) {
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
continue;
}
require(sync.admission == RuntimeAdmission::Accepted);
require(sync.completion.wait_for(5s) == std::future_status::ready);
require(sync.completion.get().outcome == RuntimeOutcome::Completed);
require(sync.completion.wait_until(deadline) == std::future_status::ready);
require(sync.completion.get().outcome == expected);
return;
}
}
@@ -359,10 +361,7 @@ Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
require(rejected_save);
session.set_ticking(false);
static_cast<void>(session.poll());
auto suspended = session.runtime().synchronize();
require(suspended.admission == RuntimeAdmission::Accepted);
require(suspended.completion.wait_for(5s) == std::future_status::ready);
require(suspended.completion.get().outcome == RuntimeOutcome::Faulted);
flush_owner(session, RuntimeOutcome::Faulted);
static_cast<void>(session.poll());
session.load(files.root / "recover.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
-392
View File
@@ -1,392 +0,0 @@
#include "settlement/core/voxel_navigation.hpp"
#include "settlement/core/worker_pool.hpp"
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <future>
#include <limits>
#include <queue>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace settlement;
using Status = VoxelNavigationStatus;
using Void::Testing::Test;
void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
Void::Uuid::Uuid epoch(std::uint8_t value = 1) {
Void::Uuid::Uuid result;
result.bytes.back() = value;
return result;
}
template<class Material>
void install(VoxelRegion& world, ChunkCoordinate chunk, Material material) {
std::array<MaterialId, voxel_chunk_cells> cells{};
for (std::uint8_t z = 0; z < 32; ++z) for (std::uint8_t y = 0; y < 32; ++y) for (std::uint8_t x = 0; x < 32; ++x) {
const auto p = join_voxel(chunk, {x, y, z});
if (p && world.descriptor().bounds.contains(*p)) cells[*voxel_index({x, y, z})] = material(*p);
}
auto candidate = world.prepare_restored(chunk, 1, cells);
require(candidate.has_value(), "valid fixture page refused");
require(world.activate(std::span(&*candidate, 1)).has_value(), "valid fixture activation refused");
}
void edit(VoxelRegion& world, VoxelPosition p, MaterialId material) {
const VoxelEdit change{p, material, world.sample(p).stamp.revision};
require(world.edit(std::span(&change, 1)).has_value(), "fixture edit refused");
}
VoxelRegion flat(VoxelBounds bounds = {{0, 0, 0}, {8, 8, 4}}) {
VoxelRegion world({1, 42, 1, bounds});
const auto low = split_voxel({static_cast<std::int32_t>(bounds.lower.x), static_cast<std::int32_t>(bounds.lower.y), static_cast<std::int32_t>(bounds.lower.z)}).chunk;
const auto high = split_voxel({static_cast<std::int32_t>(bounds.upper.x - 1), static_cast<std::int32_t>(bounds.upper.y - 1), static_cast<std::int32_t>(bounds.upper.z - 1)}).chunk;
for (auto z = low.z; z <= high.z; ++z) for (auto y = low.y; y <= high.y; ++y) for (auto x = low.x; x <= high.x; ++x) {
install(world, {x, y, z}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
}
return world;
}
VoxelPathRequest request(const VoxelRegion& world, VoxelPosition start, std::vector<VoxelPosition> goals) {
return {world.descriptor().id, epoch(), start, world.descriptor().bounds, std::move(goals), {}};
}
VoxelRegion stairs(bool closed) {
VoxelRegion world({7, 42, 1, {{28, 0, 0}, {38, 3, 8}}});
for (int x : {0, 1}) install(world, {x, 0, 0}, [closed](auto p) {
const auto height = std::clamp(p.x - 31, 0, 3);
if (p.z <= height) return MaterialId::Stone;
if ((p.y == 0 || p.y == 2) && p.z <= height + 2) return MaterialId::Stone;
if (p.x == 30 && p.y == 1 && (p.z == 1 || p.z == 2)) return closed ? MaterialId::DoorClosed : MaterialId::DoorOpen;
return MaterialId::Air;
});
return world;
}
void require_route(const VoxelRegion& world, const VoxelPathRequest& query, const VoxelPathResult& result) {
require(result.status == Status::Reachable && result.goal.has_value(), "expected a reachable goal");
require(result.cost == result.route.size(), "cost differs from actual route");
auto from = query.start;
for (auto to : result.route) {
require(voxel_transition(world, query.session, from, to).status == Status::Reachable, "returned route crosses invalid transition");
from = to;
}
require(from == *result.goal && result.consulted.current(world, query.session), "route target or read stamps invalid");
require(std::is_sorted(result.consulted.chunks.begin(), result.consulted.chunks.end(),
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }), "read stamps not canonical");
}
struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : Void::Testing::Suite<VoxelNavigationTests> {
[[= Void::Testing::tag("voxel-navigation")]] Test doorway_stairs_and_upper_work_contact();
[[= Void::Testing::tag("voxel-navigation")]] Test support_edit_invalidates_route_before_next_step();
[[= Void::Testing::tag("voxel-navigation")]] Test body_headroom_and_step_sweep_are_required();
[[= Void::Testing::tag("voxel-navigation")]] Test missing_support_page_and_negative_answer_are_dependencies();
[[= Void::Testing::tag("voxel-navigation")]] Test known_blockers_do_not_require_unrelated_missing_data();
[[= Void::Testing::tag("voxel-navigation")]] Test reachable_missing_frontier_waits_for_actual_gateway();
[[= Void::Testing::tag("voxel-navigation")]] Test unrepresentable_vector_capacity_is_a_bounded_refusal();
[[= Void::Testing::tag("voxel-navigation")]] Test interaction_contacts_outside_window_need_frontier_evidence();
[[= Void::Testing::tag("voxel-navigation")]] Test unchanged_chunks_and_old_snapshots_remain_usable();
[[= Void::Testing::tag("voxel-navigation")]] Test bounded_search_has_distinct_incomplete_and_error_results();
[[= Void::Testing::tag("voxel-navigation")]] Test invalid_same_goal_and_extreme_coordinate_windows();
[[= Void::Testing::tag("voxel-navigation")]] Test goals_and_neighbors_have_stable_shortest_ties();
[[= Void::Testing::tag("voxel-navigation")]] Test shortest_costs_match_exhaustive_small_grid();
[[= Void::Testing::tag("voxel-navigation")]] Test real_parallel_queries_preserve_route_and_readsets();
};
Test VoxelNavigationTests::doorway_stairs_and_upper_work_contact() {
auto world = stairs(true);
auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
auto blocked = find_voxel_path(world, query);
require(blocked.status == Status::Unreachable, "closed two-cell door was passable");
const std::array changes{VoxelEdit{{30, 1, 1}, MaterialId::DoorOpen, 1}, VoxelEdit{{30, 1, 2}, MaterialId::DoorOpen, 1}};
require(world.edit(changes).has_value(), "door opening failed");
require(!blocked.consulted.current(world, epoch()), "door change retained negative result");
auto found = find_voxel_path(world, query);
require_route(world, query, found);
require(found.cost == 7 && std::any_of(found.route.begin(), found.route.end(), [](auto p) { return p.x == 32 && p.z == 2; }), "path failed actual border stair");
edit(world, {37, 1, 4}, MaterialId::Stone);
auto work = find_voxel_interaction_path(world, query, {37, 1, 4});
require_route(world, query, work);
require(work.goal == VoxelPosition{36, 1, 4}, "upper work position lacks direct face contact");
}
Test VoxelNavigationTests::support_edit_invalidates_route_before_next_step() {
auto world = stairs(false);
const auto query = request(world, {32, 1, 2}, {{36, 1, 4}});
auto found = find_voxel_path(world, query);
require_route(world, query, found);
const auto held = world;
edit(world, {33, 1, 2}, MaterialId::Air);
require(!found.consulted.current(world, epoch()), "support change did not expire route");
require(voxel_standing(world, epoch(), query.start).status == Status::Reachable, "future support edit invalidated current foot");
require(voxel_transition(world, epoch(), query.start, found.route.front()).status == Status::Unreachable, "unsafe stored next step still allowed");
require(find_voxel_path(world, query).status == Status::Unreachable, "missing stair allowed a two-cell rise");
require(found.consulted.current(held, epoch()), "retained immutable geometry changed");
edit(world, {33, 1, 2}, MaterialId::Stone);
require_route(world, query, find_voxel_path(world, query));
}
Test VoxelNavigationTests::body_headroom_and_step_sweep_are_required() {
auto world = flat();
require(voxel_standing(world, epoch(), {2, 2, 1}).status == Status::Reachable, "ordinary stance refused");
edit(world, {3, 2, 1}, MaterialId::Stone);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "single stair refused");
edit(world, {2, 2, 3}, MaterialId::Stone);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Unreachable, "step rose through source ceiling");
require(voxel_transition(world, epoch(), {3, 2, 2}, {2, 2, 1}).status == Status::Unreachable, "step descended through swept ceiling");
edit(world, {2, 2, 3}, MaterialId::Air);
edit(world, {3, 2, 3}, MaterialId::DoorClosed);
require(voxel_standing(world, epoch(), {3, 2, 2}).status == Status::Unreachable, "head entered closed upper door");
edit(world, {3, 2, 3}, MaterialId::DoorOpen);
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "open door blocked head");
require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 3, 1}).status == Status::Unreachable, "diagonal corner cutting accepted");
require(voxel_transition(world, epoch(), {2, 2, 1}, {2, 2, 2}).status == Status::Unreachable, "unsupported vertical movement accepted");
}
Test VoxelNavigationTests::missing_support_page_and_negative_answer_are_dependencies() {
VoxelRegion world({1, 42, 1, {{-3, 0, -1}, {3, 3, 4}}});
install(world, {-1, 0, 0}, [](auto) { return MaterialId::Air; });
install(world, {0, 0, 0}, [](auto) { return MaterialId::Air; });
auto check = voxel_standing(world, epoch(), {-1, 1, 0});
require(check.status == Status::Unavailable, "unloaded support treated as empty or solid");
require(std::any_of(check.consulted.chunks.begin(), check.consulted.chunks.end(), [](const auto& s) { return s.coordinate == ChunkCoordinate{-1, 0, -1} && s.availability == VoxelAvailability::Unavailable; }), "missing support page omitted from reads");
install(world, {-1, 0, -1}, [](auto) { return MaterialId::Stone; });
require(!check.consulted.current(world, epoch()), "missing-to-loaded support kept stale result");
require(voxel_standing(world, epoch(), {-1, 1, 0}).status == Status::Reachable, "new support still unavailable");
auto query = request(world, {-1, 1, 0}, {{1, 1, 0}});
auto negative = find_voxel_path(world, query);
require(negative.status == Status::Unavailable, "missing route support was proven unreachable");
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
require(!negative.consulted.current(world, epoch()), "negative path omitted queried missing chunk");
require_route(world, query, find_voxel_path(world, query));
}
Test VoxelNavigationTests::known_blockers_do_not_require_unrelated_missing_data() {
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
install(world, {0, 0, 0}, [](auto p) {
return p.z == 0 || (p.x == 2 && p.z <= 2) ? MaterialId::Stone : MaterialId::Air;
});
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
auto result = find_voxel_path(world, query);
require(result.status == Status::Unreachable, "solid floor and closed wall unnecessarily wait for missing lower page");
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::Unreachable,
"loaded interaction behind known wall unnecessarily waits for missing lower page");
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
return s.coordinate == ChunkCoordinate{0, 0, -1} && s.availability == VoxelAvailability::Unavailable;
}), "conclusively blocked reads lost their actual dependency stamps");
query.goals = {{35, 5, 1}};
result = find_voxel_path(world, query);
require(result.status == Status::Unreachable, "disconnected unknown goal manufactured reachable frontier");
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
return s.coordinate == ChunkCoordinate{1, 0, 0} && s.availability == VoxelAvailability::Unavailable;
}), "unknown goal reads were not retained");
query.goals = {{5, 5, 1}};
query.search_bounds.upper = {8, 6, 4};
require(find_voxel_path(world, query).status == Status::SearchBoundary,
"actual reachable window exit was replaced by irrelevant missing data");
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
query.search_bounds = world.descriptor().bounds;
require(find_voxel_path(world, query).status == Status::Unreachable,
"lower-page activation changed proven blocked reachability");
for (int x : {0, 1}) for (int z : {1, 2}) edit(world, {x, 3, z}, MaterialId::Stone);
query.goals = {{1, 5, 1}};
query.search_bounds.upper.x = 2;
require(find_voxel_path(world, query).status == Status::Unreachable,
"known blocked transitions beyond search window manufactured an exit");
}
Test VoxelNavigationTests::reachable_missing_frontier_waits_for_actual_gateway() {
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
const auto floor = [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; };
install(world, {0, 0, 0}, floor);
auto blocked_goal = request(world, {1, 1, 1}, {{5, 5, 1}});
edit(world, {5, 5, 2}, MaterialId::Stone);
require(find_voxel_path(world, blocked_goal).status == Status::Unreachable,
"missing branch elsewhere manufactured access to conclusively blocked goal");
edit(world, {5, 5, 2}, MaterialId::Air);
auto query = request(world, {1, 1, 1}, {{35, 5, 1}});
auto pending = find_voxel_path(world, query);
require(pending.status == Status::Unavailable, "reachable missing gateway was proven unreachable");
install(world, {1, 0, 0}, floor);
require(!pending.consulted.current(world, epoch()), "gateway activation did not invalidate pending answer");
auto result = find_voxel_path(world, query);
require_route(world, query, result);
require(result.cost == 38, "loaded gateway changed shortest path cost");
}
Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.limits.max_dependencies = std::vector<ChunkStamp>{}.max_size() + 1;
query.limits.max_scratch_bytes = std::numeric_limits<std::size_t>::max();
require(find_voxel_path(world, query).status == Status::LimitExceeded, "unrepresentable read reserve escaped path API");
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::LimitExceeded,
"unrepresentable read reserve escaped interaction API");
require(voxel_standing(world, epoch(), query.start, query.limits).status == Status::LimitExceeded,
"unrepresentable read reserve escaped stance API");
require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded,
"unrepresentable read reserve escaped transition API");
}
Test VoxelNavigationTests::interaction_contacts_outside_window_need_frontier_evidence() {
auto world = flat();
edit(world, {3, 3, 1}, MaterialId::Stone);
for (auto blocker : {VoxelPosition{2, 3, 2}, VoxelPosition{3, 2, 2}, VoxelPosition{3, 4, 2}, VoxelPosition{3, 3, 3}}) {
edit(world, blocker, MaterialId::Stone);
}
auto query = request(world, {1, 1, 1}, {});
query.search_bounds.upper.x = 6;
auto complete = find_voxel_interaction_path(world, query, {3, 3, 1});
require_route(world, query, complete);
require(complete.goal == VoxelPosition{4, 3, 1}, "expanded window did not reach sole valid contact");
query.search_bounds.upper.x = 4;
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::SearchBoundary,
"clipped valid interaction contact was classified globally unreachable");
// A valid omitted goal cannot manufacture an exit from an enclosed start.
for (auto p : {VoxelPosition{0, 1, 1}, VoxelPosition{1, 0, 1}, VoxelPosition{1, 2, 1}, VoxelPosition{2, 1, 1}}) {
edit(world, p, MaterialId::Stone);
edit(world, {p.x, p.y, 2}, MaterialId::Stone);
}
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::Unreachable,
"omitted contact manufactured an escape from a known enclosed start");
// The only useful contact is beyond x=31, in an unavailable page.
VoxelRegion pending({1, 42, 1, {{0, 0, 0}, {40, 8, 4}}});
install(pending, {0, 0, 0}, [](auto p) {
if (p.z == 0 || p == VoxelPosition{31, 3, 1}) return MaterialId::Stone;
if (p == VoxelPosition{30, 3, 2} || p == VoxelPosition{31, 2, 2} ||
p == VoxelPosition{31, 4, 2} || p == VoxelPosition{31, 3, 3}) return MaterialId::Stone;
return MaterialId::Air;
});
auto partial = request(pending, {29, 1, 1}, {});
partial.search_bounds.upper.x = 32;
const auto waiting = find_voxel_interaction_path(pending, partial, {31, 3, 1});
require(waiting.status == Status::Unavailable, "unresolved interaction exit was proven unreachable");
install(pending, {1, 0, 0}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
require(!waiting.consulted.current(pending, epoch()), "missing omitted contact was absent from dependencies");
require(find_voxel_interaction_path(pending, partial, {31, 3, 1}).status == Status::SearchBoundary,
"loaded omitted contact failed to expose reachable window exit");
partial.search_bounds.upper.x = 36;
auto reached = find_voxel_interaction_path(pending, partial, {31, 3, 1});
require_route(pending, partial, reached);
require(reached.goal == VoxelPosition{32, 3, 1}, "expanded gateway did not expose actual contact");
}
Test VoxelNavigationTests::unchanged_chunks_and_old_snapshots_remain_usable() {
auto world = flat({{0, 0, 0}, {100, 8, 4}});
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.search_bounds.upper.x = 8;
auto route = find_voxel_path(world, query);
require_route(world, query, route);
edit(world, {97, 2, 1}, MaterialId::Stone);
require(route.consulted.current(world, epoch()), "unconsulted page invalidated a path");
require(!route.consulted.current(world, epoch(2)), "old session accepted same numeric revisions");
VoxelRegion other({2, 42, 1, world.descriptor().bounds});
require(!route.consulted.current(other, epoch()), "another region accepted old route");
}
Test VoxelNavigationTests::bounded_search_has_distinct_incomplete_and_error_results() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
query.limits.max_vertices = 1;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "vertex budget fabricated unreachable");
query.limits = {}; query.limits.max_scratch_bytes = 8;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "scratch budget ignored");
query.limits = {}; query.limits.max_steps = 1;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "traversal budget fabricated unreachable");
query.limits = {}; query.limits.max_samples = 2;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "material query budget ignored");
query.limits = {}; query.limits.max_dependencies = 0;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "read-set bound ignored");
query.limits = {}; query.limits.max_goals = 0;
require(find_voxel_path(world, query).status == Status::LimitExceeded, "goal bound ignored");
query.limits = {};
std::stop_source cancelled; cancelled.request_stop();
require(find_voxel_path(world, query, cancelled.get_token()).status == Status::Cancelled, "cancellation fabricated unreachable");
auto clipped_interaction = query;
clipped_interaction.search_bounds.upper = {2, 2, 4};
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::SearchBoundary,
"interaction with all feet clipped fabricated invalid input");
clipped_interaction.region = 2;
require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::InvalidInput,
"clipped interaction bypassed region identity");
query.search_bounds.upper.x = 4; query.goals = {{3, 5, 1}};
for (int y = 0; y < 8; ++y) { edit(world, {2, y, 1}, MaterialId::Stone); edit(world, {2, y, 2}, MaterialId::Stone); }
// The accessible edge at x=0 has no escape (region bound), but y edges do
// not either. Make a window smaller than the region along y as well.
query.search_bounds.upper.y = 6;
require(find_voxel_path(world, query).status == Status::SearchBoundary, "clipped search claimed global unreachability");
VoxelRegion sparse({1, 42, 1, {{std::numeric_limits<std::int32_t>::min(), 0, 0}, {std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1, 8, 4}}});
auto huge = request(sparse, {0, 1, 1}, {{1, 1, 1}});
require(find_voxel_path(sparse, huge).status == Status::LimitExceeded, "sparse huge extent allocated densely");
}
Test VoxelNavigationTests::invalid_same_goal_and_extreme_coordinate_windows() {
auto world = flat();
auto query = request(world, {1, 1, 1}, {{1, 1, 1}});
auto same = find_voxel_path(world, query);
require_route(world, query, same);
require(same.route.empty() && same.cost == 0, "already-at-goal result wrong");
edit(world, {1, 1, 2}, MaterialId::Stone);
require(find_voxel_path(world, query).status == Status::Unreachable, "blocked start==goal bypassed geometry");
query.session = {};
require(find_voxel_path(world, query).status == Status::InvalidInput, "nil session accepted");
for (auto x : {std::numeric_limits<std::int32_t>::min(), std::numeric_limits<std::int32_t>::max() - 3}) {
const VoxelBounds b{{x, 0, 0}, {std::int64_t{x} + 4, 3, 4}};
auto edge = flat(b);
auto edge_query = request(edge, {x, 1, 1}, {{static_cast<std::int32_t>(std::int64_t{x} + 3), 1, 1}});
const auto route = find_voxel_path(edge, edge_query);
require_route(edge, edge_query, route);
require(route.cost == 3, "extreme coordinate route wrapped");
}
}
Test VoxelNavigationTests::goals_and_neighbors_have_stable_shortest_ties() {
auto world = flat();
auto query = request(world, {3, 3, 1}, {{4, 3, 1}, {2, 3, 1}, {3, 4, 1}});
auto result = find_voxel_path(world, query);
require(result.goal == VoxelPosition{2, 3, 1} && result.cost == 1, "equal goals depend on request order");
std::reverse(query.goals.begin(), query.goals.end());
require(find_voxel_path(world, query).route == result.route, "goal order changed route");
query.goals = {{4, 4, 1}};
result = find_voxel_path(world, query);
require(result.route == std::vector<VoxelPosition>{{3, 4, 1}, {4, 4, 1}}, "equal paths violated coordinate neighbor order");
}
Test VoxelNavigationTests::shortest_costs_match_exhaustive_small_grid() {
for (std::uint32_t pattern = 0; pattern < 16; ++pattern) {
std::array<bool, 49> walls{};
for (std::size_t i = 0; i < walls.size(); ++i) walls[i] = ((i * 13 + pattern * 7) % 17) < 4;
walls[8] = false; walls[40] = false;
auto world = flat({{0, 0, 0}, {7, 7, 4}});
std::vector<VoxelEdit> changes;
for (int y = 0; y < 7; ++y) for (int x = 0; x < 7; ++x) if (walls[static_cast<std::size_t>(x + 7 * y)]) {
changes.push_back({{x, y, 1}, MaterialId::Stone, 1}); changes.push_back({{x, y, 2}, MaterialId::Stone, 1});
}
require(world.edit(changes).has_value(), "small oracle fixture failed");
std::array<int, 49> distance; distance.fill(-1); distance[8] = 0;
std::queue<int> queue; queue.push(8);
while (!queue.empty()) {
const auto v = queue.front(); queue.pop();
for (auto d : std::array<std::array<int, 2>, 4>{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}) {
const int x = v % 7 + d[0], y = v / 7 + d[1];
if (x < 0 || x >= 7 || y < 0 || y >= 7) continue;
const auto n = static_cast<std::size_t>(x + 7 * y);
if (walls[n] || distance[n] >= 0) continue;
distance[n] = distance[static_cast<std::size_t>(v)] + 1; queue.push(static_cast<int>(n));
}
}
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
auto result = find_voxel_path(world, query);
if (distance[40] < 0) require(result.status == Status::Unreachable, "oracle blocked path found");
else {
require_route(world, query, result);
require(result.cost == static_cast<std::size_t>(distance[40]), "Void graph route differs from exhaustive grid cost");
}
}
}
Test VoxelNavigationTests::real_parallel_queries_preserve_route_and_readsets() {
const auto world = stairs(false);
const auto query = request(world, {29, 1, 1}, {{36, 1, 4}});
const auto expected = find_voxel_path(world, query);
require_route(world, query, expected);
for (std::size_t workers : {2U, 6U, 12U}) {
WorkerPool pool(workers);
std::vector<std::future<VoxelPathResult>> futures;
for (int i = 0; i < 12; ++i) futures.push_back(pool.submit([&] { return find_voxel_path(world, query); }));
std::reverse(futures.begin(), futures.end());
for (auto& future : futures) {
auto result = future.get();
require(result.status == expected.status && result.route == expected.route && result.goal == expected.goal &&
result.consulted.chunks == expected.consulted.chunks, "worker completion order altered navigation");
}
}
}
} // namespace
-479
View File
@@ -1,479 +0,0 @@
#include "settlement/core/voxel_region.hpp"
#include "settlement/core/worker_pool.hpp"
#include <Void/Core/Hash.hpp>
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <condition_variable>
#include <future>
#include <iostream>
#include <limits>
#include <mutex>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::Test;
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
constexpr auto exhausted = std::numeric_limits<std::uint64_t>::max();
void require(bool condition, const char* message = "voxel region invariant failed") {
if (!condition) throw std::runtime_error(message);
}
VoxelRegionDescriptor descriptor(VoxelBounds bounds = {{-64, -64, -32}, {64, 64, 32}}) {
return {7, 42, voxel_generator_version, bounds};
}
PreparedVoxelChunk generated(const VoxelRegion& region, ChunkCoordinate coordinate) {
auto candidate = region.prepare_generated(coordinate);
require(candidate.has_value(), "valid chunk generation refused");
return std::move(*candidate);
}
void activate(VoxelRegion& region, std::span<const ChunkCoordinate> coordinates) {
std::vector<PreparedVoxelChunk> candidates;
for (auto coordinate : coordinates) candidates.push_back(generated(region, coordinate));
require(region.activate(candidates).has_value(), "valid chunk activation refused");
}
VoxelEdit change(const VoxelRegion& region, VoxelPosition position) {
const auto sample = region.sample(position);
require(sample.availability == VoxelAvailability::Loaded);
return {position, sample.material == MaterialId::Air ? MaterialId::Stone : MaterialId::Air, sample.stamp.revision};
}
void equivalent(const VoxelRegion& left, const VoxelRegion& right) {
require(left.descriptor() == right.descriptor());
const auto a = left.directory(), b = right.directory();
require(a->size() == b->size());
for (std::size_t i = 0; i < a->size(); ++i) {
require((*a)[i].coordinate == (*b)[i].coordinate &&
(*a)[i].chunk->revision() == (*b)[i].chunk->revision());
require(std::equal((*a)[i].chunk->cells().begin(), (*a)[i].chunk->cells().end(), (*b)[i].chunk->cells().begin()),
"complete material pages differ");
}
}
template<class T> void error(const std::expected<T, VoxelError>& result, VoxelError expected) {
require(!result && result.error() == expected, "unexpected operation result");
}
bool contains(const std::vector<ChunkCoordinate>& coordinates, ChunkCoordinate coordinate) {
return std::binary_search(coordinates.begin(), coordinates.end(), coordinate);
}
struct [[= Void::Testing::name("VoxelRegionTests")]] VoxelRegionTests : Void::Testing::Suite<VoxelRegionTests> {
[[= Void::Testing::tag("voxel-region")]] Test signed_coordinates_and_x_fast_layout();
[[= Void::Testing::tag("voxel-region")]] Test descriptor_validation_and_sparse_extreme_bounds();
[[= Void::Testing::tag("voxel-region")]] Test generated_pages_have_fixed_materials_and_continuous_surface();
[[= Void::Testing::tag("voxel-region")]] Test preparation_order_and_worker_order_preserve_complete_pages();
[[= Void::Testing::tag("voxel-region")]] Test partial_pages_mask_outside_and_validate_import();
[[= Void::Testing::tag("voxel-region")]] Test availability_and_snapshot_lifetimes();
[[= Void::Testing::tag("voxel-region")]] Test atomic_multichunk_edit_reuses_unchanged_pages();
[[= Void::Testing::tag("voxel-region")]] Test refused_batches_and_identical_writes_preserve_publication();
[[= Void::Testing::tag("voxel-region")]] Test face_neighbors_and_unavailable_boundaries();
[[= Void::Testing::tag("voxel-region")]] Test activation_checks_source_duplicates_and_prior_publication();
[[= Void::Testing::tag("voxel-region")]] Test imported_revision_exhaustion_preserves_all_pages();
[[= Void::Testing::tag("voxel-region")]] Test page_edit_and_staging_budgets_are_atomic();
[[= Void::Testing::tag("voxel-region")]] Test doorway_crossing_two_chunks_opens_atomically();
[[= Void::Testing::tag("voxel-region")]] Test full_resident_directory_copies_one_changed_page();
};
Test VoxelRegionTests::signed_coordinates_and_x_fast_layout() {
constexpr std::array values{smallest, -33, -32, -1, 0, 31, 32, largest};
constexpr std::array chunks{-67108864, -2, -1, -1, 0, 0, 1, 67108863};
constexpr std::array locals{0, 31, 0, 31, 0, 31, 0, 31};
for (std::size_t i = 0; i < values.size(); ++i) {
for (auto y : values) for (auto z : values) {
const VoxelPosition position{values[i], y, z};
const auto address = split_voxel(position);
require(address.chunk.x == chunks[i] && address.local.x == locals[i]);
require(join_voxel(address.chunk, address.local) == position);
}
}
require(voxel_index({1, 0, 0}) == 1 && voxel_index({0, 1, 0}) == 32 &&
voxel_index({0, 0, 1}) == 1024 && voxel_index({31, 31, 31}) == voxel_chunk_cells - 1);
require(!voxel_index({32, 0, 0}) && !voxel_index({0, 255, 0}));
require(!join_voxel({67108864, 0, 0}, {}) && !join_voxel({-67108865, 0, 0}, {31, 0, 0}));
require(!join_voxel({}, {0, 0, 32}));
}
Test VoxelRegionTests::descriptor_validation_and_sparse_extreme_bounds() {
const auto rejected = [](VoxelRegionDescriptor definition) {
try { const VoxelRegion region(definition); }
catch (const std::invalid_argument&) { return true; }
return false;
};
auto definition = descriptor(); definition.id = 0; require(rejected(definition));
definition = descriptor(); definition.generator_version = 0; require(rejected(definition));
definition.generator_version = 2; require(rejected(definition));
definition = descriptor(); definition.bounds.upper.x = definition.bounds.lower.x; require(rejected(definition));
definition = descriptor(); definition.bounds.lower.z = std::int64_t{smallest} - 1; require(rejected(definition));
definition = descriptor(); definition.bounds.upper.y = std::int64_t{largest} + 2; require(rejected(definition));
VoxelRegion sparse(descriptor({{smallest, smallest, smallest},
{std::int64_t{largest} + 1, std::int64_t{largest} + 1, std::int64_t{largest} + 1}}));
require(sparse.directory()->empty() && sparse.resident_bytes() == sizeof(VoxelDirectory));
const std::array coordinates{ChunkCoordinate{-67108864, -67108864, -67108864},
ChunkCoordinate{67108863, 67108863, 67108863}};
activate(sparse, coordinates);
require(sparse.sample({smallest, smallest, smallest}).material == MaterialId::Stone);
require(sparse.sample({largest, largest, largest}).availability == VoxelAvailability::Loaded &&
sparse.sample({largest, largest, largest}).material == MaterialId::Air);
error(sparse.prepare_generated({largest, 0, 0}), VoxelError::InvalidCoordinate);
}
Test VoxelRegionTests::generated_pages_have_fixed_materials_and_continuous_surface() {
VoxelRegion region(descriptor());
std::vector<ChunkCoordinate> coordinates;
for (int x = -1; x <= 0; ++x) for (int y = -1; y <= 0; ++y) for (int z = -1; z <= 0; ++z) {
coordinates.push_back({x, y, z});
}
activate(region, coordinates);
const auto height = [&](int x, int y) {
int top = -20;
for (int z = -16; z < 16; ++z) if (region.sample({x, y, z}).material != MaterialId::Air) top = z;
require(top >= -8 && top <= 8);
require(region.sample({x, y, top}).material == MaterialId::Soil &&
region.sample({x, y, top - 2}).material == MaterialId::Soil &&
region.sample({x, y, top - 3}).material == MaterialId::Stone &&
region.sample({x, y, top + 1}).material == MaterialId::Air);
return top;
};
for (int x = -31; x < 31; ++x) for (int y = -31; y < 31; ++y) {
const auto top = height(x, y);
require(std::abs(top - height(x + 1, y)) <= 1 && std::abs(top - height(x, y + 1)) <= 1,
"generator has a discontinuous chunk/lattice surface");
}
const auto page = region.directory()->front().chunk;
const auto hash = Void::Hash::fnv1a64(std::as_bytes(page->cells()));
std::cout << "generator1 seed42 chunk(-1,-1,-1) fnv1a64=" << hash << '\n';
// Recorded against the canonical little-endian generator, independently
// reproduced by the fixture calculation before accepting this revision.
require(hash == 13302332479434111011ULL, "canonical generator fixture changed");
}
Test VoxelRegionTests::preparation_order_and_worker_order_preserve_complete_pages() {
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{-1, 0, 0},
ChunkCoordinate{0, -1, -1}, ChunkCoordinate{1, 1, 0}};
VoxelRegion forward(descriptor());
activate(forward, coordinates);
VoxelRegion reverse(descriptor());
auto reversed = coordinates; std::reverse(reversed.begin(), reversed.end());
activate(reverse, reversed);
equivalent(forward, reverse);
for (std::size_t workers : {2, 6, 12}) for (bool reverse_completion : {false, true}) {
VoxelRegion parallel(descriptor());
WorkerPool pool(workers);
std::vector<PreparedVoxelChunk> candidates;
for (std::size_t pair = 0; pair < coordinates.size(); pair += 2) {
std::mutex mutex;
std::condition_variable changed;
int ready = 0;
std::array<bool, 2> permitted{};
bool released = false;
std::array<std::future<std::expected<PreparedVoxelChunk, VoxelError>>, 2> futures;
// Release and drain every accepted task before its captured gate
// dies, including a failed submission or assertion.
auto release = Void::Scope::on_exit([&] {
{
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
for (auto& future : futures) if (future.valid()) future.wait();
});
for (std::size_t index = 0; index < 2; ++index) {
futures[index] = pool.submit([&, parallel, coordinate = coordinates[pair + index], index] {
auto result = parallel.prepare_generated(coordinate);
std::unique_lock lock(mutex);
++ready;
changed.notify_all();
changed.wait(lock, [&] { return released || permitted[index]; });
return result;
});
}
{
std::unique_lock lock(mutex);
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return ready == 2; }),
"two real generator tasks did not reach completion gates");
}
const std::array<std::size_t, 2> order = reverse_completion ?
std::array<std::size_t, 2>{1, 0} : std::array<std::size_t, 2>{0, 1};
for (auto index : order) {
{
std::lock_guard lock(mutex);
permitted[index] = true;
changed.notify_all();
}
require(futures[index].wait_for(std::chrono::seconds(5)) == std::future_status::ready);
auto result = futures[index].get();
require(result.has_value());
candidates.push_back(std::move(*result));
}
}
require(parallel.activate(candidates).has_value());
equivalent(forward, parallel);
}
auto other_definition = descriptor(); ++other_definition.seed;
VoxelRegion other(other_definition); activate(other, coordinates);
require(!std::equal(forward.directory()->front().chunk->cells().begin(),
forward.directory()->front().chunk->cells().end(), other.directory()->front().chunk->cells().begin()));
}
Test VoxelRegionTests::partial_pages_mask_outside_and_validate_import() {
const std::array bounds{VoxelBounds{{-1, -1, -1}, {1, 1, 1}},
VoxelBounds{{largest, largest, largest}, {std::int64_t{largest} + 1,
std::int64_t{largest} + 1, std::int64_t{largest} + 1}},
VoxelBounds{{smallest, smallest, smallest}, {std::int64_t{smallest} + 1,
std::int64_t{smallest} + 1, std::int64_t{smallest} + 1}}};
for (const auto& bound : bounds) {
VoxelRegion region(descriptor(bound));
const VoxelPosition position{static_cast<std::int32_t>(bound.lower.x),
static_cast<std::int32_t>(bound.lower.y), static_cast<std::int32_t>(bound.lower.z)};
const auto coordinate = split_voxel(position).chunk;
auto candidate = generated(region, coordinate);
const auto cells = candidate.chunk()->cells();
for (std::size_t i = 0; i < cells.size(); ++i) {
const auto p = join_voxel(coordinate, {static_cast<std::uint8_t>(i % 32),
static_cast<std::uint8_t>((i / 32) % 32), static_cast<std::uint8_t>(i / 1024)});
require(p.has_value());
if (!bound.contains(*p)) require(cells[i] == MaterialId::Air);
}
auto restored = region.prepare_restored(coordinate, 72, cells);
require(restored.has_value() && restored->chunk()->revision() == 72);
std::array<MaterialId, voxel_chunk_cells> owned;
std::copy(cells.begin(), cells.end(), owned.begin());
auto independent = region.prepare_restored(coordinate, 1, owned);
require(independent.has_value());
const auto index = *voxel_index(split_voxel(position).local);
owned[index] = static_cast<MaterialId>(200);
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidMaterial);
require(independent->chunk()->cells()[index] == cells[index], "import retained caller's mutable cells");
owned[index] = cells[index];
const auto outside_index = (index + 1234) % voxel_chunk_cells;
owned[outside_index] = MaterialId::Stone;
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidCoordinate);
error(region.prepare_restored(coordinate, 0, cells), VoxelError::InvalidRevision);
error(region.prepare_restored(coordinate, 1, cells.first(100)), VoxelError::InvalidSource);
}
}
Test VoxelRegionTests::availability_and_snapshot_lifetimes() {
VoxelRegion region(descriptor());
const auto absent = region.sample({0, 0, 20});
require(absent.availability == VoxelAvailability::Unavailable);
const auto outside = region.sample({64, 0, 20});
require(outside.availability == VoxelAvailability::Outside);
auto held = region;
const std::array coordinates{ChunkCoordinate{0, 0, 0}};
activate(region, coordinates);
require(!region.matches(absent.stamp) && held.matches(absent.stamp));
const auto loaded = region.sample({0, 0, 20});
require(loaded.availability == VoxelAvailability::Loaded && loaded.material == MaterialId::Air);
require(held.sample({0, 0, 20}).availability == VoxelAvailability::Unavailable);
auto owned_directory = region.directory();
auto retained = region;
const std::array changes{change(region, {0, 0, 20})};
require(region.edit(changes).has_value());
require(retained.matches(loaded.stamp) && !region.matches(loaded.stamp));
require(owned_directory->front().chunk->cells()[20 * 1024] == MaterialId::Air);
auto other_stamp = loaded.stamp; ++other_stamp.region; require(!retained.matches(other_stamp));
}
Test VoxelRegionTests::atomic_multichunk_edit_reuses_unchanged_pages() {
VoxelRegion region(descriptor());
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}, ChunkCoordinate{1, 0, 0}};
activate(region, coordinates);
const auto held = region;
const std::array changes{change(region, {0, 2, 20}), change(region, {-1, 2, 20}), change(region, {4, 4, 20})};
const auto result = region.edit(changes);
require(result.has_value() && result->changed_chunks.size() == 2 && result->changed_cells.size() == 3);
require(result->changed_cells[0].position == VoxelPosition{-1, 2, 20} &&
result->changed_cells[1].position == VoxelPosition{0, 2, 20});
require(result->changed_chunks[0].coordinate == ChunkCoordinate{-1, 0, 0} &&
result->changed_chunks[1].coordinate == ChunkCoordinate{0, 0, 0});
for (const auto& change : changes) {
require(region.sample(change.position).material == change.material);
require(held.sample(change.position).material != change.material);
require(region.sample(change.position).stamp.revision == 2);
}
require(region.directory()->back().chunk == held.directory()->back().chunk,
"untouched geometry was copied");
VoxelRegion other = held;
auto reversed = changes; std::reverse(reversed.begin(), reversed.end());
require(other.edit(reversed).has_value()); equivalent(region, other);
}
Test VoxelRegionTests::refused_batches_and_identical_writes_preserve_publication() {
VoxelRegion region(descriptor());
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}};
activate(region, coordinates);
const auto held = region;
auto changes = std::array{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
++changes[1].expected_revision;
error(region.edit(changes), VoxelError::Stale);
--changes[1].expected_revision; changes[1].material = static_cast<MaterialId>(255);
error(region.edit(changes), VoxelError::InvalidMaterial);
changes[1] = changes[0]; error(region.edit(changes), VoxelError::Duplicate);
changes[1] = {{32, 1, 20}, MaterialId::Stone, 1}; error(region.edit(changes), VoxelError::Unavailable);
changes[1].position.x = 64; error(region.edit(changes), VoxelError::InvalidCoordinate);
require(region.directory() == held.directory()); equivalent(region, held);
require(region.edit({}).has_value() && region.directory() == held.directory());
const auto current = region.sample({0, 1, 20});
std::array identical{VoxelEdit{{0, 1, 20}, current.material, current.stamp.revision}};
const auto result = region.edit(identical);
require(result && result->changed_chunks.empty() && result->changed_cells.empty() && result->dirty_chunks.empty());
require(region.directory() == held.directory());
--identical[0].expected_revision; error(region.edit(identical), VoxelError::Stale);
require(region.directory() == held.directory());
}
Test VoxelRegionTests::face_neighbors_and_unavailable_boundaries() {
VoxelRegion region(descriptor({{-64, -64, -64}, {64, 64, 64}}));
const std::array coordinates{ChunkCoordinate{-1, -1, -1}, ChunkCoordinate{0, -1, -1}};
activate(region, coordinates);
const auto neighbor = region.chunk_stamp({0, -1, -1});
const auto absent = region.chunk_stamp({-1, 0, -1});
const std::array changes{change(region, {-1, -1, -1})};
const auto result = region.edit(changes);
require(result && result->dirty_chunks.size() == 4);
require(contains(result->dirty_chunks, {-1, -1, -1}) && contains(result->dirty_chunks, {0, -1, -1}) &&
contains(result->dirty_chunks, {-1, 0, -1}) && contains(result->dirty_chunks, {-1, -1, 0}));
require(!contains(result->dirty_chunks, {0, 0, -1}) && !contains(result->dirty_chunks, {0, 0, 0}));
require(region.matches(neighbor) && region.matches(absent));
const std::array interior{change(region, {-2, -2, -2})};
const auto result2 = region.edit(interior);
require(result2 && result2->dirty_chunks == std::vector<ChunkCoordinate>{{-1, -1, -1}});
VoxelRegion edge(descriptor({{largest, 0, 0}, {std::int64_t{largest} + 1, 1, 1}}));
const std::array last_chunk{split_voxel({largest, 0, 0}).chunk}; activate(edge, last_chunk);
const std::array last_change{change(edge, {largest, 0, 0})};
const auto last_result = edge.edit(last_change);
require(last_result && last_result->dirty_chunks == std::vector<ChunkCoordinate>{last_chunk[0]});
}
Test VoxelRegionTests::activation_checks_source_duplicates_and_prior_publication() {
VoxelRegion region(descriptor());
auto candidate = generated(region, {});
const auto empty = region.directory();
const std::array duplicate{candidate, candidate}; error(region.activate(duplicate), VoxelError::Duplicate);
require(region.directory() == empty);
for (int field = 0; field < 3; ++field) {
auto wrong = descriptor();
if (field == 0) ++wrong.id;
if (field == 1) ++wrong.seed;
if (field == 2) --wrong.bounds.lower.x;
VoxelRegion other(wrong);
const std::array mixed{candidate, generated(other, {-1, 0, 0})};
error(region.activate(mixed), VoxelError::InvalidSource);
require(region.directory() == empty);
}
const std::array first{candidate}; require(region.activate(first).has_value());
const auto held = region.directory();
const std::array late{generated(region, {-1, 0, 0}), candidate};
error(region.activate(late), VoxelError::Stale); require(region.directory() == held);
}
Test VoxelRegionTests::imported_revision_exhaustion_preserves_all_pages() {
VoxelRegion region(descriptor());
const auto source = generated(region, {});
auto maximum = region.prepare_restored({}, exhausted, source.chunk()->cells());
require(maximum.has_value());
const std::array pages{generated(region, {-1, 0, 0}), *maximum};
require(region.activate(pages).has_value());
const auto held = region;
const std::array changes{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
error(region.edit(changes), VoxelError::RevisionExhausted);
require(region.directory() == held.directory()); equivalent(region, held);
const auto current = region.sample({0, 1, 20});
const std::array identical{VoxelEdit{{0, 1, 20}, current.material, exhausted}};
require(region.edit(identical).has_value() && region.directory() == held.directory());
}
Test VoxelRegionTests::page_edit_and_staging_budgets_are_atomic() {
VoxelRegion source(descriptor());
const std::array pages{generated(source, {}), generated(source, {-1, 0, 0})};
VoxelLimits one; one.max_resident_chunks = 1;
VoxelRegion bounded(descriptor(), one);
const auto empty = bounded.directory();
error(bounded.activate(pages), VoxelError::LimitExceeded); require(bounded.directory() == empty);
require(bounded.activate(std::span(pages).first(1)).has_value());
error(bounded.activate(std::span(pages).last(1)), VoxelError::LimitExceeded);
VoxelLimits bytes; bytes.max_resident_bytes = sizeof(VoxelDirectory) + sizeof(VoxelChunkEntry) + sizeof(VoxelChunk) - 1;
VoxelRegion small(descriptor(), bytes);
error(small.activate(std::span(pages).first(1)), VoxelError::LimitExceeded);
VoxelLimits transactions; transactions.max_transaction_bytes = sizeof(VoxelChunk) + 1024;
VoxelRegion limited(descriptor(), transactions);
error(limited.prepare_generated({}), VoxelError::LimitExceeded);
require(limited.activate(std::span(pages).first(1)).has_value());
const auto held = limited.directory();
const std::array edits{change(limited, {1, 1, 20})};
error(limited.edit(edits), VoxelError::LimitExceeded); require(limited.directory() == held);
VoxelLimits edit_limit; edit_limit.max_edit_cells = 1;
VoxelRegion two(descriptor(), edit_limit); require(two.activate(pages).has_value());
const std::array too_many{change(two, {1, 1, 20}), change(two, {-1, 1, 20})};
error(two.edit(too_many), VoxelError::LimitExceeded);
require(two.resident_bytes() == sizeof(VoxelDirectory) + 2 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)));
VoxelLimits hostile; hostile.max_resident_chunks = std::numeric_limits<std::size_t>::max();
VoxelRegion sparse(descriptor(), hostile); require(sparse.directory()->empty());
std::cout << "voxel payload: page=" << sizeof(VoxelChunk) << " directory entry=" << sizeof(VoxelChunkEntry)
<< " active256=" << sizeof(VoxelDirectory) + 256 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) << '\n';
}
Test VoxelRegionTests::doorway_crossing_two_chunks_opens_atomically() {
require(voxel_blocks_passage(MaterialId::DoorClosed) && !voxel_blocks_passage(MaterialId::DoorOpen));
require(!voxel_provides_support(MaterialId::DoorClosed) && !voxel_provides_support(MaterialId::DoorOpen));
require(!voxel_blocks_passage(MaterialId::Air) && !voxel_provides_support(MaterialId::Air));
for (auto material : {MaterialId::Soil, MaterialId::Stone}) {
require(voxel_blocks_passage(material) && voxel_provides_support(material));
}
VoxelRegion region(descriptor({{0, 0, 0}, {32, 32, 64}}));
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{0, 0, 1}};
activate(region, coordinates);
const std::array closed{VoxelEdit{{2, 2, 31}, MaterialId::DoorClosed, 1},
VoxelEdit{{2, 2, 32}, MaterialId::DoorClosed, 1}};
require(region.edit(closed).has_value());
const auto held = region;
std::array opened{VoxelEdit{{2, 2, 31}, MaterialId::DoorOpen, 2},
VoxelEdit{{2, 2, 32}, MaterialId::DoorOpen, 1}};
error(region.edit(opened), VoxelError::Stale);
require(region.directory() == held.directory());
opened[1].expected_revision = 2;
const auto result = region.edit(opened);
require(result && result->changed_chunks.size() == 2 && result->changed_cells.size() == 2);
for (auto edit : opened) {
require(region.sample(edit.position).material == MaterialId::DoorOpen);
require(held.sample(edit.position).material == MaterialId::DoorClosed);
}
auto imported = region.prepare_restored(coordinates[0], 3, region.directory()->front().chunk->cells());
require(imported.has_value());
}
Test VoxelRegionTests::full_resident_directory_copies_one_changed_page() {
using Clock = std::chrono::steady_clock;
VoxelRegion region(descriptor({{-256, -256, 0}, {256, 256, 32}}));
std::vector<ChunkCoordinate> coordinates;
for (int x = -8; x < 8; ++x) for (int y = -8; y < 8; ++y) coordinates.push_back({x, y, 0});
const auto preparation_started = Clock::now();
activate(region, coordinates);
const auto preparation_done = Clock::now();
const auto held = region;
require(held.directory() == region.directory() && held.directory()->size() == 256);
const std::array edits{change(region, {1, 1, 20})};
const auto edit_started = Clock::now();
const auto result = region.edit(edits);
const auto edit_done = Clock::now();
require(result && result->changed_chunks.size() == 1);
std::size_t shared = 0;
for (std::size_t i = 0; i < region.directory()->size(); ++i) {
if ((*held.directory())[i].chunk == (*region.directory())[i].chunk) ++shared;
}
require(shared == 255 && region.directory() != held.directory());
require(held.sample(edits[0].position).material != region.sample(edits[0].position).material);
std::cout << "full256 pages: prepare+activate_us="
<< std::chrono::duration_cast<std::chrono::microseconds>(preparation_done - preparation_started).count()
<< " edit_us=" << std::chrono::duration_cast<std::chrono::microseconds>(edit_done - edit_started).count()
<< " shared_pages=" << shared << " resident_payload=" << region.resident_bytes() << '\n';
}
} // namespace