Compare commits

..
Author SHA1 Message Date
faumaray 59eb683404 docs(m02): record signed slice picking and WARP acceptance evidence 2026-12-03 00:15:16 +03:00
faumaray 9a55167201 integrate(m02): include the rendering branch publication history 2026-12-03 00:11:22 +03:00
faumaray a6989f35ad integrate(m02): include independently verified D3D11 voxel slices and picking 2026-12-03 00:11:22 +03:00
faumaray f2ff1ce0e8 integrate(rendering): retain existing camera branch and add voxel slices 2026-12-03 00:11:22 +03:00
faumaray 41748ac964 docs(m02): record verified voxel region and cross-floor navigation foundation 2026-12-03 00:06:37 +03:00
faumaray 129d7f204b integrate(m02): stage immutable height-slice rendering for verification 2026-12-03 00:05:34 +03:00
faumaray 37a08d4d48 feat(rendering): draw and pick immutable voxel height slices through D3D11 2026-12-03 00:05:11 +03:00
faumaray 14987b240e integrate(m02): preserve valid off-window terrain interactions 2026-12-03 00:04:09 +03:00
faumaray 2017e5685a fix(navigation): preserve work contacts beyond the current search window 2026-12-03 00:04:09 +03:00
faumaray c40d9b2ae2 integrate(m02): include proven frontier navigation and bounded allocation 2026-12-02 23:57:01 +03:00
faumaray 17389b23d7 fix(navigation): distinguish reachable missing terrain from incidental reads 2026-12-02 23:57:01 +03:00
faumaray 6fdf5a90f7 Base the playable voxel milestone on the verified M01 exit 2026-12-02 23:49:43 +03:00
faumaray 3f1817a285 Integrate voxel movement and interaction queries with authoritative saves 2026-12-02 23:49:43 +03:00
faumaray 15887d5613 Record M01 software acceptance and trace the new VoidLibrary contract 2026-12-02 23:48:11 +03:00
faumaray 51311ca104 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 69ce32c2b6 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray cd75eab191 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray f60375a9f3 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 519e4e72a7 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 77781a5f1f Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 22420e9fe2 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray c812df8c0b Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray ba00651b45 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray 7a7ff32e14 Verify door, stair and work access across signed chunk boundaries 2026-12-02 23:46:14 +03:00
faumaray 13dc673088 Run voxel region acceptance with current custody, order controls and LAN admission 2026-12-02 23:41:44 +03:00
faumaray 4bac17df83 Integrate atomic publication-conditioned admission for legacy peers 2026-12-02 23:39:19 +03:00
faumaray aaa0f82527 Verify conditioned peer admission with restored custody states 2026-12-02 23:39:19 +03:00
faumaray e7046a92a1 Exercise settler routes against the real immutable voxel region
# Conflicts:
#	CMakeLists.txt
2026-12-02 23:39:19 +03:00
faumaray 447a1cfd2b Admit legacy guest commands against the exact checked publication 2026-12-02 23:39:19 +03:00
faumaray ee1eca7571 Trace bounded settler paths and their consulted voxel revisions 2026-12-02 23:39:09 +03:00
faumaray 1ca481b8f9 Generate immutable voxel pages and apply checked cross-chunk edits 2026-12-02 23:37:52 +03:00
faumaray e60dc355f0 Include the final checkpoint migration evidence 2026-12-02 23:37:52 +03:00
faumaray 74aadb27b2 Record the observed LAN count and verified fence recovery 2026-12-02 23:35:46 +03:00
faumaray 2ba4b3ffc4 Record order-control verification against the actual Windows run 2026-12-02 23:35:46 +03:00
faumaray 86b5fb35f1 Integrate reviewed terminal receipts, phase checks and authenticated mutants 2026-12-02 23:35:46 +03:00
faumaray 6d1123e172 Share door clearance and support rules between voxel consumers 2026-12-02 23:32:09 +03:00
faumaray f6402eb80f Check all inventory and transfer state in the held-frame test 2026-12-02 23:31:44 +03:00
faumaray d13a232f29 Run the frame test with full checkpoint state alongside the new controls 2026-12-02 23:31:44 +03:00
faumaray 070db7864e Track complete custody state in presentation smoke tests 2026-12-02 23:31:44 +03:00
faumaray 6279a60bf7 Define signed voxel coordinates and immutable region publication 2026-12-02 23:27:36 +03:00
faumaray 431ee602c7 Exercise full-state replay alongside order controls and protocol 11 2026-12-02 23:27:36 +03:00
faumaray 9bc52ea5c9 Stabilize fault-recovery verification in the integrated client 2026-12-02 23:26:10 +03:00
faumaray 22111440c9 Integrate item custody, checkpoint migration, order controls and legacy peers 2026-12-02 23:24:03 +03:00
faumaray c183de1952 Connect legacy admission to the validated custody state 2026-12-02 23:23:51 +03:00
faumaray 13b4665ed2 Verify order selection through real window controls and modal replacement 2026-12-02 23:23:51 +03:00
faumaray f34dcc5053 Check live peer admission alongside verified order controls 2026-12-02 23:23:51 +03:00
faumaray 0d71bcf5d8 Set voxel, navigation and mining contracts for the two-floor scenario 2026-12-02 23:21:55 +03:00
faumaray a47e850bb4 Record the verified camera, checkpoint and title-screen integration 2026-12-02 23:19:32 +03:00
faumaray 6cc59b4ef5 Verify peer cutoff while real owner commands and snapshots are pending 2026-12-02 23:19:32 +03:00
faumaray 5c309b2a9f Exercise a protocol 11 host through real order cancellation 2026-12-02 23:14:05 +03:00
faumaray a1c65119a2 Exercise order controls with persisted physical cargo 2026-12-02 23:13:59 +03:00
faumaray 83a57cbe46 Fence legacy peers from an unrepresentable custody publication 2026-12-02 23:13:59 +03:00
faumaray b5f75d3c13 Cancel and resume durable production orders from the Works menu 2026-12-02 23:13:59 +03:00
faumaray 1cf8bd08fc Present immutable camera frames independently of colony progress 2026-12-02 23:12:05 +03:00
faumaray 455630fb39 Integrate presentation frames with the current title screen and session rules 2026-12-02 23:12:05 +03:00
faumaray e9e7e8276e Record integrated replay results under opposite worker schedules 2026-12-02 23:10:35 +03:00
faumaray 048268a27e Integrate replay diagnostics and adversarial completion-order checks 2026-12-02 23:02:14 +03:00
faumaray 1b57183939 Prepare LAN compatibility checks for durable cargo 2026-12-02 23:01:50 +03:00
faumaray e5d01a4ecd Prepare S04 commands against the durable custody contract 2026-12-02 23:01:50 +03:00
faumaray 5a64a27d17 Record rule selection and quantity transfer checks in the combined game 2026-12-02 22:57:52 +03:00
faumaray 37fb6a897d Integrate actual colony rule selection in the Windows client 2026-12-02 22:53:10 +03:00
52 changed files with 5773 additions and 153 deletions

No files matched your search

+31 -1
View File
@@ -49,7 +49,9 @@ 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
)
@@ -94,17 +96,22 @@ enable_language(RC)
add_library(settlement_client STATIC app/viewer_session.cpp)
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
target_link_libraries(settlement_client PUBLIC settlement_core)
add_library(settlement_voxel_scene STATIC app/voxel_scene.cpp)
target_include_directories(settlement_voxel_scene PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
target_link_libraries(settlement_voxel_scene PUBLIC settlement_core Void::Math)
add_executable(settlement_viewer WIN32
app/d3d_scene_win32.cpp
app/viewer_win32.cpp
app/house_icons.rc
)
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan settlement_voxel_scene user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
if(MSVC)
target_compile_options(settlement_voxel_scene PRIVATE /W4 /permissive-)
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
else()
target_compile_options(settlement_voxel_scene PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
target_link_options(settlement_viewer PRIVATE -municode)
@@ -128,6 +135,7 @@ if(BUILD_TESTING)
tests/executor_tests.cpp
tests/identity_tests.cpp
tests/production_identity_tests.cpp
tests/production_commands_tests.cpp
tests/profile_tests.cpp
tests/quantity_transaction_tests.cpp
tests/replay_tests.cpp
@@ -136,6 +144,8 @@ 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)
@@ -145,7 +155,27 @@ 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 settlement_voxel_scene
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)
add_executable(settlement_production_controls_tests
tests/production_controls_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan settlement_voxel_scene
Void::Testing user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
add_test(NAME settlement_production_controls_tests COMMAND settlement_production_controls_tests)
set_tests_properties(settlement_production_controls_tests PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
add_executable(settlement_voxel_scene_tests
tests/voxel_scene_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp)
target_link_libraries(settlement_voxel_scene_tests PRIVATE settlement_voxel_scene Void::Testing d3d11 d3dcompiler)
add_test(NAME settlement_voxel_scene_tests COMMAND settlement_voxel_scene_tests)
set_tests_properties(settlement_voxel_scene_tests PROPERTIES TIMEOUT 90)
endif()
+122 -26
View File
@@ -11,6 +11,8 @@
#include <cstring>
#include <iterator>
#include <limits>
#include <new>
#include <stdexcept>
#include <utility>
namespace settlement::viewer {
@@ -468,6 +470,8 @@ cbuffer Camera : register(b0) {
float2 screen;
float scale;
float padding;
float2 depthParameters;
float2 depthPadding;
};
struct Input { float3 position : POSITION; float3 color : COLOR; };
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
@@ -477,7 +481,8 @@ Pixel project(Input input) {
(p.x + p.y) * halfTile.y - p.z * 16.0);
Pixel result;
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
1.0 - screenPoint.y * 2.0 / screen.y,
depthParameters.x - (p.x + p.y + p.z * 1.5) * depthParameters.y, 1.0);
result.color = input.color;
return result;
}
@@ -486,6 +491,13 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
} // namespace
class PreparedGeometry {
public:
Mesh mesh;
std::shared_ptr<const VoxelScene> voxel_scene;
float depth_bias = .96f, depth_scale = .009f;
};
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
@@ -501,10 +513,11 @@ struct D3DScene::Backend {
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
Mesh mesh;
std::shared_ptr<const PreparedGeometry> uploaded;
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();
@@ -532,22 +545,29 @@ struct D3DScene::Backend {
return true;
}
bool upload_geometry() {
bool upload_geometry(const Mesh& mesh) {
if (mesh.vertices.empty()) return true;
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
ComPtr<ID3D11Buffer> replacement;
auto* destination = geometry.Get();
if (bytes > buffer_bytes) {
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = static_cast<UINT>(bytes);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
buffer_bytes = desc.ByteWidth;
if (FAILED(device->CreateBuffer(&desc, nullptr, &replacement))) return false;
destination = replacement.Get();
}
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
if (FAILED(context->Map(destination, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
context->Unmap(geometry.Get(), 0);
context->Unmap(destination, 0);
if (replacement) {
geometry = std::move(replacement);
buffer_bytes = static_cast<UINT>(bytes);
}
return true;
}
@@ -578,7 +598,7 @@ D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_unique<Backend>();
auto graphics = std::make_shared<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;
@@ -615,7 +635,7 @@ bool D3DScene::initialize(HWND target, bool software) {
raster.CullMode = D3D11_CULL_NONE;
raster.DepthClipEnable = TRUE;
D3D11_BUFFER_DESC constants{};
constants.ByteWidth = 32;
constants.ByteWidth = 48;
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
vertex->GetBufferSize(), &graphics->layout)) ||
@@ -628,24 +648,97 @@ bool D3DScene::initialize(HWND target, bool software) {
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
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);
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);
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(graphics.mesh, plan, false, world.can_place_room(plan));
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);
}
std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
D3DScene::prepare_voxels(std::shared_ptr<const VoxelScene> scene) {
if (!scene) return std::unexpected(VoxelSceneError::InvalidInput);
if (scene->faces().size() > std::numeric_limits<UINT>::max() / (6 * sizeof(Vertex)))
return std::unexpected(VoxelSceneError::LimitExceeded);
try {
auto prepared = std::make_shared<PreparedGeometry>();
prepared->voxel_scene = std::move(scene);
const auto bounds = prepared->voxel_scene->visible_bounds();
const double depth_extent = static_cast<double>(bounds.upper.x - bounds.lower.x) +
static_cast<double>(bounds.upper.y - bounds.lower.y) +
static_cast<double>(bounds.upper.z - bounds.lower.z) * 1.5;
prepared->depth_bias = .95f;
prepared->depth_scale = static_cast<float>(.9 / depth_extent);
auto& mesh = prepared->mesh;
mesh.vertices.reserve(prepared->voxel_scene->faces().size() * 6);
for (const auto& face : prepared->voxel_scene->faces()) {
const float x = static_cast<float>(std::int64_t{face.cell.x} - bounds.lower.x);
const float y = static_cast<float>(std::int64_t{face.cell.y} - bounds.lower.y);
const float z = static_cast<float>(std::int64_t{face.cell.z} - bounds.lower.z);
const auto packed = voxel_face_color(face);
const auto color = rgb(static_cast<int>((packed >> 16u) & 255u),
static_cast<int>((packed >> 8u) & 255u), static_cast<int>(packed & 255u));
if (face.normal.x != 0) {
const float a = x + (face.normal.x > 0 ? 1.f : 0.f);
mesh.quad({a, y, z}, {a, y + 1, z}, {a, y + 1, z + 1}, {a, y, z + 1}, color);
} else if (face.normal.y != 0) {
const float a = y + (face.normal.y > 0 ? 1.f : 0.f);
mesh.quad({x, a, z}, {x + 1, a, z}, {x + 1, a, z + 1}, {x, a, z + 1}, color);
} else {
const float a = z + (face.normal.z > 0 ? 1.f : 0.f);
mesh.quad({x, y, a}, {x + 1, y, a}, {x + 1, y + 1, a}, {x, y + 1, a}, color);
}
}
return prepared;
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
} catch (const std::length_error&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
}
}
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& camera,
std::vector<std::uint32_t>* capture) {
if (!geometry || !geometry->voxel_scene || !valid_voxel_camera(camera)) return false;
SceneView view{};
view.width = camera.width;
view.height = camera.height;
view.origin_x = static_cast<float>(camera.origin_x);
view.origin_y = static_cast<float>(camera.origin_y);
view.scale = static_cast<float>(camera.scale);
view.tile_half_width = static_cast<float>(camera.tile_half_width);
view.tile_half_height = static_cast<float>(camera.tile_half_height);
return render(std::move(geometry), 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_;
}
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};
@@ -656,7 +749,8 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
ctx->RSSetViewports(1, &viewport);
ctx->RSSetState(graphics.rasterizer.Get());
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
viewport.Width, viewport.Height, view.scale, 0};
viewport.Width, viewport.Height, view.scale, 0,
geometry->depth_bias, geometry->depth_scale, 0, 0};
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
constexpr UINT stride = sizeof(Vertex);
constexpr UINT offset = 0;
@@ -666,9 +760,11 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
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>(graphics.mesh.vertices.size()), 0);
ctx->Draw(static_cast<UINT>(geometry->mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
if (graphics.swap_chain && FAILED(graphics.swap_chain->Present(0, 0))) return false;
++frames_;
return true;
}
} // namespace settlement::viewer
+17 -1
View File
@@ -3,6 +3,7 @@
#include <windows.h>
#include "settlement/core/world.hpp"
#include "voxel_scene.hpp"
#include <cstdint>
#include <memory>
@@ -40,18 +41,33 @@ 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]] static std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
prepare_voxels(std::shared_ptr<const VoxelScene> scene);
bool render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& 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::unique_ptr<Backend> backend_;
std::shared_ptr<Backend> backend_;
};
} // namespace settlement::viewer
+11 -1
View File
@@ -3,6 +3,7 @@
#include "settlement/core/world.hpp"
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
@@ -31,9 +32,16 @@ struct LanCommandResult {
AgentId resident;
};
struct LanSessionOptions {
// Runs on the polling thread after a guest command's snapshot checks and
// before owner admission. May block or throw for diagnostics/tests.
std::function<void()> before_command_admission;
};
class LanSession {
public:
LanSession();
explicit LanSession(LanSessionOptions options);
~LanSession();
LanSession(const LanSession&) = delete;
LanSession& operator=(const LanSession&) = delete;
@@ -53,7 +61,9 @@ public:
// poll_guest pauses further sends until this one retained result is drained.
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
[[nodiscard]] std::unique_ptr<World> poll(World& world);
// Protocol 11 accepts the compiled default rules and a 32x32 active colony.
// Protocol 11 accepts the compiled default rules and a representable 32x32
// active colony. Incompatible state drops the peer, including queued bytes,
// while the listener and authoritative owner remain available.
// Calls never wait for the owner. An admitted guest operation survives peer
// turnover, so poll_host must continue with the same owner until it settles.
void poll_host(SimulationRuntime& runtime);
+70 -22
View File
@@ -151,6 +151,16 @@ struct Action {
AgentId resident;
};
void require_legacy_world(const World& world) {
if (!world.scenario_active() || world.width() != first_colony_map_size ||
world.height() != first_colony_map_size) {
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
}
if (!world.legacy_representable()) {
throw UnsupportedLegacyState{};
}
}
} // namespace
struct LanSession::Impl {
@@ -186,8 +196,9 @@ struct LanSession::Impl {
std::optional<Void::Uuid::Uuid> runtime_session;
std::optional<RulesManifest> compatibility_rules;
std::optional<PendingCommand> pending_command;
LanSessionOptions options;
Impl() {
explicit Impl(LanSessionOptions settings) : options(std::move(settings)) {
WSADATA data{};
winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0;
}
@@ -270,8 +281,9 @@ struct LanSession::Impl {
peer.queue(Message::Receipt, std::string_view(bytes));
}
void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot,
void handle_runtime_host(SimulationRuntime& runtime, const std::shared_ptr<const PublishedSnapshot>& checked,
Message message, std::string_view payload) {
const auto& snapshot = *checked;
if (!authenticated) {
authenticate(message, payload);
return;
@@ -290,23 +302,34 @@ struct LanSession::Impl {
snapshot.next_requests[guest_player - 1],
CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident}
};
auto submitted = runtime.try_submit({guest_player}, envelope);
if (options.before_command_admission) options.before_command_admission();
auto submitted = runtime.try_submit_if_current({guest_player}, envelope, checked);
if (submitted.admission == RuntimeAdmission::Accepted) {
pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation);
} else if (submitted.admission == RuntimeAdmission::Busy) {
reply(CommandStatus::Busy, *snapshot.world);
} else if (submitted.admission == RuntimeAdmission::Busy ||
submitted.admission == RuntimeAdmission::StaleSnapshot) {
// Contention/capacity does not certify the old publication either.
// Fail closed on incompatible/faulted/replaced state; an ordinary
// compatible revision leaves the legacy sequence available to retry.
const auto current = current_runtime_snapshot(runtime);
reply(CommandStatus::Busy, *current->world);
} else {
throw std::runtime_error("The authoritative owner cannot accept guest commands.");
}
}
void complete_runtime_command() {
void complete_runtime_command(SimulationRuntime& runtime) {
if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return;
auto pending = std::move(*pending_command);
pending_command.reset();
const auto result = pending.completion.get();
if (pending.peer_generation != peer_generation || !authenticated ||
!runtime_session || pending.session != *runtime_session) return;
// A ready receipt can predate a load or an incompatible local change.
// Settle its future, but never queue old bytes for the current peer.
const auto current = runtime.view();
validate_runtime(current);
if (current.snapshot->identity.session != pending.session) return;
if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot ||
result.snapshot->identity.session != pending.session) {
throw std::runtime_error("The authoritative guest command did not commit.");
@@ -321,27 +344,38 @@ struct LanSession::Impl {
}
}
void bind_runtime(const RuntimeView& view) {
void validate_runtime(const RuntimeView& view) {
if (!compatibility_rules) {
auto rules = default_rules_manifest();
if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules.");
compatibility_rules = std::move(*rules);
}
if (view.state != RuntimeState::Running || !view.snapshot) {
if (view.state != RuntimeState::Running || !view.snapshot || !view.snapshot->world) {
throw std::runtime_error("The authoritative owner is unavailable.");
}
const auto& snapshot = *view.snapshot;
if (!snapshot.rules || *snapshot.rules != *compatibility_rules) {
throw std::runtime_error("Protocol 11 requires the compiled default rules.");
}
if (!snapshot.world->scenario_active() || snapshot.world->width() != first_colony_map_size ||
snapshot.world->height() != first_colony_map_size) {
throw std::runtime_error("Protocol 11 requires a supported 32x32 colony.");
}
require_legacy_world(*snapshot.world);
}
void bind_runtime(const RuntimeView& view) {
validate_runtime(view);
const auto& snapshot = *view.snapshot;
if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer();
runtime_session = snapshot.identity.session;
}
std::shared_ptr<const PublishedSnapshot> current_runtime_snapshot(SimulationRuntime& runtime) {
const auto view = runtime.view();
validate_runtime(view);
if (!runtime_session || *runtime_session != view.snapshot->identity.session) {
throw std::runtime_error("The authoritative session changed. Reconnect to the host.");
}
return view.snapshot;
}
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
if (message == Message::Snapshot) {
@@ -373,6 +407,7 @@ struct LanSession::Impl {
}
void send_snapshot(const World& world, Clock::time_point now) {
require_legacy_world(world);
if (peer.pending()) return;
const auto host_seq = world.next_command_sequence(1);
const auto guest_seq = world.next_command_sequence(guest_player);
@@ -400,8 +435,9 @@ struct LanSession::Impl {
awaiting_receipt = action;
}
template<class Receive, class SendHost>
void poll_network(Receive receive, SendHost send_host, bool accept_allowed = true) {
template<class Receive, class SendHost, class Validate>
void poll_network(Receive receive, SendHost send_host, Validate validate, bool accept_allowed = true) {
validate();
if (listener && accept_allowed) accept_guest();
if (!peer.socket) return;
const auto now = Clock::now();
@@ -411,7 +447,12 @@ struct LanSession::Impl {
}
if (connecting) finish_connection();
if (connecting) return;
peer.receive(receive);
peer.receive([&](Message message, std::string_view payload) {
// The owner can publish while one receive drains several frames.
validate();
receive(message, payload);
});
validate();
if (authenticated && guest) {
send_action();
if (!peer.pending() && now - last_ping >= 2s) {
@@ -421,12 +462,15 @@ struct LanSession::Impl {
} else if (authenticated) {
send_host(now);
}
// This includes old snapshots/receipts already waiting in output.
validate();
peer.flush();
if (reject_pending && !peer.pending()) drop_peer();
}
};
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
LanSession::LanSession() : LanSession(LanSessionOptions{}) {}
LanSession::LanSession(LanSessionOptions options) : impl_(std::make_unique<Impl>(std::move(options))) {}
LanSession::~LanSession() = default;
void LanSession::host(std::uint16_t port, bool loopback_only) {
@@ -536,7 +580,9 @@ std::unique_ptr<World> LanSession::poll(World& world) {
connection.poll_network([&](Message message, std::string_view payload) {
if (connection.guest) connection.handle_guest(latest, message, payload);
else connection.handle_host(world, message, payload);
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); });
}, [&](Clock::time_point now) { connection.send_snapshot(world, now); }, [&] {
if (connection.listener && !connection.guest) require_legacy_world(world);
});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
@@ -549,16 +595,18 @@ void LanSession::poll_host(SimulationRuntime& runtime) {
auto& connection = *impl_;
if (!connection.listener || connection.guest) return;
try {
connection.complete_runtime_command();
connection.complete_runtime_command(runtime);
// Completion may have published a newer next-request number. Re-read it
// before admitting a reconnect or decoding any further guest intent.
const auto view = runtime.view();
connection.bind_runtime(view);
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_runtime_host(runtime, *view.snapshot, message, payload);
const auto snapshot = connection.current_runtime_snapshot(runtime);
connection.handle_runtime_host(runtime, snapshot, message, payload);
}, [&](Clock::time_point now) {
if (!connection.pending_command) connection.send_snapshot(*view.snapshot->world, now);
}, !connection.pending_command);
const auto snapshot = connection.current_runtime_snapshot(runtime);
if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now);
}, [&] { static_cast<void>(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command);
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
@@ -573,7 +621,7 @@ std::unique_ptr<World> LanSession::poll_guest() {
try {
connection.poll_network([&](Message message, std::string_view payload) {
connection.handle_guest(latest, message, payload);
}, [](Clock::time_point) {});
}, [](Clock::time_point) {}, [] {});
} catch (const std::exception& error) {
connection.notice = error.what();
connection.drop_peer();
+5 -1
View File
@@ -76,7 +76,11 @@ bool ViewerSession::can_submit() const {
bool ViewerSession::can_host_legacy() const {
const auto current = runtime_.view();
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
current.snapshot->rules && *current.snapshot->rules == supported_rules_;
current.snapshot && current.snapshot->rules && *current.snapshot->rules == supported_rules_ &&
current.snapshot->world && current.snapshot->world->scenario_active() &&
current.snapshot->world->width() == first_colony_map_size &&
current.snapshot->world->height() == first_colony_map_size &&
current.snapshot->world->legacy_representable();
}
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
+427 -90
View File
@@ -72,6 +72,7 @@ constexpr int furnished_room_tool_id = 1045;
constexpr int house_list_back_id = 1046;
constexpr int carpenter_menu_id = 1047;
constexpr int craft_door_id = 1048;
constexpr int manage_orders_id = 1049;
constexpr int first_furniture_craft_id = 1143;
constexpr int first_work_choice_id = 1050;
constexpr int resident_list_id = 1060;
@@ -90,6 +91,7 @@ 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;
@@ -140,7 +142,7 @@ LanState displayed_lan_state = LanState::Offline;
std::uint64_t lan_generation = 1;
const auto local_worker_count = std::clamp<std::size_t>(
std::thread::hardware_concurrency(), settlement::min_worker_count, 8);
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room };
enum class PlacementMode { None, Building, Foraging, BerryField, FlaxField, TreePlot, Mine, Loom, Storage, Pantry, Move, Demolish, Room, ManageOrders };
PlacementMode placement_mode = PlacementMode::None;
enum class WorkPanel { Farmer, Woodcutter, Miner, Builder, Gathering, Zones, Construction, Houses, Carpenter, None };
WorkPanel work_panel = WorkPanel::None;
@@ -294,6 +296,63 @@ 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();
@@ -469,13 +528,9 @@ POINT client_point(LPARAM coordinates) {
}
void invalidate_scene(HWND window) {
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);
}
++frame_requests;
if (painting_main || painting_scene) repaint_pending = true;
if (showing_title && !viewer_destroyed) InvalidateRect(window, nullptr, FALSE);
}
void layout_scene(HWND window) {
@@ -832,6 +887,15 @@ bool can_give_orders() {
return world && session && (lan->is_guest() ? lan->state() == LanState::GuestConnected : session->can_submit());
}
bool can_manage_orders() {
return !showing_title && can_give_orders() && !lan->is_guest() && !session->guest() &&
!session->changing_world();
}
bool manageable_order(const settlement::ProductionOrder& order) {
return order.suspended || order.state != settlement::JobState::Completed;
}
void update_roster_details() {
const auto* resident = selected_agent();
const auto role = resident ? profession_name(resident->profession) : L"";
@@ -893,8 +957,8 @@ void sync_resident_roster(bool update_selection = false) {
update_roster_details();
}
void update_status() {
if (status_label == nullptr || !world) return;
StatusText prepare_status() {
StatusText result;
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;
@@ -921,21 +985,13 @@ void update_status() {
L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) +
L" Двери: " + std::to_wstring(doors) +
L" Ход: " + std::to_wstring(world->tick());
SetWindowTextW(status_label, text.c_str());
result.status = text;
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"Сначала стройка";
SetWindowTextW(priority_button, priority);
if (scenario && production_label != nullptr) {
result.priority = priority;
if (scenario) {
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; });
@@ -944,10 +1000,10 @@ void update_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);
SetWindowTextW(production_label, goal.c_str());
return;
result.production = goal;
return result;
}
if (production_label != nullptr) {
{
unsigned waiting = 0;
unsigned carrying = 0;
unsigned building = 0;
@@ -967,8 +1023,22 @@ void update_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);
SetWindowTextW(production_label, production.c_str());
result.production = production;
}
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() {
@@ -1313,7 +1383,7 @@ void handle_lan_menu(HWND window, int command) {
guest_intents.clear();
if (was_guest) {
clear_blueprints();
world = session->world();
if (!session->changing_world()) world = session->world();
}
enter_game_on_snapshot = false;
set_work_panel(window, WorkPanel::None);
@@ -1422,6 +1492,9 @@ bool valid_edit_cell(settlement::GridPosition cell) {
case PlacementMode::Move:
return move_source ? world->can_place_storage(cell) : world->object_status(cell, true) == CommandStatus::Accepted;
case PlacementMode::Demolish: return world->object_status(cell, false) == CommandStatus::Accepted;
case PlacementMode::ManageOrders:
return can_manage_orders() && std::any_of(world->production_orders().begin(), world->production_orders().end(),
[cell](const auto& order) { return order.position == cell && manageable_order(order); });
case PlacementMode::Building:
return world->scenario_active() ? world->can_place_bed(cell) : world->can_place_cabin(cell);
case PlacementMode::Room:
@@ -1676,6 +1749,11 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa
}
if (accepted) {
placement_message = L"Команда выполнена.";
if (std::holds_alternative<settlement::CancelProductionPayload>(payload)) {
placement_message = L"Заказ отменён. Установленные части сохранены; груз вернут жители.";
} else if (std::holds_alternative<settlement::ResumeProductionPayload>(payload)) {
placement_message = L"Работа по заказу возобновлена.";
}
if (const auto* command = std::get_if<settlement::CommandPayload>(&payload)) {
if (command->kind == settlement::CommandKind::MoveObject && move_source == command->cell) {
move_source.reset();
@@ -1687,6 +1765,13 @@ void complete_command(std::uint64_t id, const settlement::SessionPayload& payloa
}
}
} else {
if (std::holds_alternative<settlement::CancelProductionPayload>(payload) ||
std::holds_alternative<settlement::ResumeProductionPayload>(payload)) {
placement_message = status == settlement::CommandStatus::Busy
? L"Заказ пока нельзя изменить. Дождитесь возврата материалов или повторите позже."
: L"Заказ отклонён: работа уже завершена, удалена или изменилась.";
return;
}
placement_message = status == settlement::CommandStatus::Busy
? L"Объект занят. Дождитесь окончания работы или сна."
: L"Команда отклонена. Проверьте клетку и доступ к ней. Чертёж сохранён.";
@@ -1701,12 +1786,13 @@ void reconcile_ticking() {
}
void pump_session(HWND window) {
static bool pumping = false;
if (!session || pumping) return;
pumping = true;
struct Finish { ~Finish() { pumping = false; } } finish;
if (!session || pumping_session || preparing_frame || viewer_destroyed) return;
FlagScope pumping(pumping_session);
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));
@@ -1715,13 +1801,21 @@ void pump_session(HWND window) {
} else if (lan->state() != LanState::Offline) {
lan->poll_host(session->runtime());
}
world = session->world();
// 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();
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"Поселение готово.");
@@ -1779,8 +1873,115 @@ void pump_session(HWND window) {
invalidate_scene(window);
}
const wchar_t* production_name(settlement::RecipeId recipe) {
using settlement::RecipeId;
switch (recipe) {
case RecipeId::SawPlank: return L"Распилить доску";
case RecipeId::CutStoneBlock: return L"Вытесать каменный блок";
case RecipeId::BuildCabin: return L"Построить домик";
case RecipeId::BuildBed: return L"Спальное место";
case RecipeId::WeaveCloth: return L"Ткать ткань";
case RecipeId::BuildFloor: return L"Пол";
case RecipeId::BuildWall: return L"Стена";
case RecipeId::BuildDoorAlongX:
case RecipeId::BuildDoorAlongY: return L"Построить дверь";
case RecipeId::BuildMedicineCabinet: return L"Построить аптечный шкаф";
case RecipeId::BuildMiningRack: return L"Построить стойку шахтёра";
case RecipeId::BuildLoom: return L"Построить ткацкий станок";
case RecipeId::InstallDoorAlongX:
case RecipeId::InstallDoorAlongY: return L"Установить дверь";
case RecipeId::CraftWoodenDoor: return L"Изготовить дверь";
case RecipeId::InstallMedicineCabinet: return L"Установить аптечный шкаф";
case RecipeId::InstallMiningRack: return L"Установить стойку шахтёра";
case RecipeId::InstallLoom: return L"Установить ткацкий станок";
case RecipeId::CraftMedicineCabinet: return L"Изготовить аптечный шкаф";
case RecipeId::CraftMiningRack: return L"Изготовить стойку шахтёра";
case RecipeId::CraftLoom: return L"Изготовить ткацкий станок";
}
return L"Производственный заказ";
}
void manage_orders_at_cell(HWND window, settlement::GridPosition cell) {
if (!can_manage_orders()) return;
// Popup menus pump nested messages. Keep every displayed order alive and
// fence both replacement admission and completed world/session replacement.
const auto opening = session->runtime().latest();
const auto generation = session->generation();
const auto* opening_session = session.get();
const auto network_generation = lan_generation;
const auto* connection = lan.get();
const auto current_context = [&] {
return can_manage_orders() && session.get() == opening_session && session->generation() == generation &&
session->runtime().latest()->identity == opening->identity && network_generation == lan_generation &&
connection == lan.get() && placement_mode == PlacementMode::ManageOrders;
};
constexpr std::size_t page_size = 16;
constexpr UINT previous_page = 100;
constexpr UINT next_page = 101;
std::size_t offset = 0;
POINT cursor{};
GetCursorPos(&cursor);
for (;;) {
std::array<const settlement::ProductionOrder*, page_size> choices{};
std::size_t count = 0, skipped = 0;
bool more = false;
for (const auto& order : opening->world->production_orders()) {
if (order.position != cell || !manageable_order(order)) continue;
if (skipped++ < offset) continue;
if (count == page_size) { more = true; break; }
choices[count++] = &order;
}
if (count == 0) {
placement_message = L"На этой клетке нет незавершённых или приостановленных заказов.";
return;
}
const auto menu = CreatePopupMenu();
if (!menu) return;
for (std::size_t index = 0; index < count; ++index) {
const auto& order = *choices[index];
const auto title = std::wstring(order.suspended ? L"Возобновить: " : L"Отменить: ") +
production_name(order.recipe) + L" №" + std::to_wstring(order.id) + L" [" +
std::to_wstring(cell.x + 1) + L", " + std::to_wstring(cell.y + 1) + L"]";
AppendMenuW(menu, MF_STRING, index + 1, title.c_str());
}
if (offset != 0 || more) AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
if (offset != 0) AppendMenuW(menu, MF_STRING, previous_page, L"← Предыдущие заказы");
if (more) AppendMenuW(menu, MF_STRING, next_page, L"Следующие заказы →");
const auto selected = static_cast<UINT>(TrackPopupMenu(menu, TPM_RETURNCMD |
TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, window, nullptr));
DestroyMenu(menu);
if (!current_context()) {
placement_message = L"Поселение или режим изменились. Выберите заказ заново.";
return;
}
if (selected == previous_page) { offset -= page_size; continue; }
if (selected == next_page) { offset += page_size; continue; }
if (selected == 0 || selected > count) return;
const auto& chosen = *choices[selected - 1];
const auto current = session->runtime().latest();
const auto* order = current->world->find_production(chosen.id);
if (!order || order->position != chosen.position || order->recipe != chosen.recipe ||
order->suspended != chosen.suspended || !manageable_order(*order)) {
placement_message = L"Заказ изменился. Выберите его заново.";
return;
}
const settlement::SessionPayload payload = chosen.suspended
? settlement::SessionPayload{settlement::ResumeProductionPayload{chosen.id}}
: settlement::SessionPayload{settlement::CancelProductionPayload{chosen.id}};
placement_message = enqueue_command(payload) ? L"Изменение заказа ожидает подтверждения…"
: L"Очередь занята. Попробуйте ещё раз.";
return;
}
}
void edit_at_cell(HWND window, settlement::GridPosition cell) {
if (!can_give_orders()) return;
if (placement_mode == PlacementMode::ManageOrders) {
manage_orders_at_cell(window, cell);
update_status();
invalidate_scene(window);
return;
}
const auto held_world = world;
const auto generation = session->generation();
const auto installed_session = session->runtime().latest()->identity.session;
@@ -1850,6 +2051,7 @@ HMENU create_work_menu() {
role_choices[static_cast<std::size_t>(id - farmer_menu_id + 1)].title);
}
AppendMenuW(menu, MF_STRING, carpenter_menu_id, L"Плотник");
if (can_manage_orders()) AppendMenuW(menu, MF_STRING, manage_orders_id, L"Управление заказами…");
AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(menu, MF_STRING, residents_button_id, L"Жители…\tC");
return menu;
@@ -2069,6 +2271,24 @@ std::wstring resident_details() {
profession_name(resident->profession) + L" Голод " + std::to_wstring(hunger) + L"%";
if (resident->state == settlement::AgentState::GoingToEat) text += L" Идёт к кладовой";
else if (resident->state == settlement::AgentState::Eating) text += L" Ест";
else if (resident->state == settlement::AgentState::Returning) {
text += L" Возвращает материалы";
if (resident->execution) {
switch (resident->execution->blocked) {
case settlement::CustodyStatus::NoDestination:
text += L": нет доступного склада с местом"; break;
case settlement::CustodyStatus::Capacity:
text += L": на складе недостаточно места"; break;
case settlement::CustodyStatus::Busy:
text += L": ожидает освобождения склада"; break;
case settlement::CustodyStatus::Exhausted:
case settlement::CustodyStatus::Overflow:
text += L": достигнут предел учёта запасов"; break;
case settlement::CustodyStatus::Accepted: break;
default: text += L": ожидает возможности сдать груз"; break;
}
}
}
else if (world->find_production(resident->production_id) != nullptr &&
settlement::is_carpentry_recipe(world->find_production(resident->production_id)->recipe)) {
text += resident->state == settlement::AgentState::Working ? L" Работает за верстаком" :
@@ -2146,31 +2366,7 @@ std::wstring blueprint_details() {
return text;
}
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));
std::pair<std::wstring, std::wstring> prepare_hud() {
const wchar_t* hint = world->scenario_active() ?
L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" :
L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство";
@@ -2192,6 +2388,8 @@ void draw_world(HDC dc, int width, int height) {
L"Выберите кровать, склад, станок или посаженный участок.";
} else if (placement_mode == PlacementMode::Demolish) {
hint = L"Щёлкните по объекту, чтобы снести его. Правая кнопка — отмена.";
} else if (placement_mode == PlacementMode::ManageOrders) {
hint = L"Щёлкните по площадке или станку. Выберите заказ, чтобы отменить или возобновить работу.";
} else if (placement_mode == PlacementMode::Room) {
if (room_draft_move) {
hint = L"Щёлкните по новой площадке. R поворачивает дом, правый щелчок отменяет перенос.";
@@ -2210,10 +2408,6 @@ void draw_world(HDC dc, int width, int height) {
} 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)
@@ -2237,9 +2431,43 @@ void draw_world(HDC dc, int width, int height) {
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 + dock_layout.line_height};
DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
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);
if (previous_font) SelectObject(dc, previous_font);
}
@@ -2268,23 +2496,117 @@ 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) {
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);
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);
if (!drawn) {
graphics.reset();
const auto parent = GetParent(window);
layout_scene(parent);
invalidate_scene(parent);
}
@@ -2587,7 +2909,9 @@ 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:
@@ -2622,6 +2946,11 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
if (world) show_resident_roster(window);
return 0;
}
if (LOWORD(wparam) == manage_orders_id && HIWORD(wparam) == BN_CLICKED) {
if (can_manage_orders()) set_placement_mode(window, PlacementMode::ManageOrders);
SetFocus(window);
return 0;
}
if (HIWORD(wparam) == BN_CLICKED && LOWORD(wparam) == build_blueprint_id) {
submit_blueprint(window);
SetFocus(window);
@@ -2932,6 +3261,8 @@ 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;
@@ -2939,7 +3270,12 @@ 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);
@@ -2950,28 +3286,29 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
InvalidateRect(window, nullptr, FALSE);
break;
case WM_PAINT: {
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);
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);
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));
+337
View File
@@ -0,0 +1,337 @@
#include "voxel_scene.hpp"
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <limits>
#include <new>
#include <stdexcept>
namespace settlement::viewer {
namespace {
constexpr std::array<VoxelPosition, 6> normals{{
{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}};
constexpr double elevation_pixels = 16;
bool finite(VoxelPoint point) noexcept {
return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
}
bool empty(VoxelBounds bounds) noexcept {
return bounds.upper.z <= bounds.lower.z;
}
bool solid(const VoxelSample& sample) noexcept {
return sample.availability == VoxelAvailability::Unavailable ||
(sample.availability == VoxelAvailability::Loaded && voxel_blocks_passage(sample.material));
}
bool record(std::vector<ChunkStamp>& reads, ChunkStamp stamp, std::size_t limit) {
const auto at = std::lower_bound(reads.begin(), reads.end(), stamp.coordinate,
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
if (at != reads.end() && at->coordinate == stamp.coordinate) return true;
if (reads.size() >= limit) return false;
reads.insert(at, stamp);
return true;
}
std::optional<VoxelPosition> neighbor(VoxelPosition cell, VoxelPosition normal) noexcept {
const auto x = Void::Numeric::checked_add(cell.x, normal.x);
const auto y = Void::Numeric::checked_add(cell.y, normal.y);
const auto z = Void::Numeric::checked_add(cell.z, normal.z);
if (!x || !y || !z) return std::nullopt;
return VoxelPosition{*x, *y, *z};
}
bool within_budget(std::size_t faces, std::size_t reads, std::size_t limit) noexcept {
// Include the eventual six expanded position/color vertices per quad, so
// this budget covers a retained CPU scene plus its prepared D3D geometry.
constexpr std::size_t face_bytes = sizeof(VoxelFace) + 6 * 6 * sizeof(float);
const auto mesh_bytes = Void::Numeric::checked_mul(faces, face_bytes);
// Account for geometric vector capacity growth in the read directory.
const auto stamp_bytes = Void::Numeric::checked_mul(reads, 2 * sizeof(ChunkStamp));
if (!mesh_bytes || !stamp_bytes) return false;
const auto total = Void::Numeric::checked_add(*mesh_bytes, *stamp_bytes);
return total && *total <= limit;
}
std::array<std::int64_t, 3> lower_array(VoxelBounds bounds) noexcept {
return {bounds.lower.x, bounds.lower.y, bounds.lower.z};
}
std::array<std::int64_t, 3> extent_array(VoxelBounds bounds) noexcept {
return {bounds.upper.x - bounds.lower.x, bounds.upper.y - bounds.lower.y,
bounds.upper.z - bounds.lower.z};
}
VoxelPosition normal_for(std::size_t axis, int sign) noexcept {
if (axis == 0) return {sign, 0, 0};
if (axis == 1) return {0, sign, 0};
return {0, 0, sign};
}
} // namespace
VoxelScene::VoxelScene(VoxelRegion region, Void::Uuid::Uuid session,
VoxelSceneOptions options, VoxelBounds visible)
: region_(std::move(region)), session_(session), options_(options), visible_(visible) {}
bool VoxelScene::current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept {
return session == session_ && region.descriptor() == region_.descriptor() &&
std::all_of(reads_.begin(), reads_.end(), [&](auto stamp) { return region.matches(stamp); });
}
std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError> prepare_voxel_scene(
const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options) {
const auto& bounds = options.bounds;
const auto& region_bounds = region.descriptor().bounds;
const auto& limits = options.limits;
if (bounds.lower.x < region_bounds.lower.x || bounds.lower.y < region_bounds.lower.y ||
bounds.lower.z < region_bounds.lower.z || bounds.upper.x > region_bounds.upper.x ||
bounds.upper.y > region_bounds.upper.y || bounds.upper.z > region_bounds.upper.z ||
bounds.lower.x >= bounds.upper.x || bounds.lower.y >= bounds.upper.y ||
bounds.lower.z >= bounds.upper.z || limits.max_axis <= 0) {
return std::unexpected(VoxelSceneError::InvalidInput);
}
const auto extents = extent_array(bounds);
for (auto extent : extents) {
// The shader uses float local vertices. Keep all cell corners exact,
// including the upper endpoint, even if a caller raises its budget.
if (extent > limits.max_axis || extent > 65536) return std::unexpected(VoxelSceneError::LimitExceeded);
}
auto visible = bounds;
visible.upper.z = std::max(bounds.lower.z,
std::min(bounds.upper.z, std::int64_t{options.slice} + 1));
auto cells = Void::Numeric::checked_mul(static_cast<std::size_t>(extents[0]),
static_cast<std::size_t>(extents[1]));
if (cells) cells = Void::Numeric::checked_mul(*cells,
static_cast<std::size_t>(visible.upper.z - visible.lower.z));
if (!cells || *cells > limits.max_cells) return std::unexpected(VoxelSceneError::LimitExceeded);
try {
auto scene = std::shared_ptr<VoxelScene>(new VoxelScene(region, session, options, visible));
std::size_t face_count = 0;
const auto record_read = [&](ChunkStamp stamp) {
const auto at = std::lower_bound(scene->reads_.begin(), scene->reads_.end(), stamp.coordinate,
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
if (at != scene->reads_.end() && at->coordinate == stamp.coordinate) return true;
if (scene->reads_.size() >= limits.max_read_chunks ||
!within_budget(face_count, scene->reads_.size() + 1, limits.max_bytes)) return false;
scene->reads_.insert(at, stamp);
return true;
};
// First pass counts and records dependencies before allocating faces.
// Second pass reads the same held immutable pages and fills exact capacity.
for (int pass = 0; pass < 2; ++pass) {
for (auto z = visible.lower.z; z < visible.upper.z; ++z) {
for (auto y = visible.lower.y; y < visible.upper.y; ++y) {
for (auto x = visible.lower.x; x < visible.upper.x; ++x) {
const VoxelPosition cell{static_cast<std::int32_t>(x),
static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
const auto sample = region.sample(cell);
if (pass == 0 && !record_read(sample.stamp))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (!solid(sample)) continue;
for (auto normal : normals) {
const auto next = neighbor(cell, normal);
if (next && visible.contains(*next)) {
const auto beside = region.sample(*next);
if (pass == 0 && !record_read(beside.stamp))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (solid(beside)) continue;
}
if (pass == 0) {
if (face_count >= limits.max_faces) return std::unexpected(VoxelSceneError::LimitExceeded);
++face_count;
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
return std::unexpected(VoxelSceneError::LimitExceeded);
} else {
scene->faces_.push_back({cell, normal, sample.material,
sample.availability == VoxelAvailability::Unavailable});
}
}
}
}
}
if (pass == 0) {
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
return std::unexpected(VoxelSceneError::LimitExceeded);
scene->faces_.reserve(face_count);
}
}
return scene;
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
} catch (const std::length_error&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
}
}
bool valid_voxel_camera(const VoxelCamera& camera) noexcept {
// D3D11 maximum 2D resource dimension, with finite practical shader inputs.
// Tiny/huge scales cannot identify a cell in a pixel and are refused.
return camera.width > 0 && camera.width <= 16384 && camera.height > 0 && camera.height <= 16384 &&
std::isfinite(camera.origin_x) && std::abs(camera.origin_x) <= 1e7 &&
std::isfinite(camera.origin_y) && std::abs(camera.origin_y) <= 1e7 &&
std::isfinite(camera.scale) && camera.scale >= 0.01 && camera.scale <= 256 &&
std::isfinite(camera.tile_half_width) && camera.tile_half_width >= 1 && camera.tile_half_width <= 256 &&
std::isfinite(camera.tile_half_height) && camera.tile_half_height >= 1 && camera.tile_half_height <= 256;
}
std::optional<ScreenPoint> project_voxel_point(const VoxelScene& scene,
const VoxelCamera& camera, VoxelPoint point) noexcept {
if (!valid_voxel_camera(camera) || !finite(point)) return std::nullopt;
const auto lower = scene.options().bounds.lower;
point = point - VoxelPoint{static_cast<double>(lower.x), static_cast<double>(lower.y), static_cast<double>(lower.z)};
const ScreenPoint result{camera.origin_x + camera.scale * (point.x - point.y) * camera.tile_half_width,
camera.origin_y + camera.scale * ((point.x + point.y) * camera.tile_half_height - point.z * elevation_pixels)};
if (!std::isfinite(result.x) || !std::isfinite(result.y)) return std::nullopt;
return result;
}
std::uint32_t voxel_face_color(const VoxelFace& face) noexcept {
std::array<std::uint32_t, 3> color{128, 132, 140};
if (!face.unavailable) {
switch (face.material) {
case MaterialId::Soil: color = {166, 119, 70}; break;
case MaterialId::Stone: color = {130, 143, 157}; break;
case MaterialId::DoorClosed: color = {184, 99, 46}; break;
default: break;
}
}
const std::uint32_t percent = face.normal.z > 0 ? 100u : face.normal.x != 0 ? 82u :
face.normal.y != 0 ? 66u : 50u;
for (auto& channel : color) channel = channel * percent / 100u;
return (color[0] << 16u) | (color[1] << 8u) | color[2];
}
bool VoxelPick::current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept {
return session == current_session && region == world.descriptor().id &&
std::all_of(reads.begin(), reads.end(), [&](auto stamp) { return world.matches(stamp); });
}
std::expected<VoxelPick, VoxelSceneError> trace_voxels(
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits) {
if (!finite(ray.origin) || !finite(ray.direction) || !std::isfinite(ray.max_distance) ||
ray.max_distance < 0) return std::unexpected(VoxelSceneError::InvalidInput);
const double magnitude = std::max({std::abs(ray.direction.x), std::abs(ray.direction.y), std::abs(ray.direction.z)});
if (magnitude == 0) return std::unexpected(VoxelSceneError::InvalidInput);
// Power-of-two scaling preserves represented component ratios. Dividing by
// a Euclidean norm first would turn a 1:3 exact corner tie into two steps.
int exponent = 0;
std::frexp(magnitude, &exponent);
const std::array<long double, 3> direction{std::scalbn(static_cast<long double>(ray.direction.x), -exponent),
std::scalbn(static_cast<long double>(ray.direction.y), -exponent),
std::scalbn(static_cast<long double>(ray.direction.z), -exponent)};
const auto length = std::hypot(direction[0], direction[1], direction[2]);
VoxelPick result;
result.region = scene.region().descriptor().id;
result.session = scene.session();
const auto bounds = scene.visible_bounds();
if (empty(bounds)) return result;
const auto lower = lower_array(bounds);
const auto extent = extent_array(bounds);
const std::array<long double, 3> origin{static_cast<long double>(ray.origin.x) - lower[0],
static_cast<long double>(ray.origin.y) - lower[1], static_cast<long double>(ray.origin.z) - lower[2]};
std::array<int, 3> step{};
std::array<long double, 3> entry{};
long double start = 0, finish = ray.max_distance / length;
for (std::size_t axis = 0; axis < 3; ++axis) {
if (!std::isfinite(origin[axis])) return std::unexpected(VoxelSceneError::InvalidInput);
step[axis] = direction[axis] > 0 ? 1 : direction[axis] < 0 ? -1 : 0;
if (step[axis] == 0) {
if (origin[axis] < 0 || origin[axis] >= extent[axis]) return result;
entry[axis] = -std::numeric_limits<long double>::infinity();
continue;
}
const auto a = -origin[axis] / direction[axis];
const auto b = (extent[axis] - origin[axis]) / direction[axis];
entry[axis] = std::min(a, b);
start = std::max(start, entry[axis]);
finish = std::min(finish, std::max(a, b));
}
if (start > finish || !std::isfinite(start)) return result;
std::array<std::int64_t, 3> cell{};
VoxelPosition normal{};
bool has_normal = false;
for (std::size_t axis = 0; axis < 3; ++axis) {
auto point = std::fma(direction[axis], start, origin[axis]);
if (entry[axis] == start) point = step[axis] > 0 ? 0 : static_cast<long double>(extent[axis]);
if (!std::isfinite(point) || point < 0 || point > extent[axis])
return std::unexpected(VoxelSceneError::InvalidInput);
const auto floor = std::floor(point);
cell[axis] = static_cast<std::int64_t>(floor) - (step[axis] < 0 && point == floor ? 1 : 0);
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
if (!has_normal && step[axis] != 0 && point == floor) {
normal = normal_for(axis, -step[axis]);
has_normal = true;
}
}
try {
auto distance = start;
for (std::size_t walked = 0; ; ++walked) {
if (walked >= limits.max_steps) return std::unexpected(VoxelSceneError::LimitExceeded);
const VoxelPosition absolute{static_cast<std::int32_t>(lower[0] + cell[0]),
static_cast<std::int32_t>(lower[1] + cell[1]), static_cast<std::int32_t>(lower[2] + cell[2])};
const auto sample = scene.region().sample(absolute);
if (!record(result.reads, sample.stamp, limits.max_read_chunks))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (solid(sample)) {
result.status = sample.availability == VoxelAvailability::Unavailable ? VoxelPickStatus::Unavailable :
has_normal ? VoxelPickStatus::Hit : VoxelPickStatus::Inside;
result.cell = absolute;
result.normal = normal;
if (has_normal) result.adjacent = neighbor(absolute, normal);
result.material = sample.material;
result.distance = static_cast<double>(distance * length);
return result;
}
std::array<long double, 3> crossing{};
for (std::size_t axis = 0; axis < 3; ++axis) {
crossing[axis] = step[axis] == 0 ? std::numeric_limits<long double>::infinity() :
(static_cast<long double>(cell[axis] + (step[axis] > 0 ? 1 : 0)) - origin[axis]) / direction[axis];
}
const auto next = *std::min_element(crossing.begin(), crossing.end());
if (next > finish || !std::isfinite(next)) return result;
// A distance too large to represent successive voxel planes is not
// safe for a selection. Refuse rather than returning an arbitrary cell.
if (next <= distance) return std::unexpected(VoxelSceneError::InvalidInput);
has_normal = false;
for (std::size_t axis = 0; axis < 3; ++axis) {
if (crossing[axis] != next) continue;
cell[axis] += step[axis];
if (!has_normal) {
normal = normal_for(axis, -step[axis]);
has_normal = true;
}
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
}
distance = next;
}
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
} catch (const std::length_error&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
}
}
std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point) {
if (!valid_voxel_camera(camera) || !std::isfinite(point.x) || !std::isfinite(point.y) ||
point.x < 0 || point.y < 0 || point.x >= camera.width || point.y >= camera.height)
return std::unexpected(VoxelSceneError::InvalidInput);
const auto bounds = scene.visible_bounds();
const double z = static_cast<double>(bounds.upper.z - bounds.lower.z);
const double u = (point.x - camera.origin_x) / (camera.scale * camera.tile_half_width);
const double v = (point.y - camera.origin_y) / (camera.scale * camera.tile_half_height);
const double elevated = v + z * elevation_pixels / camera.tile_half_height;
VoxelRay ray{{(u + elevated) * 0.5 + static_cast<double>(bounds.lower.x),
(elevated - u) * 0.5 + static_cast<double>(bounds.lower.y), static_cast<double>(bounds.upper.z)},
{-1, -1, -2 * camera.tile_half_height / elevation_pixels}, 0};
ray.max_distance = z * std::hypot(ray.direction.x, ray.direction.y, ray.direction.z) / -ray.direction.z;
return ray;
}
std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits) {
const auto ray = voxel_screen_ray(scene, camera, point);
if (!ray) return std::unexpected(ray.error());
return trace_voxels(scene, *ray, limits);
}
} // namespace settlement::viewer
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include "map_camera.hpp"
#include "settlement/core/voxel_region.hpp"
#include <Void/Core/Uuid.hpp>
#include <Void/Math/Vec.hpp>
#include <expected>
#include <memory>
#include <span>
#include <vector>
namespace settlement::viewer {
using VoxelPoint = Void::Math::Vec3<double>;
struct VoxelCamera {
int width = 0, height = 0;
// Screen position of the lower corner of the prepared display bounds.
double origin_x = 0, origin_y = 0;
double scale = 1;
double tile_half_width = 12, tile_half_height = 7;
};
struct VoxelSceneLimits {
std::size_t max_cells = 2 * 1024 * 1024;
std::size_t max_faces = 262144;
std::size_t max_read_chunks = 1024;
// Faces, read directory capacity and expanded CPU vertices. Shared source
// pages, allocator overhead, retained older scenes and GPU memory are separate.
std::size_t max_bytes = 64 * 1024 * 1024;
std::int64_t max_axis = 4096;
};
struct VoxelSceneOptions {
// An explicit display volume bounds work even in an enormous sparse region.
VoxelBounds bounds;
std::int32_t slice = 0; // Highest displayed cell, inclusive.
VoxelSceneLimits limits;
};
enum class VoxelSceneError {
InvalidInput, LimitExceeded, AllocationFailed
};
struct VoxelFace {
VoxelPosition cell;
VoxelPosition normal;
MaterialId material = MaterialId::Air;
bool unavailable = false;
bool operator==(const VoxelFace&) const = default;
};
class VoxelScene {
public:
[[nodiscard]] const VoxelRegion& region() const noexcept { return region_; }
[[nodiscard]] const Void::Uuid::Uuid& session() const noexcept { return session_; }
[[nodiscard]] const VoxelSceneOptions& options() const noexcept { return options_; }
[[nodiscard]] const VoxelBounds& visible_bounds() const noexcept { return visible_; }
[[nodiscard]] std::span<const VoxelFace> faces() const noexcept { return faces_; }
[[nodiscard]] std::span<const ChunkStamp> reads() const noexcept { return reads_; }
[[nodiscard]] bool current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept;
private:
friend std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
prepare_voxel_scene(const VoxelRegion&, const Void::Uuid::Uuid&, VoxelSceneOptions);
VoxelScene(VoxelRegion region, Void::Uuid::Uuid session, VoxelSceneOptions options, VoxelBounds visible);
VoxelRegion region_;
Void::Uuid::Uuid session_;
VoxelSceneOptions options_;
VoxelBounds visible_;
std::vector<VoxelFace> faces_;
std::vector<ChunkStamp> reads_;
};
// Missing cells are opaque gray terrain boundaries. Picks stop there with
// Unavailable so loaded geometry cannot be selected through unknown space.
[[nodiscard]] std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
prepare_voxel_scene(const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options);
[[nodiscard]] bool valid_voxel_camera(const VoxelCamera& camera) noexcept;
[[nodiscard]] std::optional<ScreenPoint> project_voxel_point(
const VoxelScene& scene, const VoxelCamera& camera, VoxelPoint point) noexcept;
[[nodiscard]] std::uint32_t voxel_face_color(const VoxelFace& face) noexcept;
struct VoxelRay {
VoxelPoint origin;
VoxelPoint direction;
double max_distance = 0;
};
struct VoxelPickLimits {
std::size_t max_steps = 16384;
std::size_t max_read_chunks = 1024;
};
enum class VoxelPickStatus { Miss, Hit, Inside, Unavailable };
struct VoxelPick {
RegionId region = 0;
Void::Uuid::Uuid session;
VoxelPickStatus status = VoxelPickStatus::Miss;
VoxelPosition cell;
VoxelPosition normal; // Zero for an initial occupied cell with no crossed face.
std::optional<VoxelPosition> adjacent; // May be outside the region. Validate before placement.
MaterialId material = MaterialId::Air;
double distance = 0;
std::vector<ChunkStamp> reads;
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept;
};
// Cells are [x,x+1). At an exact plane the direction selects the forward cell.
// A zero component stays in the half-open cell owning that coordinate.
// Simultaneous plane crossings advance all tied axes, selecting normal X/Y/Z
// in that priority order. Cells touched only along an edge are skipped.
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> trace_voxels(
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits = {});
[[nodiscard]] std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point);
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits = {});
} // namespace settlement::viewer
+10
View File
@@ -2,6 +2,10 @@
Текущий план разработки расположен в [PLAN.md](../../PLAN.md). Ниже сохранена история предыдущего этапа интеграции.
В M02 проверены каталог изменяемых воксельных страниц и поиск пути на нескольких высотах. В объединённом коммите `14987b2` под Wine прошли 210 проверок ядра, 17 LAN, 15 клиентского сеанса, шесть проверок управления заказами в окне и испытание кадра D3D11. Житель высотой две клетки учитывает ступени, проёмы и границу области поиска. Работа в игре над верхней площадкой, выдача добычи, сохранение и показ слоя находятся в реализации. [Ход M02](../plan/milestones/M02.md#проверенный-каталог-и-навигация) · [Проверка кода](tasks/M02-V1.md)
Программная приёмка M01 завершена на `4bac17d` для Windows x64 под Wine. Проверены потактное воспроизведение, перенос и возврат имущества, исторические сохранения, управление заказами, оба профиля правил, совместимость с прежним клиентом в обеих ролях и кадры во время ожидания. Пять исполняемых наборов прошли полностью. Для M02 доступны подтверждённые границы мира, сеанса, команд, сохранений и отображения. [Результаты M01](../plan/milestones/M01.md#приёмка-реализации-m01) · [Экономика и кодек](tasks/M01-V14.md) · [Сеть и клиент](tasks/M01-V15.md)
As of 2026-12-02, the baseline is `74b89ae` on `chore/integrate-void-library`. The tracked checkout was clean at discovery. The project targets Windows x64, MSYS2 UCRT64 and Direct3D 11.
The user approved pinning Void to `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, adopting Binary and Core for saves and LAN, and migrating the reflection suites to Void Testing. The Windows build uses CMake 4+ and GCC 16. Use a configurable agent with Astra 6.2 XHigh for planning and independent review and Sol 6.2 XHigh for implementation, as approved by the user.
@@ -93,3 +97,9 @@ 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,3 +48,7 @@ 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
@@ -0,0 +1,52 @@
# 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`.
+50
View File
@@ -0,0 +1,50 @@
# Audit live item ownership and checkpoint migration across real game actions
Task ID: M01-V14
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Independent review on root M01 at 2211144 vs a47e850. S06+S15 share ccd50ec plus validated phase/ID changes 4f4c038. Contracts M01-P5/F8, S06-03, S15-04 and docs/plan/custody.md. Real saved old v1/raw<=13, v2/raw14 historical f6493e2 world fixtures, new v3/raw15. One pending correction deduplicates consumed effects when one site input merges pooled supplies and rejects invalid duplicate result rows (root supplies refs later). User requested real upstream gaps, #7 and #8 exist. S04/S16/UI are independently reviewed.
## 2. Objective and deliverables
Review full ownership/ID/transaction/replay invariants and raw15/checkpoint3 encoding, real migration + strict malformed input behavior. Send source/trigger/scope for high-confidence defects early. Recheck repaired areas and eventual integrated evidence prior to publication.
## 3. Scope and non-goals
Only M01 S06 physical stock/reservation/transfer logic, receipt lifecycle, balances, migration/projection, bounds/format and validation. Cross S04/S16 entry when determining effect/reservations but leave UI/transport review to peer. No code, tests, performance redesign or external effects.
## 4. Files to inspect
Inspect real 2211144 vs a47e850 delta in engine/include/settlement/core/{world,custody,inventory_transaction,checkpoint}.hpp, engine/src/{world,custody,inventory_transaction,world_save,checkpoint}.cpp, tests/{custody_tests,custody_migration_tests,checkpoint_tests,snapshot_tests}.cpp and tests/fixtures/custody_v14/{capture.cpp,fixtures.hpp,README.md}; M01-P5,F8,S06-03/S15-04. Look at unchanged scheduler/job/cache and replay owners as needed. S06/S15 sibling and stable historical f6493e2 source in /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14. Actual logs in same temp directory.
## 5. Write ownership and coordination
Write scope: none
No mutations, builds (root/implementers run builds), Git/Gitea changes/shared project switches or children. Review real sources, not worker summaries. Root M01 graph identity matches main worktree, check freshness/file coverage; direct source for parsed gaps and all siblings.
## 6. Implementation or investigation approach
Trace actual grant, depletion, admission, meal, cancel while fetching/working/partial, split/merge/delivery, final generated material, retired stacks IDs and replay. Verify preflight of count/capacity/exhaustion incl multi-actor effects plus before allocating memory, no state changes after late failure, no duplicate issue on retries. Audit request key shape/cache/misses/highwaters for exactly-once and ring wrap despite losing prior receipt after retirement; differentiated source/dest refs across ops. Clarify caller-owned scheduler advance vs recoverable repeat endpoint; look for actual repeated/public invocations causing duplicate effects. Validate balance equation and max 5 material/8 claims/11 effects vs true recipes and multiple stores.
## 7. Interfaces and data contracts
Check current/legacy save schema pairs, bounded typed extensions/no trailing bytes/digest, active vs retired references, ID allocator ordering, source/sink balances, strict phase/live ownership/claims/cache and backed capacity, genuine historical Working & routes & generic jobs, mixed/canceled blocked/suspended/unrepresentable legacy error before writing. Distinguish representable historical migration with Opening from true current state. Confirm 4096 fixed retained results and canonical order despite physical wrap. Normal file/guest/corrupt loads preserve old world. Verify resource-limited loops/allocations/drift and that doc performance describes actual configurations.
## 8. Dependencies and integration
Component baseline 4f4c038 and root 2211144 are stable snapshots; sibling latest duplicate-row/consumption adjustments are ongoing and not pre-approved. Report first pass immediately, wait for frozen fixes and final root acceptance. S21-02 will incorporate Current15 authoritative replay separately; original raw13 corpora remain.
## 9. Edge cases security and performance
Watch valid images silently rejected at supported count/phase, malformed modern input creating economic value/alias, algorithmic overrun from untrusted huge small-on-wire counts, pre-commit partial effects, underflow on pending timer0, MAX issuance and persisted retired ID lookup. Only high-confidence findings with source & concrete realistic reproduction/impact. Native Windows limits noted.
## 10. Acceptance criteria
1. READY or changes required for both core and format, with precise counterexample and verification. 2. State source evidence and inspected logs of authentic schema tests, exact old outputs across modes and actual scoped benchmark/limits. 3. Audit zero-byte legacy refusal and current persistence consistency. 4. Final verdict on supplied frozen fixing ref and integrated root evidence only.
## 11. Verification commands and evidence
Use git diff --check and git show/diff a47e850..2211144 for relevant paths; git log for history. Probe logs /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-*-final.log, *compare.log, s15-custody-{strict*,*migration*,*ctest*}.log, m01-custody-*.log. Read actual fixtures/capture.cpp and origin 2 corpora + metadata if needed, note no tests run yourself. Follow root graph coverage skill and direct reads for sibling files.
## 12. Constraints and stop conditions
No additional models/tests or reproduction that mutates checkout. If same defect already under repair, mention coverage and wait for actual new source. Do not equate reported passing tests with independent correctness or native Windows. Report unresolved exposure rather than accepting a moving target.
## 13. Authorization and decisions
User authorizes all milestones, normal pushes and filing real library gaps; only root owns all external operations. Grants/receipts business contract in docs/plan/custody.md, retain functional old projection for normal worlds.
## 14. Return format
Return M01-V14 staged defect-oriented findings with citeable file/line/domain, correction and verifiable example; state final actual refs/outcome only after recheck.
Final economic and codec candidate `e348a42` incorporates S06 `120db6c` and S15 `d613b73`/ `67fba6e`. It is merged into M01 `86b5fb3`, followed by documentation-only `2ba4b3f`. Inspect the actual canonicalization and issuer verification, live/terminal disjointness and operation-specific terminal states, acquisition/hauling/working/tending/meal/return phase and source/capacity rules, validated historical retained routes and ring. The final migration logs `s15-custody-final-{build,migration,ctest}.log` contain the 14 authentic and re-signed test cases. The root will attach the final combined game/transport evidence.
+50
View File
@@ -0,0 +1,50 @@
# Audit live order controls, peer cutoff and integrated viewer recovery
Task ID: M01-V15
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Independent review at M01 merged 2211144 parents a47e850 + c183de1, plus 9bc52ea that includes root test fix 596b491. S04 control branch 13b4665, S16 final 6cc59b4 plus integrated data c183de1. S17 was independently accepted at 455630f. New S04 typed SessionPayload, UI and real Win32 menus; S16 gates raw13/protocol11 hosting on stable represented state and handles queued bytes/outstanding receipts; V14 peer owns core/codec details. S21-02 modern replay will be added to final source.
## 2. Objective and deliverables
Read the complete actual cross-branch changes from both parent sides. Check authenticated command idempotency, exact target and presentation generation, all legacy host/rules/wire and old-binary handling across same-epoch cancellation, and S17 snapshot HUD/frame lockstep. Later issue final integrated verdict when all repaired sources and logs provided.
## 3. Scope and non-goals
Review modern cancel/resume session/GUI, S16 legacy compatibility admission/drop, S18 test fence, integration boundaries including S17. Do not duplicate exhaustive core/format inside V14; identify cross-boundary contract flaws and relay either owner.
## 4. Files to inspect
Inspect engine/include/settlement/core/{command_dispatcher,world,simulation_runtime}.hpp, engine/src/{command_dispatcher,simulation_runtime,custody}.cpp, app/{lan_session_win32,viewer_session,viewer_win32,d3d_scene_win32}.cpp, lan_session.hpp and lan_wire.cpp, tests/{production_commands_tests,production_controls_tests,lan_tests,viewer_session_tests,viewer_frame_smoke}.cpp, S04-02/S16-03 and M01-V13, CMake and actual logs; preserve exact S18 profile/held world behavior. At final recheck inspect S21-02, actual current-canonical comparisons and instructions.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/commits/Gitea/children or shared Serena switching. Use root graph verified identity plus direct actual sources/missed lines; branch specific source via read-only git show/diff.
## 6. Implementation or investigation approach
Inspect complete command admission and dispatch sequencing through trust gates, ledger conflict/replay, stale world/incarnation/city, refusal revision and pending local async UI. Follow open modal/quick selections, exact durable ProductionId, all orders/same cell after paging and generation/connection replacement, guest hide/synthetic action, actual game handler uses active frame. Trace protocol11 hello/auth/input/partial or queued output and completion from both standalone World and Runtime; active default 32×32 exact profile, actual legacy-representable predicate with nonprojectable mixed returns/suspended, ability to continue locally, earlier admitted results retained, later queued command refused. Question race windows at message receive/send/completion vs changing latest() when cancellation occurs in same epoch.
## 7. Interfaces and data contracts
Old protocol unchanged, authentication maps to authoritative context. No leaked stale/partial snapshot or receipt or reapplication after disconnect; host still healthy, rejoin when eligible. User displays precise refusal/return/wait and preserves old title/profile choices, S17 immutable frame synchronization, null replacement fencing and nested modal. Test helper new bounded flush_owner retries documented RuntimeAdmission::Busy but must still assert Faulted, not mask regressions. Consider classic tests that assert immediate admission despite try_to_lock.
## 8. Dependencies and integration
At a47e850 S17 + S21 accepted. Actual 2211144 integrated core&UI+protocol. Root fresh CTest prior to helper has 5/5 targets. 9bc52ea includes helper with 24 successive viewer-suite executions in S18. Stage final includes newest core duplicate-row fixes and S21 modern replay; root appends exact ref/evidence before final verdict.
## 9. Edge cases security and performance
Pay attention to outstanding owner completion survives peer drop, replacing/reconnection with distinct session & same player ID, partially drained FIFO bytes vs disconnect handling, state sampled before committed result, race between readiness and send, actual old binary cross-play both ways. Aggregate genuine observables rather than promising TCP can recall bytes already sent. Prior flaky test must be protected by legitimate Busy handling and bounded wait.
## 10. Acceptance criteria
1. READY or changes required for S04,S16 and their S17/S18 integration independently, reproducible trigger and correction for defect. 2. Verify evidence for six real normal window controls, stale modal, real guest, old compiled two-way interop, held frame+file, prior variant profiles, actual previous signs. 3. Final merged source/CTest consistency, no unsupported native Windows performance/real LAN claim. 4. Review last S21 replay data when new ref provided.
## 11. Verification commands and evidence
Use git diff --check <relevant range>, git show --stat, actual files and surrounding calls. Logs in /tmp/stoneheart-milestones.xprJ2SVp/ s04-cancel-ctest-complete.log, s16-custody-{interop,target-ctest,legacy-corpus}.log, m01-custody-{build,ctest}.log, s18-fault-fence-repeat.log, m01-frame-profiles.log. Look at real harness/fixtures, not summaries. After appending final ref inspect corresponding logs; never require additional physical PCs to certify a Wine run.
## 12. Constraints and stop conditions
No external operations or peer implementation, tests maintained by root/workers. Report actionable actual defects early; if correction only pending on one surface, report other subsystem separately. Never approve unseen final changes.
## 13. Authorization and decisions
User authorized all milestones, branches and Gitea, root owns remote side effects. Existing product P5/F8 authorize cancel/resume and old-peer fence; full contract in docs/plan/custody.md and S04/S16 work orders.
## 14. Return format
Return M01-V15 separate source-anchored component verdicts and after final root recheck combined verdict; identify code/evidence refs and limitations.
Final M01 combined candidate `4bac17d` includes the S16 conditional-admission repair `447a1cf`, S17 full-custody frame assertion `f6402eb`, S21 current-canonical replay `a347337`, S18 bounded fence `596b491` and V14-reviewed economics `e348a42`. Read `s16-published-admission-{before-test,after-test,ctest,interop}.log` for the deterministic real-peer race, successful compatible retry, already admitted work and original binary exchange. Review the publication mutex and stale/Busy/null/fault paths in the actual changes. Combined build and five-target CTest are in `m01-exit-{build,ctest}.log`; independent latest executable GUI/profile, original/current interop and both old byte corpora are recorded in `m01-exit-*.log`. [Library proposal](https://git.faumaray.com/Void/Library/issues/16)
+48
View File
@@ -0,0 +1,48 @@
# 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.
+49
View File
@@ -0,0 +1,49 @@
# Review the authoritative voxel scenario and checkpoint transition before coding
Task ID: M02-F2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Second-stage M02 technical preflight at real region+M01 base13dc673/4bac17d and actual S03 at7a7ff32. M02-P1/F1 foundations passed, one integrated S02 session and strict M01 V14/V15 with custody15. M02-P2 developing exact owner/codec/rules seams now. Need review sufficient constraints for safe parallel World+S19+S15 activation & GUI integration.
## 2. Objective and deliverables
Validate the proposed authority/scenario/language boundary, inventory and durable job semantics, activation and serializer evolution. Earliest verdict on independent S19 compiled profile/new factory and World interface so coding can start promptly. Produce concrete corrections, not a feature redesign.
## 3. Scope and non-goals
Only preflight M02 bounded playable region; no app edits/merge approval or speculative full future city economy. Do not review S02/S03 implementations, separately reviewed. Use their frozen contract as dependency.
## 4. Files to inspect
Read actual world.hpp/world.cpp (2d access, step and capture), custody.cpp/world_save.cpp/checkpoint.cpp, simulation_runtime.cpp+command_dispatcher, rules_manifest.cpp/colony_profile.cpp, viewer_session.cpp/lan/session compatibility, M02 P1/P2/F1 and M01 custody doc, actual sibling S03 voxel_navigation.hpp and S02 region. Include current coordinate types and schema readers and scenario paths.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote/children/shared project switch. Report to root, do not change app or tasks. Direct evidence in separate worktrees.
## 6. Implementation or investigation approach
Adversarially map GridPosition.z=0 for historical records vs one canonical foot in voxel mode; existing flat maps and x/y commands must not alias a different elevation. Compute how typed region/session/observed revisions, stable TerrainOrderId and actor progress, retained terrain target/cargo and actual S06 balances survive failure and reload. Need atomic prospective edit+stock/reservation durable issuance with no-throw publication, accepted cancel retries no duplicate yield, and no loss if storage full. Distinguish extraction operation from ResourceNodeId to avoid wrong source resolution, normal distribution checks and checked allocator. Reconcile system ownership and dependent header freezes.
## 7. Interfaces and data contracts
Validate explicit finite profile & compiled generator/material package, retain byte-identical old two profile manifests and historical modes. Proposed raw16/checkpoint4 pairs and legacy before-byte rejection; new z on applicable physical positions/route, terrain order highwaters and source claims/opaque receipts, canonical generator/deltas, required activation state/revisions, fresh session rekeys no replay of stale external work. Snapshot freeze cheap; save after removal of a future support must preserve target, current safe foot, cargo and next logical choice. New World mode controls stale typed commands without breaking old players.
## 8. Dependencies and integration
Activation barrier must operate before any logical step mutation: target due_tick/required keys, background read/generate/validate returns identities and immutable data, all due batch publishes in sorted order or none. Read failure publishes a recoverable fault, stable old snapshot remains, load/shutdown cannot join a blocked data task inside owner. Exact work remains for S19(profile), S01(owners), S02(file prepare), S15(schema), S17/S18(runtime UI). M02-R2 separately validating Void options; use actual #5/#9/#13/#14/#15/#16 where applicable.
## 9. Edge cases security and performance
Test when same material read/target cross2 pages, support under current person/structure or next planned step, phase=complete still full, single-grant before resource/writing receipt, unknown material/generator/deltas shape, uint32 overflow, observed revision changes on inactive/missing neighbors, obsolete I/O completion after rollback of same region, elapsed clock during wait must not create simulation debt/extra ticks. Physical Windows cannot be asserted.
## 10. Acceptance criteria
1. Earliest scope/lifetimes for S19 formal profile and core public interface sufficient for coding in disjoint files. 2. Concrete counterexamples and remedies for ownership/atomicity or migration data loss, plan constraints for source/bounds/IDs. 3. Achievable real tests marked per cross-component responsibility. 4. Distinguish open P2 confirmation vs actual blocker. Return verdict once planner final available.
## 11. Verification commands and evidence
Read-only direct current source and git rev-parse/show per worktree. No runs or claims of tests of proposed code. Use pinned library source for specific claims, or refer to upcoming R2.
## 12. Constraints and stop conditions
No user contact, remote posts, implementation or pretending future code pass. Do not demand physical PC or unneeded larger product choices for first bounded code. Report immediate corrections as found.
## 13. Authorization and decisions
User approved roadmap; root delegates technical choices and owns all publication. This preflight supplements M02-P1/F1 for actual playable integrated scenario after S02/S03.
## 14. Return format
Return M02-F2 PREFLIGHT with earliest S19/World actionability, actual file references, required tests/failure boundaries and any resolved/remaining blockers.
Preflight accepted the integrated contracts after the viewer explicitly supported the 32×10 terrain region, contact selection required a stance still supported after excavation, and execution lifetime allowed install and shutdown before a blocked old preparation returned. The first due boundary uses requirements from a previously published snapshot. Scope covers the contract only; real gameplay, schema and runtime reviews follow implementation.
+48
View File
@@ -0,0 +1,48 @@
# 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.
+48
View File
@@ -0,0 +1,48 @@
# Freeze owner, terrain work and persistence contracts against the new voxel APIs
Task ID: M02-P2
Role: astra_planner
Status: READY
## 1. Context and baseline
M02-P1/F1 established architecture. S02 frozen and component-reviewed 1ca481b, actual S03 navigation public header at sibling e7046a9 (implementation/tests soon), actual M01 final custody/conditional admission at root4bac17d. M02 worktree13dc673 contains raw15/checkpoint3, S02 and C++ rules; next is a real playable topology with authority, durable work, 3D save, selected profile, render/pick and nonblocking logical activation. A separate worker is building S17 D3D surface/picking.
## 2. Objective and deliverables
Resolve exact interfaces and ownership/order for immediately implementing the complex M02 authority and persistence integration, including yield to S06, mode & position adaptation, atomic support edits, logical activation/resume and old save gate. Return first implementable independent owner package early.
## 3. Scope and non-goals
Read-only second-stage architecture of approved M02, ground it in actual immutable S02/S03 types and new M01 version. No M03/multiregion/water, fake demo or rewriting all old economics simply to get pictured. Prior plan is accepted; extend missing seams only.
## 4. Files to inspect
Read M02-P1/F1, M02 plan/S02/S03/S15/S16/S19 and docs/plan/custody.md, actual merged world.hpp/world.cpp (GridPosition, mutable economic work and capture), custody.cpp/world_save.cpp/checkpoint.cpp, simulation_runtime.hpp/cpp state/load/fault/publication, command_dispatcher.hpp/cpp variant ledger and session UUID, first_colony.cpp, colony_profile/rules_manifest, viewer_session gates. Inspect exact s03 header and S02 region implementation; S17 CPU pick in design.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote/children/shared project switches; root will persist reconciled interfaces. Isolated m02/s03 use direct reads; do not query root index as if identical.
## 6. Implementation or investigation approach
Map minimum full normal gameplay journey: player selects terrain profile, actual resident starts at canonical 3D foot, path through two-cell open/closed door + traversable stairs to cross-chunk upper face; issue excavation order, work from safe adjacent cell, mutate terrain + real material yield with ledger exactly once, close/open door/remove support and recover path, save at that boundary, load and deterministic continuation. Choose precise failure/receipt semantics when any staged operation cannot run. Keep normal actors/stock/stable IDs (no uncorrelated duplicate resident list). Formulate schema proposal for new fields and highwaters and adaptation of old2D.
## 7. Interfaces and data contracts
Specify NEW APIs and minimal concrete owned paths for (i) S01/World terrain metadata, GridPosition.z compatibility, durable terrain orders/actor progress/route and highwater + S06 grant/reservation integration; (ii) required chunk activation: actual work/visibility demand, prepared immutable backing page or regenerated natural + deltas, stable due_tick/reasons, handle root owner publication if waiting/faulted, recover same request or load, bounded CPU/I/O/stale fences; (iii) separate S15 raw16 /outer4 including exact explicit old mappings, route goal/position/deps and fresh session, transactional fallback before first byte for raw13–15 incapable of representing new terrain. Defer performance features while preserving tests and normal enablement. (iv) S19 exact profile/compiled data and current/legacy validation, S04/S16 modern typed edit and client hooks.
## 8. Dependencies and integration
Your P1/F1 work covered baseline. Now target actual available types so core/codec/profile/runtime developers can work simultaneously on frozen header without overlapping files. Direct dependency on S03 valid real header + later library implementation. Temporary detached WTs for M02 system packages allowed by root; one per published milestone/system. Separate geometry source/checked memory before side effect.
## 9. Edge cases security and performance
Stairs and headroom, unsupported occupant/occupied cell cannot be removed, coordinate vs interacting face/adjacency, edits may cross 2+ pages, revision set stale after partial fulfillment, wait-before-effect while full storage, durable exact chosen region/worker/target, rollback/new session re-key route readsets without accepting stale pending execution. Existing WorldState type-copy/inventory caches and old `GridPosition` equality/subscript. Bounded file/scope staging and possible O(N) deep copies. Loaded invalid geometry/queue errors must leave previous snapshot. No synchronous permanently blocked I/O in owner or destructor on replacement.
## 10. Acceptance criteria
1. Source-grounded immediately dispatchable WHAT/HOW for first owner plus peer stages with exact data types/fields/ownership. 2. Minimal integrated test scene exercising real commands, route, stock, save/load, old 2D and held activation. 3. Acknowledge genuine potential wider interaction e.g. legacy 2D methods interpreting z and give guard/fallback. 4. Distinguish what directly exploits existing Void vs any confirmed generic missing guarantee (researcher covers async).
## 11. Verification commands and evidence
Read-only git rev-parse/status/show actual m02 and s03 and root refs, direct source/surrounding tests. Produce feasible existing Windows GCC16/CMake/Wine and targeted CTest commands for later packages. No bringing up auxiliary services or claiming own tests.
## 12. Constraints and stop conditions
No application edits or published issue, extra scope or approval loop. Recommend concrete principled tradeoff with verification where bounded/reversible. Immediate send first typed public seam as available. Two separate files cannot both own the same source; identify serialization points honestly.
## 13. Authorization and decisions
User asks full implementation and delegates choices. Approve core first, task assignments and Gitea sends all root-owned, earlier design residence one cell/two height, upper worked excavation yields material through S06, no old-LAN new-mode projection.
## 14. Return format
Return M02-P2 PLAN with early affected-code ownership/interfaces, real file/symbol refs, dependency graph/failure cases, contract for scope-independent development, decisions needing F2/next verification.
+49
View File
@@ -0,0 +1,49 @@
# Verify pinned support for logical chunk readiness and bounded persistence
Task ID: M02-R2
Role: astra_researcher
Status: READY
## 1. Context and baseline
M02 now has actual S02 paged region and immutable prepared pages; S03/public nav and S17 ray consumers ongoing. M01 final raw15/checkpoint3 and FIFO files on Windows x64; logical activation must wait for all pages due at a logical tick while owner can still load/shutdown, keep old snapshot during I/O failure and discard obsolete work. Existing Void #5/#9/#13/#14/#15/#16 cover distinct earlier needs. Pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792 == upstream HEAD last verified.
## 2. Objective and deliverables
Inspect real pinned published API/tests to distinguish directly reusable pieces vs genuinely missing generic scheduled work/barrier/storage capabilities. Check coverage for typed terrain rules representation and explicit seed/revision persistence only as relevant. Send concise concrete evidence and any issue candidate.
## 3. Scope and non-goals
Read-only official-source feasibility, registry matching + downstream consumer/replacement tests, no application edits or remote writes. No filesystem/network crawl, new Nix dependency, generic world design, or unrelated library issue filing.
## 4. Files to inspect
Read M02-R1/P1/F1, plan M02/S02/S15/S01/void-library; VoxelRegion::prepare_generated/prepare_restored/activate, SimulationRuntime loop/fault/load/worker options, CheckpointFiles/World save size caps, S21 observer semantically. Pinned exact library include and matching standalone tests for Async (FuturePool, TaskScope, tasks/operations), Binary Reader/Writer/Budget, file/storage/transaction and any actual stateful ordering/barrier module with name found. Gitea existing upstream issues3–16 can be read via authenticated tool or prior matrix; no secrets.
## 5. Write ownership and coordination
Write scope: none
No working tree edits, Git mutations/remote comments, credentials or other project data, or switching shared Serena. Actual sibling git roots confirmed by parent; pinned isolated source direct. Independent of M02-P2 owner design.
## 6. Implementation or investigation approach
Check exact semantics for bounded submissions (retained payload/full queue), completion wakeup without blocking actor/control loop, ordered barrier over required keys at logical step, supersession/cancellation/stale results, fault/recovery while preserving still-running work/ownership. Determine if directly using future readiness/TaskScope provides every contract; do not turn purely game-specific tick policy into an unnecessary library ticket. Check relevant real API source/tests and feasible Windows availability.
## 7. Interfaces and data contracts
Return named actual modules/public methods and important limits, whether resources submit/update/cleanup fit M02 nonblocking owner. Consider if existing #5/#13/#14/#15/#16 already cover actual reusable subcontracts (reuse matching issue). For any distinct genuine gap, write narrowly scoped, library-general input/result, shutdown/late completion ordering and replacement test involving two prepared operations in opposite order and one obsolete generation. Include pinned source/test URLs or paths; no public posting.
## 8. Dependencies and integration
Root will use findings in M02 owner/codec/activation spec and file any genuinely missing issue before local integration. No approval of application code or code changes needed. Current prepared pages/region activation, historical raw15 /128MiB work as known consumers.
## 9. Edge cases security and performance
Bounds such as largest 256 pages/4096 edits, seed/version deterministic rebuild, storage/sidecar optional vs existing saved file, Windows closed handle/decode budget, pool task holding old World on replacement/Shutdown. Prefer exact recorded behavior over guesswork; never read token configs or transmit private content outside configured repos.
## 10. Acceptance criteria
1. State directly composable pin-level facilities and tests. 2. Identify missing guarantee vs application-specific policy; map replacement tests/issues and avoid duplicate. 3. Record real native/cross limits and any unchecked uncertainty.
## 11. Verification commands and evidence
Read-only git -C <pin> rev-parse HEAD; rg --files/header+test direct evidence, root/subtree source check for current owner. Optional read-only official Gitea issue listing allowed. Temporary /tmp trial compile only if necessary for an uncertain important contract. No code snippets containing private user projects to third parties.
## 12. Constraints and stop conditions
No speculative upstream issue or tests claimed unrun. Report early distinguishing existing primitive even when other details pending. Stop if exact pin missing and notify root with supported fallback.
## 13. Authorization and decisions
User expressly mandates verifying VoidLibrary and filing missing reusable features in that project. Root handles all actual issue writes and links to local implementation. Paid services and installs outside scope.
## 14. Return format
Return M02-R2 VERIFIED/PARTIAL, actual APIs/source+test, genuine reusable gaps/issue candidates or existing records, exact downstream test for possible substitution.
Pin `7b0fea6095f603f9e1904f66dfdc7752f4be4792` provides bounded `FuturePool::try_submit`, movable immutable inputs and exception-carrying futures. ThreadExecutor joins on destruction, and the game adapter may run overloads inline. The application therefore requires a separately owned bounded executor, true readiness notification or short readiness polling and application-level bounds on completed/obsolete pages. Existing Void issues 3, 5, 9, 13, 14, 15 and 16 were verified open; the due-tick rule uses the existing facilities. The reviewed Void Storage FilePort at this pin is POSIX-specific. No new standalone runs in this research packet.
+53
View File
@@ -0,0 +1,53 @@
# Audit immutable terrain mutations and their navigation consumer
Task ID: M02-V1
Role: astra_reviewer
Status: READY
## 1. Context and baseline
M02 foundation candidate 1ca481b in identical s02 and m02 worktrees, compared to 0d71bcf. M02-P1/F1 set signed32 coordinates/64bit endpoints, finite bounds/canonical generation, disjoint worktree ownership. S03 branch initially 6d1123e with incomplete implementation; review that only when final evidence announced. Actual S02 full 4/4 CTest, 155 core includes14 voxel,9 LAN,14 viewer plus real frame; checks in temp.
## 2. Objective and deliverables
Independent defect-oriented source review of completed section S02-01, then S03-01 and both combined after frozen. Send first S02 verdict as soon as possible. Root uses that sign-off and integration checks for real new branch/PR.
## 3. Scope and non-goals
Coordinate math, generation, immutable lifetime and edit failure contracts, then separately path/query/cache invariants. No gameplay/codec/render implementation or approval of unchecked future M02 integration.
## 4. Files to inspect
Read actual include/settlement/core/voxel_region.hpp under engine/, engine/src/voxel_region.cpp, tests/voxel_region_tests.cpp, two CMake entries, S02 docs, S02-01 and M02-P1/F1. Review exact pinned Void Numeric/Binary/Hash APIs and #11/#14 if relevant. Once S03 is frozen, read voxel_navigation.hpp/cpp/test plus CMake/graph interfaces/region consumers and S03-01. Use direct sibling source; do not activate shared Serena. For Stage A m02 HEAD=1ca481b.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote effects or children. Parent and workers have exclusive separate WTs. Stage A must use actual committed code plus standalone allocation-probe source and logs, not just worker statements.
## 6. Implementation or investigation approach
For S02 trace equals/extremes, join/split INT_MIN/INT_MAX, checked half-open bounds and partial pages, stable index/neighbor overflow, deterministic seed encoding, generator consistency at seams and version, opaque candidate/provenance validation for multiple activation, immutable directory/const page/ref lifetimes, aliases from import retained data. All-or-nothing activate/edit for stale duplicate invalid/no-op/resident/revision/alloc failures with output arrays. Test transactional/caller-retained memory boundaries incl actual charged value vs std::vector capacity, incorrect estimates, dirty-face list canonical with boundary cells and unaffected pages. Evaluate actual failure-injection probe rather than counting a synthetic status.
## 7. Interfaces and data contracts
Passability helpers must agree with mission: soil/stone support, DoorClosed blocks body, DoorOpen/Air permit clearance only, generator natural. Queries distinct outside/unavailable/air, stamps identity consistent at partial and extreme bounds, after activation previous unavailability stale. Request ordering should not alter same group revision/result. Multiple independent copies sharing original base can diverge; document expected caller/session/view assumptions and distinguish actionable bug from absent future feature.
## 8. Dependencies and integration
Stage B only after linked S03 and complete worktree. Check actual Void BFS worklimits incl scratch allocations, bounded index dimensions, zero-length fast path legality, input/refusal/cancel/unknown, blocked/clearance reads incl passage and support from neighboring pages, exact path/interaction/cost, stable deterministic ties, affected negative invalidation vs edit in off-route region, safe next step. Actual two-floor scenario and interaction consumers belong to later packages.
## 9. Edge cases security and performance
Reject overstated memory/benchmark claims, unsafe reference/worker lifetime or future worlds using stale pages after region handoff. Check wrapping revision/limit results with no dirty mutation. Compare actual content and live normal edge flows vs only invented tests. Later path results cannot authorize newer session, through walls or truncated search marketed as unreachable.
## 10. Acceptance criteria
1. Stage A/B verdicts independently with actual refs, exact location, trigger, impact and fix/verification for each defect. 2. Affirm or refute saved earlier views/rejected edits/accurate neighbors, 1 vs 2/6/12 genuine tasks, branch evidence. 3. Stage B inspect real upper floor stairs/door/material semantics, limited and unavailable results plus missing/unchanged revisions. 4. Final integration verdict only when source/logs provided, report native target limitations.
## 11. Verification commands and evidence
Use git -C sibling show/diff --check and actual files, no builds. Inspect /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-{build-complete,ctest-complete}.log, s02-voxel-allocation-probe.cpp/s02-voxel-allocation.log, targeted info and S03 logs when supplied. Source-only facts separate from logged runs. Sibling paths outside verified root index, direct reads appropriate.
## 12. Constraints and stop conditions
No approving the S03 implementation mid-flight. No fake workloads/claims or extra upstream issues without a genuine uncovered API. Send earliest actionable finding immediately. No source/branch/Serena/remote changes.
## 13. Authorization and decisions
User supplied fully approved roadmap plus branches, Gitea and issue workflow. Reviewer role independent. Root owns all side effects and roadmap acceptance.
## 14. Return format
Return M02-V1 Stage A (and later B/combo) READY or CHANGES_REQUIRED with actual evidence and source refs. Include any untested platform/hardware behavior.
Stage A `1ca481b` passed component inspection. Combined region / current M01 source is `13dc673`; build and CTest evidence are in `m02-region-{build,ctest}.log`. The finished S03 component is `7a7ff32` on top of the actual linked S02 base. Inspect the new navigation header, implementation and tests with `s03-voxel-{build-final,focused-final,ctest}.log`. Stage A and B verdicts may be returned separately before the later combined navigation check.
Corrective checkpoint: the two reported S03 defects are fixed at `17389b2`, and the integrated code plus all M01 corrections is `c40d9b2` in m02. Inspect the actual 7a7ff32..17389b2 source and tests, including proof of both old failures, possible/inconclusive reachable edges, all four max-size calls, and all combined status/geometry contracts. Evidence is in `s03-voxel-review-{before,final-focused,final-goals-ctest}.log` and `m02-foundation-{build,ctest}.log` when complete. Root requests an independent final Stage B and integrated foundation verdict; no review of future unpublished gameplay.
Final interaction-window correction at `2017e56`, integrated with final M01 at `14987b2`. Reinspect actual 17389b2..2017e56 including omitted contacts, both missing and known exits and enclosed start, side effects on budgets/direct goals. Component proof and full results `s03-interaction-{before,after,after-build,after-ctest}.log`; combined build/CTest `m02-foundation-final-{build,ctest}.log`. Return final source and Stage B/combined signoff after logs.
Final review accepted `1ca481b`, `2017e56` and their combined implementation `14987b2`. Logs contain both old failure classes and the clipped-contact regression before and after repair. All 14 focused navigation cases and all five integrated CTest targets pass under Wine. Native hardware and the future normal gameplay integration remain outstanding.
+49
View File
@@ -0,0 +1,49 @@
# Review bounded signed voxel meshing, D3D11 height slices and picking
Task ID: M02-V2
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Foundation S02/S03 accepted at 14987b2. Actual frozen S17 slice component 37a08d4 in s17-voxel vs 13dc673, and combined 129d7f2 in m02-render vs 14987b2. Normal S18 client hookup is subsequent and deliberately not claimed yet. Independent reviewer has not implemented this code.
## 2. Objective and deliverables
Adversarial code/contract and recorded-test review of real WARP and CPU mesh/picking/retained packet. Provide quick actionable findings for any code or claimed evidence problem then verdict on component and combined.
## 3. Scope and non-goals
Only S17 geometry/limits/session/readset, render/camera/pick agreement/surface and exceptions, D3D integration and regressions. Later gameplay/codec/S18 UI out of scope. Native physical hardware separate.
## 4. Files to inspect
Inspect app/{voxel_scene,d3d_scene_win32}.{hpp,cpp}, tests/voxel_scene_tests.cpp, CMakeLists.txt, docs/plan/systems/S17.md, S17-02 task, S02 navigable geometry/header, existing frame smoke/shader code. Exact sibling worktrees outside root graph; direct source and git diff/check. Never change shared Serena project.
## 5. Write ownership and coordination
Write scope: none
No file/Git/remote mutations, commands for read-only inspection; no subagents. Root gathers actual runs. S17 worker completed implementation separately.
## 6. Implementation or investigation approach
Trace projected coordinates vs shader (foot origin/local offset/z-up, signed extremes, camera fractional pan/zoom, cap distance and overflow); DDA direction/ties/zero component, missing/invisible paired open door, cut at inclusive slice and border of region. Check visibility of internal/edge faces, admission/culling budgets before allocations, stale/empty session and actual frame/pick consistent for held publication.
## 7. Interfaces and data contracts
Retained immutable VoxelScene uses actual VoxelRegion directory and readstamps, preserve source data through newer edits. Mutable GPU resources must keep old prepared geometry working after failed preparation and avoid treating device mismatch as valid. Verify tested D3D11 WARP color readback vs mathematically chosen surfaces and real default frame path. Ensure terrain/unknown materials draw accurately with z-buffer and DDA at shared boundaries.
## 8. Dependencies and integration
Compare original 13dc673 and 37a08d4; combined 129d7f2 includes corrected S03/current M01. Evidence resides /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-final-{build,ctest}.log and m02-render-integrated-{build,ctest}.log when complete. Void #12/#13 existing links and proposed replacement conditions; no extra novel gap absent evidence.
## 9. Edge cases security and performance
Bound read/face/vertex bytes, allocation failure, effective public camera/view dimension and signed-coordinate endpoints, ambiguous corners, overflow D3D limits, HRESULT lifecycle, capturing prior immutable GPU packet from another device, stable rendering while world or save busy. Discern correctness vs explicitly declared renderer limits/performance.
## 10. Acceptance criteria
Concrete trigger/ref/impact/correction plus before/after validation for any finding. 15 focused behavioral pixel/CPU cases and full 6-target CTest + new integrated code must match actual logs. Give verdict only for what was built, distinguish real WARP readback/visible legacy frame/physical Windows or untested GPU failure injection.
## 11. Verification commands and evidence
git show 37a08d4; git diff --check 13dc673..37a08d4 and 14987b2..129d7f2; inspect files and /tmp/stoneheart-milestones.xprJ2SVp/{s17-voxel-final,m02-render-integrated}-{build,ctest}.log. Component 6/6 in17.60s reported; verify independently. Full combined build still running; send initial findings independently.
## 12. Constraints and stop conditions
No changes, credential or remote writes. No reliance solely on existing summary. No false approval for end-to-end editable game until S18/World integration. Send first defect early even if waiting on remaining logs.
## 13. Authorization and decisions
User authorized milestone/branches; only root commits/pushes/opens issues. This contract covers independent technical review, not external merge.
## 14. Return format
Return M02-V2 READY/CHANGES_REQUIRED per component and combined, exact source refs, concrete experiments, checked logs and platform limits.
Independent review accepted the S17 component at `37a08d4` and joint renderer/region/navigation tree `129d7f2`. The rendering branch merge `f2ff1ce` has exactly the same tree as the reviewed component. The combined run passed all six CTest targets under Wine 11, including 15 voxel scene tests with real WARP pixel captures. Generated signed terrain contained 1,998 faces for 6,528 inspected cells. Separate work connects this API to the resident, preview, pointer controls and saved session.
+50
View File
@@ -0,0 +1,50 @@
# 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
@@ -0,0 +1,52 @@
# 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 @@
# Cancel and resume production work by durable order ID
Task ID: S04-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s04 e5d01a4 contains 5a64a27 user-facing viewer + private S06 header 4f42488. World::cancel_production/resume_production(ProductionId)->CommandStatus, AgentState::Returning, Agent.execution and ProductionOrder.suspended are frozen declarations; peer S06 implements actual effects. Legacy LAN11 supports only PlayerCommand and local LegacyCabinPayload has existing runtime path. Existing Работы menu is a real entry and current UI correlates exact SessionPayload after receipt.
## 2. Objective and deliverables
Connect modern cancellation and resumption to the authenticated command dispatcher and an actual localized host/offline Win32 control aimed at durable ProductionId. Make receipt/status/return reason visible and verify retry, rejection, stale selection and real returned cargo with S06.
## 3. Scope and non-goals
Only S04 modern session variants and minimal Win32 normal orders action for present job lifecycle. Keep historical PlayerCommand, CommandKind, LAN11, ordinary demolition/move and S19 profiles unchanged. S06 owns World and all ledger/cargo transitions; S15 owns codecs. S17 owns presentation in a sibling branch.
## 4. Files to inspect
Read command_dispatcher.hpp/.cpp, simulation_runtime.hpp and exact receipt semantics, app/viewer_win32.cpp enqueue_command/complete_command/edit_at_cell/Работы menu & agent status, app/viewer_session and existing modal epoch guards, tests/session/runtime and viewer. Inspect frozen custody.hpp/world.hpp and docs/plan/custody.md. Study exposed work order/actual stages and S04 docs.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; app/viewer_win32.cpp narrow order-action menu/handler and returned cargo display only; tests/session_tests.cpp and NEW tests/production_commands_tests.cpp if needed; NEW tests/production_controls_tests.cpp for the real Win32 controls; CMakeLists.txt only owned test entries; docs/plan/systems/S04.md
Isolated s04 only; other workers have independent worktrees. Never revert changes, edit S06/S16/S17 or switch shared Serena. No Git/remote ops/children.
## 6. Implementation or investigation approach
Add distinct typed CancelProductionPayload{ProductionId production} and ResumeProductionPayload; equality/payload conflict checks go through existing SessionPayload variant/ledger. Admit/validate trusted client/world/session/city/request before World methods and pass domain status through existing DispatchReceipt; successful mutations advance revision once, refused result retained. No legacy sequence side effect for these new modern payloads or untyped std::get fallthrough. Existing cabin branch remains exact.
## 7. Interfaces and data contracts
User must be able to cancel/resume through normal game UI. Prefer a single order-management action in existing Работы menu with a map target using current user-visible names/coordinates and explicit Отменить/Возобновить choices; if multiple eligible orders share a cell, bind each displayed choice to its actual durable ProductionId. Don't use vector index as command. Host/offline only: hide/disable for legacy guest before enqueue. Pin opening snapshot, recheck world+session incarnation and presentation generation after any modal interaction and validate target still appropriate; never send an old selection into a loaded different colony. Bound menu/list size while retaining access to all choices. Use existing asynchronous queue and return receipt so UI only reports completion after commit. Returning resident with no eligible space shows why it waits; avoid reporting unearned cancel/return, preserve existing move/demolish behaviors.
## 8. Dependencies and integration
Depends on S06 core, not yet linked initially; root provides actual local commits before final build. S17 in another branch may touch drawing; keep changes narrow and alert parent about status text fields so final packet integration preserves them. Separate S16 tests for incompatible legacy guests, no new wire variant.
## 9. Edge cases security and performance
Resource/capacity refusal returns repeatable domain status with stable world and actual request identities. Prior receipt still valid after target removed. Wrong-world/city/session and same request differing ProductionId/variant are fenced/Conflict. Early command/UI must not synthesize arbitrary orders or try to resolve IDs from stale sessions.
## 10. Acceptance criteria
1. Tests use actual dispatcher/runtime with live order/cargo; same request accepted/refused twice, different payload same key Conflict, wrong world/session/city rejected, accepted cancellation/return and resume retained site progress once. 2. UI test actual action/receipt, bound durable ID and cancel on stale dialog without enqueuing new-world action, legacy guest cannot submit. 3. Default legacy command numbering/cabin/old raw & LAN tests unchanged. 4. Native Windows x64 cross-build + loops, full integrated CTest when dependencies provided.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s04-cancel-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. Compile independent translation units/tests as feasible before S06 implementation lands. Use actual focused session/order tests and CTest -V, isolated Windows/Wine UI smoke under /tmp, logs s04-cancel-*. git diff --check. Native hardware not assumed.
## 12. Constraints and stop conditions
Never implement duplicate inventory mutation/ID logic or mock final acceptance. If cyclic API, incorrect capacity/epoch or unavailable real core, report exact required seam and continue independent adapter/tests. Two failed same-cause attempts escalate. No Git/remote/children.
## 13. Authorization and decisions
User authorizes all milestones. F8/root approve explicit modern cancel/resume of retained partially built bed or existing loom, stable identities and old Busy constraints. Root integrates/publishes once end-to-end safe.
## 14. Return format
Return S04-02 READY or PARTIAL, actual normal command/UI entry, test outcomes/real dependency status, logs and native limitations.
The Win32 executable may include the viewer implementation in its test translation unit using its real window and menu handlers. Drive modal selection via an actual window timer, including a world replacement while a choice is open. Cover the correct durable selection, receipt, stale selection and guest action fence. Reuse existing test/build conventions and keep this target independent of the S17 frame smoke. Register it with CTest and report actual Wine results after S06/S15 link.
+48
View File
@@ -0,0 +1,48 @@
# Gate legacy guests on exact representability of authoritative cargo
Task ID: S16-03
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s16 1b57183, local base modern selector 5a64a27 + S06 header 4f42488. World::legacy_representable() const noexcept and typed UnsupportedLegacyState declared. S06 and S15 owners implement actual new states and raw13 preflight. Existing session supports LAN11 32×32/default rules and historical old binary interop. A common send path sends pending output before a new snapshot, so handling only encode exceptions is too late.
## 2. Objective and deliverables
Reject admission and disconnect incompatible existing LAN11 guests early when the actual authoritative snapshot cannot project into the old format, while preserving the host and all already-admitted receipts. Keep both direct/deferred UI Host refusal before creating a listener.
## 3. Scope and non-goals
LAN11 adapter, host-readiness predicate used by Win32, and focused compatibility tests. No protocol change, modern authoritative-rules restriction, dispatcher command variant or alteration of actual inventory ownership. Normal valid old/new binary interop remains.
## 4. Files to inspect
Read app/lan_session_win32.cpp all poll_network, handshake/receive/send_snapshot/pending output/complete_runtime_command paths incl older standalone poll(World&), app/lan_session.hpp, viewer_session.cpp::can_host_legacy and member/header/actual normal callers from S18; engine/core/world.hpp public frozen readiness + exception, S04/S06 plans and M01-F8. Read tests/lan_tests.cpp and viewer_session_tests.cpp, historic two-binary interop harness in /tmp.
## 5. Write ownership and coordination
Write scope: app/lan_session_win32.cpp; app/lan_session.hpp only if meaningful API docs or narrow shared predicate; app/viewer_session.cpp only can_host_legacy and local support predicate; tests/lan_tests.cpp and tests/viewer_session_tests.cpp narrowly for legacy compatibility; docs/plan/systems/S16.md
No S06 World/codec/cancel implementation, dispatcher edits or S04/S17 viewer_win32 file changes. Others own these in siblings; do not revert/switch Serena or write outside worktree except your temp verification source. Root owns Git/remote.
## 6. Implementation or investigation approach
Gate exact supported rules/active dimensions and actual World::legacy_representable result before accepting/authenticating, receiving/dispatching guest commands, sending/continuing queued legacy output. Do not send partially legacy-encoded bytes. A newly unrepresentable state disconnects old peer and safely clears outgoing/peer-specific pending/request metadata; preserve settlement of already-admitted owner work and compatibility of later reconnection. Incoming cmd must check current published view/epoch before admission; allow valid previously accepted owner work to settle after disconnect. Old poll(World&) normal host path must guard projection and keep owning standalone world unchanged on refusal.
## 7. Interfaces and data contracts
Use typed compatibility failures/explicit reason or existing guarded notice. Healthy hosts continue stepping, saving modern checkpoint and receiving modern commands; ViewerSession::can_host_legacy must check published exact default and freeze during replacement, direct/deferred actual callers gate on that. Do not silently downgrade, fabricate a matching old state, or disconnect a guest for representable ordinary historical default/simple worlds. Preserve user-selected local colony and port/peer while refusing a newly requested Host.
## 8. Dependencies and integration
Depends on S06-03 implementation+S15-04 current15 for actual integrated tests. Local branch currently contains header only, parent will merge coherent core for real normal entry and old binary. Design fixture with a real canceled mixed-cargo/no-storage or withheld suspended site and positive representable counterpart; coordinate with S06/S04 if needed. No mocks for final acceptance.
## 9. Edge cases security and performance
Beware connected guest with old snapshot bytes pending, re-auth/wrong connection incarnation, UDP not involved, S16 ledger boundaries vs published current epoch. Keep game thread and UI polling nonblocking. Avoid full serialization solely to test readiness on each poll when dedicated bounded pure check exists; use immutable snapshot identity/revision when caches needed.
## 10. Acceptance criteria
1. At least one real unrepresentable default colony (mixed canceled carrier/single unlinked plank/suspended residual as applicable) refuses listener/handshake and drops already-connected guest before a further wire command mutates it. 2. Already-admitted command still settles. 3. Host remains healthy, new modern save/reload works and local progress continues. 4. Normal old protocol fixture and old binary both directions pass, valid default simple historical colony still allowed; optional rules still denied. 5. All CTest/GUI at final integrate.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-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. Compile independent translation units as feasible now; verify actual core when root supplies it. CTest -V/targeted wire/owner, external interop harness /tmp/stoneheart-milestones.xprJ2SVp/lan-owner-interop.{cpp,py}; keep s16-custody-* logs. Scoped tests use localhost only and temp saves.
## 12. Constraints and stop conditions
Never weaken wire11 bounds or gate whole modern owner/dispatcher. Do not add general authentication flow or expose an external service. If checked interface missing/incorrect, inform root and work independently pending real dependencies. No Git/remote writes/children. Two same-cause failed repairs escalate.
## 13. Authorization and decisions
User authorizes full project. F8/root approve truthful unsupported legacy projection and disconnect preserving host; original normal interop retained. Root owns public actions.
## 14. Return format
Return S16-03 progress/READY or PARTIAL, actual admission/queued frame/receipt behavior, tests/logs and native limits. Identify exact dependency commit needed for final integration.
+47
View File
@@ -0,0 +1,47 @@
# Linearize legacy guest command admission with authoritative publication
Task ID: S16-04
Role: sol_implementer
Status: READY
## 1. Context and baseline
Independent review M01-V15 found a real race in S16-03 at c183de1 in s16 worktree. app/lan_session_win32.cpp current_runtime_snapshot takes a healthy compatible immutable snapshot, then handle_runtime_host later calls unconditional SimulationRuntime::try_submit. Runtime::enqueue under its mutex only checks closing/capacity; a host cancellation can publish an unrepresentable world in the same epoch between those operations. Work already queued before cutoff must still settle. Earlier old/current compatibility and partial buffered data tests unrelated to this gap passed.
## 2. Objective and deliverables
Enforce atomic conditional admission against the exact compatible publication already inspected by protocol11; verify a deterministically forced check→concurrent publish→enqueue race using the real owner/host/socket. Keep old clients functional on compatible newer snapshots, and no secret fallback to the legacy path.
## 3. Scope and non-goals
Limited change to S16 adapter, smallest general runtime admission seam and targeted regression/doc. No protocol layout change, global gameplay trust/authority changes, or duplicate compatibility logic under network ownership.
## 4. Files to inspect
Inspect engine/include/settlement/core/simulation_runtime.hpp, engine/src/simulation_runtime.cpp enqueue/publish/fault/try_submit, app/lan_session_win32.cpp + lan_session.hpp poll/handle_runtime_host/reply/drop, tests/lan_tests.cpp plus tests/runtime_tests.cpp existing gates, docs/plan/systems/{S01,S16}.md. Read M01-V15 and S16-03 and actual earlier logs in temp.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; app/lan_session_win32.cpp; app/lan_session.hpp if essential for a small test seam; tests/lan_tests.cpp; docs/plan/systems/S16.md. S21 owns runtime_tests.cpp in a sibling; keep your specific regression in lan_tests. No shared changes/remote, Git writes, children or shared Serena switching.
## 6. Implementation or investigation approach
Add narrowly named conditional admission to normal runtime queue (suggest try_submit_if_current, explicit checked snapshot). Under exactly the mutex serializing published/state and queue insertion, before effects, require RuntimeState::Running and match non-null expected retained shared publication (identity pointer or version+incarnation with equal semantics). Leave existing unconditional local API unchanged. Ensure lock contention/capacity Busy is distinct in outcome/handling from a changed publication, e.g. explicit mismatch result or documented guard outcome; no read outside mutex can certify admission. Do not recompute/copy the whole World in the lock. Never revalidate/revoke work already admitted before publication.
## 7. Interfaces and data contracts
LAN adapter passes checked published snapshot capability with outgoing command. On mismatch re-evaluate latest state: incompatible/faulted/session replacement clears peer/buffers and never enqueues stale envelope; healthy same-session changed revision must retain old protocol sequence/ack, e.g. legitimate Busy and old-client retry or bounded retry with current snapshot, not disconnect all guests every tick. Invalid/fault/capacity must not emit receipt for an unadmitted command as Accepted. Distinguish handshakes/queue flush; prior external bytes already sent cannot be recalled.
## 8. Dependencies and integration
Real S04 cancel from host and custody S06/S15 already in s16. Root also integrating S21/S18 tests. Use test hook at narrow point after checking snapshot and before runtime enqueue, or equivalent genuine scheduling barrier. Avoid new permanent per-frame overhead unrelated to this path. If testing hook is needed, prefer existing configured seams or narrow optional sterile observer rather than global test-only code in normal library that changes semantics.
## 9. Edge cases security and performance
Protect repeated remote sessions/idempotency and stale same-epoch publication across canonical cancellation. Guards must not coerce nullptr into unconditional admission, ABA impossible with retained shared_ptr and immutable identity. Publication faults and shutdown must obey existing semantics. Do not busy-loop when current world is advancing. Old/queued command with exact accepted availability must complete on healthy owner even if the state changes afterwards.
## 10. Acceptance criteria
1. Deterministic two-thread/real-loopback test holds remote operation after capturing representable S, publishes same-epoch unrepresentable S+1 via real typed cancellation, releases, proves zero new guest ledger entry/sequence/stock/command effect and correct peer drop (works on old code as counterexample). 2. Positive same-session compatible revision interleaving maintains coherent old-client progress/sequence and earlier admitted request still settles. 3. Existing 13 LAN and target viewer, actual compiled original/new host+guest both ways pass. 4. No change to PC11 bytes/ordinary local auth or installed snapshots.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-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. Run new focused LAN tests and full CTest -V, old/new interop harnesses from your S16-03 context, use logs s16-published-admission-*.log and git diff --check. Native Windows unavailable. Before fixed build, show exact reproducer outcome if feasible.
## 12. Constraints and stop conditions
If inability to atomically compare protected publication and enqueue, report actual contract and fail closed within scope. After two failed same-cause attempts root escalates; no other agents, external writes, retrying commands outside the appropriate session or full scans under runtime lock.
## 13. Authorization and decisions
User requested end-to-end software and protocol compatibility. Fresh V15 correction belongs to S16; bounded change to existing owner seam is authorized. Root exclusively owns commits/remote operations and post-fix re-review.
## 14. Return format
Return S16-04 READY or PARTIAL, frozen paths, observed pre-fix failure/post-fix controlled interleaving and old/new compatibility, actual logs and residual limits.
+48
View File
@@ -0,0 +1,48 @@
# 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.
+48
View File
@@ -0,0 +1,48 @@
# Draw and pick the same sliced voxel terrain through Direct3D
Task ID: S17-02
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated detached staging worktree s17-voxel at 13dc673 contains both M01 immutable D3D frame changes and accepted S02 1ca481b (including MaterialId DoorClosed/DoorOpen). Later root integrates this work to the existing system/s17-rendering. M02-P1/F1 define shared z-up projection, frozen bounds/32³ S02 sampling/availability, finite edit scenario. Actual shader uses (x−y)*halfTile.x and (x+y)*halfTile.y−16*z, existing flat pick is z=0. Void pin 7b0fea6 Math::Vec/Numeric present, general bounded 3D grid-ray traversal absent under issue #12; mesh neighbor revision issue #13.
## 2. Objective and deliverables
Implement a usable terrain geometry and height-slice picking API, real D3D11 renderer entry point and offscreen WARP test proving projected visible surfaces agree with mouse hit cells/faces for edited signed voxel regions. Provide frozen interface early for normal S18+World frame hookup. Root/next worker wires actual authored game when its World factory exists.
## 3. Scope and non-goals
M02 terrain presentation/picking/CPU prepared geometry and actual D3D draw only; do not edit mutable World, simulation, new-game menu, viewer_win32.cpp, existing legacy protocol/codec or actor motion. Existing 2D rendering and immutable prepare/render interface are relied upon; cover regressions. Use game generated terrain and material colors, no borrowed graphics.
## 4. Files to inspect
Read real S02 voxel_region.hpp/cpp/test, S17-01 frame contract and S17 docs, M02 F1/P1, dependency matrix M02 and pin Math Vec/Numeric. Read app/{d3d_scene_win32,map_camera}.hpp, d3d_scene_win32.cpp Mesh/PreparedGeometry/shader/camera constant buffer/D3DScene::render, viewer_win32 map_cell/scene_view/camera/timers, tests/viewer_frame_smoke.cpp CMake graphics targets. Share public anchors with S18 owner; M02 normal World integration upcoming.
## 5. Write ownership and coordination
Write scope: app/d3d_scene_win32.hpp; app/d3d_scene_win32.cpp; app/voxel_scene.hpp; app/voxel_scene.cpp; tests/voxel_scene_tests.cpp; CMakeLists.txt; docs/plan/systems/S17.md
New dedicated voxel_scene files plus tested D3D terrain overload; CMake only own source/test entries/libraries. Other agents own separate WTs. No external actions, Git writes/checkout changes, shared Serena activation, children or other source edits. Temporary controlled probes in your own /tmp build OK.
## 6. Implementation or investigation approach
Use actual existing shader isometric basis, z-up. Expose one view/projection/slice model for both rendering and hit query; support real camera origin/pan/scale/viewport and integer slice inclusive maximum visible z. Render material faces exposed to air/open door/slice/outside, avoid duplicate internal faces across adjacent loaded pages. Decide display for unavailable neighboring pages consistently; picking must return unresolved when an unloaded visible cell can precede a farther surface. Open doorway permits seeing and picking through its aperture, closed door blocks, rendering/picking same shape. Bound drawable cells/faces/time, support signed absolute/extreme coordinates via region-local origin and double checked ray/cell transforms, no huge implicit dense region allocation. Clip to actual bounds + slice and dynamic depth or comparable ordering so unusual signed positions are not clipped by the legacy flattened shader constants. Keep old renderer unchanged for old 2D. Use real immutable prepared CPU data and actual D3D upload/render, camera-pan reuse and retained meshes across mutation.
## 7. Interfaces and data contracts
NEW public terrain APIs for building immutable surface mesh/packet (a shared pointer accepted by D3DScene::render over existing PreparedGeometry or equivalent) and constrained screen/world ray picking. Return region/epoch or caller-held snapshot plus stable voxel, signed face normal, adjacent placement/work cell when representable, consulted chunk stamps incl neighbor/missing for stale check. GPU resources owned by UI as existing; do not expose mutable resident pointers. NEW generic DDA local to receiver if no pin primitive: deterministic exact boundary negative coordinate convention, finite distance/step budget, zero components/no-hit/inside/start exactly on plane/edge/corner ties with declared single face, outside/unavailable distinct. Avoid epsilon that scales poorly across world; one documented voxel cell convention shared between meshing and picking. Bound face budget before/while preparing and refuse atomically without replacing old displayed geometry.
## 8. Dependencies and integration
Committed S02 actual region ready. No new World getter needed in this package; S18 will call terrain prepare and pick on the exact held published region after M02 owner. Expose next-point integration callback/document only if needed. Root will sign off and ff/merge existing S17 branch after publication of M01. Preceding user branches/MRs preserved.
## 9. Edge cases security and performance
Negative floors/near int extrema/partial chunk boundaries, clipping slice (below/above whole region), camera pan/zoom/viewport, equal edge/corner traversal, unknown and unloaded neighbor occlusion, triangles orientation/cull/depth, overflows at INT_MIN/INT_MAX adjacency, WARP device reset/upload of older immutable packet. Respect real outcome with WARP, no physical 1080p60 claims. Keep CMake test registrations independent of running interactive controls, use offscreen captures where possible.
## 10. Acceptance criteria
1. Build real signed two-page sample incl cutaway cave/passage, opendoor/closed, compare expected emitted faces and frozen old vs updated CPU buffers & distinct markers incl neighbor stamps. 2. Test/measure real offscreen WARP draws at controlled pixel samples and projected hit face/adjacent cell including slice and camera transforms, consistent crossing from both directions through x31/32 and negatives. 3. Ties/start-inside/zero direction/limits/unloaded/extremes explicit, refusal leaves displayed packet usable, camera-only no regeneration or upload when previous mesh valid. 4. Legacy viewer/frame tests pass, actual link and diagnostic output/issue links #12/#13 in docs. 5. Show bounded per world/page costs (prepared counts), no placeholder flat map geometry presented as voxel mode.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-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 new registered voxel scene target showing real offscreen WARP output and full ctest -V; coordinate interactive keyboard control tests with root before running. Write s17-voxel-*.log and git diff --check. Non-Windows host does not establish native hardware perf.
## 12. Constraints and stop conditions
Do not silently fallback to flat map for unsupported 3D or ray through unloaded cells. If dependency/API or D3D transform must change beyond local scope, notify root with targeted counterexample. No new upstream ticket without pin/duplicate research; user mandated genuine gaps, #12/#13 already cover this. No remote, children or claims of normal S18 integration until actual world is wired.
## 13. Authorization and decisions
User authorized all milestones and system branches. Planner/F1 accepted 3D render/pick and actual shader basis. Reversible drawing/Face data layout choices delegated, root accepts final integration and posts remote work.
## 14. Return format
Return S17-02 READY or PARTIAL, early stable public interface, verified real D3D pixel/pick behavior, touched paths, tests/limits/CPU-GPU retention and exact upcoming normal-viewer options.
+8
View File
@@ -13,6 +13,14 @@
5. Ввести выбор совместимых модулей при создании мира и сохранить их версии и контрольные суммы. Определить контракт явного состояния скрипта и атомарного применения его предложений в [S19](../systems/S19.md). Внутренний сценарий с двумя клиентами проверяет общую поверхность команд до публичного кооператива M09.
6. Для механизмов потоков, бинарной записи и тестов проверить существующие возможности VoidLibrary по [матрице](../void-library.md). Для отсутствующей возможности найти или создать issue в Void/Library и привязать к локальной реализации. Конкретный API выбирать по проверенной версии библиотеки.
## Приёмка реализации M01
В Windows x64 Release `4bac17d` под Wine 11 прошли все пять исполняемых наборов. Они охватили 182 теста ядра, 17 LAN, 15 клиентского сеанса, 6 проверок управления заказами и отдельный тест окна Direct3D. В последовательном режиме и на 2, 6 и 12 исполнителях два контрольных файла прежнего прототипа совпали побайтово. Потактный тест современной партии также сравнивает владельцев стеков, резервы, идентификаторы передач, квитанции и балансы. В 24 запусках с перестановкой завершений результат совпал с эталоном. [Испытания воспроизведения](../../../tests/replay_tests.cpp) · [Независимая проверка](../../agent-workflow/tasks/M01-V15.md)
Сохранение в пути, отмена заказа и возврат части груза прошли через рабочее меню и авторитетный диспетчер. Формат контрольной точки 3 восстанавливает имущество и незавершённые работы. Для 13 подлинных сохранений формата 2 проверены следующие 80 тактов на каждой из четырёх конфигураций исполнения. В отдельном опыте остановили гостевой приказ между чтением снимка и постановкой в очередь. После несовместимой отмены на хосте номер приказа гостя и состояние мира сохранились. При обратном порядке ранее принятый приказ завершился. Первоначальная и новая сборки сыграли по протоколу 11 в обеих ролях. [Фикстуры прежних сохранений](../../../tests/fixtures/custody_v14/README.md) · [Проверка имущества и кодека](../../agent-workflow/tasks/M01-V14.md) · [Условный допуск в VoidLibrary](https://git.faumaray.com/Void/Library/issues/16)
Два профиля рецепта кровати проверены через настоящие элементы управления в отдельных процессах. Камера работала во время задержанной записи и незаконченного такта. Воспроизведены загрузка предыдущего состояния и отказ при повреждённом файле. Эти результаты подтверждают программные условия выхода в M02. Нативный прогон Windows, физическая сеть и измерение частоты кадров на целевом ПК ещё предстоят. [Кадр и пользовательский интерфейс](../../agent-workflow/tasks/M01-V13.md) · [Ветка этапа](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6)
## Первый переход с текущего клиента
### Потактный эталон прототипа
+19
View File
@@ -22,9 +22,28 @@
## Проверки и выход
### Контракты первой реализации
Воксели имеют знаковые 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)
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
- Сценарий работает на Windows x64, а его составляющие доступны для строительства и снабжения в [M03](M03.md).
[Мастер-план](../../../PLAN.md) · [Паритет](../parity.md) · [VoidLibrary](../void-library.md)
## Проверенный каталог и навигация
В `1ca481b` каталог S02 публикует только целые правки. Из 256 исходных страниц при изменении одной клетки переиспользуются 255. Отдельная программа по очереди внесла 18 отказов выделения памяти и сравнила исходные данные после каждого отказа. В `2017e56` поиск S03 фиксирует также прочитанные недоступные страницы. При поиске рабочей позиции он различает замкнутую стеной область, недостающий проход и выход за край исследованного окна. Узкое окно в контрольном примере исчерпывает границу; расширение на две клетки находит доступ к материалу. [Каталог S02](../systems/S02.md) · [Маршруты S03](../systems/S03.md)
Обе системы с окончательной версией M01 проверены в `14987b2`. Сборка Windows x64 GCC 16.2 под Wine 11 прошла все пять наборов CTest, в том числе 14 проверок каталога и 14 навигации. В следующих изменениях M02 реальный житель получает задание на добычу, владеет извлечённым камнем до доставки, а игрок выбирает высоту и клетку в окне. Состояние рельефа и незаконченной работы получает версионное представление в сохранении. [Проверка исходного кода](../../agent-workflow/tasks/M02-V1.md) · [Контракты интеграции](../../agent-workflow/tasks/M02-F2.md)
В совместной сборке `129d7f2` видимая поверхность и выбор лучом используют одну проекцию с высотой `z`. При открытой двери пиксель соответствует более далёкому блоку, а недоступная страница перекрывает выбор. На 16 страницах генератора из 6 528 проверенных ячеек получились 1 998 граней. Запись старого кадра осталась доступной после отказа по бюджету. Проверены 15 случаев слоя и все шесть наборов CTest под Wine, включая чтение реальных пикселей WARP. [Визуализация S17](../systems/S17.md) · [Независимая проверка](../../agent-workflow/tasks/M02-V2.md)
+28
View File
@@ -10,6 +10,34 @@
## Данные и ответственность
### Исполняемая основа ограниченного региона
`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,6 +8,34 @@
В прототипе есть 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 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками.
+14
View File
@@ -20,6 +20,20 @@
Проверки: [production_identity_tests.cpp](../../../tests/production_identity_tests.cpp), [checkpoint_tests.cpp](../../../tests/checkpoint_tests.cpp), [replay_tests.cpp](../../../tests/replay_tests.cpp). Срез проверен Windows x64 GCC 16.2 через Wine: 9 проверок `--tag production-id`, полный verbose CTest — 115 core и 4 LAN. Replay сравнивает тело 14 на каждом такте в serial/2/6/12, включая сохранение в пути и дырку в ID. Существующие двоичные эталоны формата 13 совпали во всех четырёх режимах: 738386 байт (`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`) и 393857 байт (`05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`). Сохранён настоящий checkpoint схемы 1, полученный старым encoder до изменения. Нативный запуск Windows и MSVC не выполнялись. Общие поручения, самостоятельные ID резервов, передача владения и отмена груза остаются последующими срезами S04/S06.
## Реализованный срез S04-02: отмена и возобновление
Современная сессия принимает отдельные `CancelProductionPayload{ProductionId}` и `ResumeProductionPayload{ProductionId}`. Диспетчер проверяет доверенного игрока, мир, инкарнацию, город и номер запроса, затем передаёт действие в `World::cancel_production` / `resume_production`. Их физические эффекты принадлежат [S06](S06.md): адаптер команд не перемещает имущество самостоятельно. Современные действия доступны хозяину; гостю возвращается сохраняемый `Unauthorized`. Они не расширяют `CommandKind`, LAN 11 и прежнюю нумерацию `PlayerCommand`.
Принятый результат и отказ сохраняются в существующем журнале с исходными тактом и ревизией. Точный повтор возвращает прежнюю квитанцию даже после удаления заказа. Другой ID или замена отмены на возобновление под тем же номером возвращает `Conflict`; новый успешный эффект увеличивает ревизию ровно один раз. Используется существующий контракт [Void/Library #6](https://git.faumaray.com/Void/Library/issues/6) для журнала и [#8](https://git.faumaray.com/Void/Library/issues/8) для физического перехода. У закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792` нет готового игрового жизненного цикла заказа; условия замены журнала и передачи имущества сохраняются в этих задачах.
В обычном окне игры команда находится в **Работы → Управление заказами…**. После выбора клетки меню показывает явные «Отменить» / «Возобновить», название работы, постоянный ID и координаты. Несколько заказов одной клетки остаются отдельными действиями; страницы содержат до 16 заказов с переходами вперёд и назад. Отмена предлагается для незавершённых активных работ, возобновление — для приостановленных. Завершённые итоговые объекты сохраняют прежний отказ `Busy` от ядра. Перед отправкой повторно проверяются актуальный заказ, полная идентичность сессии, поколение представления, начавшаяся смена мира, сетевое соединение и выбранный режим. Открытый снимок удерживается до закрытия меню. Диалог из прежней колонии не может отправить действие в новую; гость LAN 11 не видит инструмент и не может вызвать его синтетической командой окна.
До квитанции интерфейс показывает ожидание подтверждения. Подтверждённая отмена сообщает о сохранении установленных частей и последующем возврате груза; возобновление сообщает о продолжении работы. У возвращающего материалы жителя видны действительный состав сумки и причина ожидания: отсутствие доступного склада, недостаток места, занятый склад либо предел учёта. Прежние `DemolishObject` / `MoveObject` сохраняют отказы при занятом источнике, складе и объекте.
Проверки с реальным ядром: [production_commands_tests.cpp](../../../tests/production_commands_tests.cpp) — повтор принятых/отклонённых результатов, конфликты вариантов и ID, границы контекста и прав, отмена до получения/в пути/на площадке, ожидание полного склада и возврат всех материалов, продолжение частичной кровати и установленного станка, публикация runtime. [production_controls_tests.cpp](../../../tests/production_controls_tests.cpp) создаёт настоящее Win32-окно с Direct3D, выбирает клетку обычными сообщениями мыши, проходит меню клавиатурным вводом через `WM_TIMER`, проверяет квитанции обоих действий, выбор точного ID и доступ ко всем 35 заказам на одной клетке, смену мира во время меню, подключённого гостя LAN 11 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных.
Полный `ctest -V` для Windows x64 GCC 16.2 под Wine 11 выполнил 160 тестов ядра, 9 LAN, 14 клиентских сеансов и 6 проверок управления в настоящем окне. В одном предыдущем прогоне тест восстановления после сбоя получил временный отказ при попытке синхронизации. Ветка S18 добавила ограниченное ожидание допуска. После этой правки клиентский набор прошёл 24 раза подряд. На физической Windows и под MSVC эти проверки ещё предстоят.
## Данные и владение
| Новый объект | Ответственность |
+16
View File
@@ -51,6 +51,22 @@
Совместимый протокол 11 допускает точный встроенный набор правил и активную колонию 32×32. После смены инкарнации соединение проходит вход заново. Принятая операция слота сохраняется при разрыве TCP. Новое подключение ждёт её завершения, затем получает актуальные номера команд. Ответ прежнего подключения отбрасывается. Обычный отказ игры сохраняет старый сетевой номер, а номер конверта владельца продвигается.
Проверка представимости фактического имущества выполняется до приёма соединения, перед каждым разобранным сообщением и перед отправкой, включая продолжение ранее поставленного снимка или квитанции. `World::legacy_representable()` проверяет игровой контракт без пробной сериализации. Если отменённый груз или приостановленная площадка не имеют точного представления в формате 13, адаптер закрывает гостя и очищает его буферы. Слушатель, современный владелец и принятая им работа сохраняются; готовая квитанция прежнего подключения не отправляется следующему гостю. При работе с фоновым владельцем каждое сообщение и отправка сверяют свежую публикацию и инкарнацию. Прежний `poll(World&)` применяет ту же проверку представимости.
Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md)
Проверка представимости снимка сама по себе не разрешает позднейший допуск команды. `SimulationRuntime::try_submit_if_current` сравнивает удержанную проверенную публикацию с текущей и проверяет рабочее состояние под тем же mutex, который защищает публикацию и постановку в очередь. Пустая ссылка получает `InvalidRequest`, нерабочий владелец — `Closed`, сменившаяся публикация — `StaleSnapshot`; конкуренция за mutex и заполненная очередь возвращают `Busy`. Сравнение публикаций предшествует проверке вместимости очереди. Внутри блокировки нет сканирования мира или сериализации. Обычный `try_submit` сохраняет прежний контракт. Уже допущенные операции не отзываются последующей публикацией.
Адаптер передаёт точную проверенную ссылку. При `StaleSnapshot` или `Busy` он заново проверяет текущую публикацию: несовместимое имущество, отказ владельца или другая инкарнация закрывают гостя и очищают буферы. Совместимое новое состояние возвращает честный `Busy` с актуальным прежним номером команды, чтобы гость мог повторить намерение. Цикла повторных допусков в сетевом опросе нет. Необязательный диагностический `LanSessionOptions::before_command_admission` позволяет остановить поток опроса ровно между проверкой и допуском, не удерживая блокировку владельца. [Контракт S16-04](../../agent-workflow/tasks/S16-04.md)
Общий контракт условного допуска отслеживается отдельно от публикации и журнала результатов в [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16). Закреплённый `FuturePool::try_submit` проверяет лимит и остановку исполнителя, но не игровую публикацию. Условие замены локального допуска — сохранить точное сравнение удержанного снимка и постановку в ограниченную очередь одной критической секцией и повторить управляемую гонку: после проверки представимого S реальный владелец публикует несовместимое S+1 в той же инкарнации, затем гость пытается войти в очередь. До исправления регрессия реально продвинула номер запроса гостя с 1 до 2. Она также проверяет совместимую новую публикацию с повтором прежнего сетевого номера, отсутствие эффектов отказа, завершение ранее допущенной работы и отказ после сбоя владельца.
Проверка S16-04 на базе `c183de1`: Windows x64 Release GCC 16.2 под Wine 11, 4/4 новых `lan-admission`; полный CTest — 168/168 core, 17/17 LAN, 15/15 клиента и 6/6 управления заказами. После исправления управляемая гонка сохраняет точную публикацию отмены, прежние сетевой номер и номер запроса гостя, профессию жителя и отсутствие квитанции в журнале. Старый скомпилированный клиент и заново собранный адаптер успешно обменялись приказами в обеих ролях. `git diff --check` прошёл. Нативная Windows, MSVC и физические машины этим прогоном не проверялись.
Для этого адаптера повторно проверены публичный `Void/Net/Socket.hpp`, Windows-ветка `src/Net/Socket.cpp` и `tests/standalone/Net/Socket.cpp` закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792`: UDP не реализован для Windows и не предоставляет игровую проверку представимости. Существующий TCP-транспорт остаётся прежним. Имущество и условие отказа принадлежат игровому адаптеру поверх операций [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8); новое универсальное сетевое средство не вводится.
Проверка S16-03 на интеграционной базе `5c309b2`: Windows x64 Release GCC 16.2 под Wine 11, 13/13 LAN и 15/15 клиента. Четыре новых LAN-сценария проверяют настоящий отменённый смешанный груз при полном складе, отказ входа, сохранение современного мира, завершение ранее допущенного приказа и отсечение следующего приказа в той же инкарнации, а также удаление недосланного снимка размером больше 64 КиБ на обоих путях хоста. Отдельно проходят 3/3 `wire` и 9/9 `lan-owner`. Старый скомпилированный клиент и новый адаптер обменялись приказами в обеих ролях. Оба старых корпуса формата 13 (738 386 и 393 857 байтов) совпали полностью на 1/2/6/12 исполнителях. Полный CTest этой базы выявил два отказа `production-command` и четыре отказа `production-controls` в параллельном срезе S04; их исправление и повторная общая проверка относятся к интеграции. Нативная Windows, MSVC и две физические машины этим прогоном не проверялись.
Пять проверок `--tag lan-owner` под Wine покрывают квитанции, заполнение очереди, совмещённые пакеты, переподключение при задержанной публикации, откат с незавершённой командой и отказ при несовместимых правилах. Отдельный двоичный клиент прототипа подтвердил обмен в обоих направлениях с новым хостом и гостем. Проверка физической Windows и двух машин остаётся частью сетевой приёмки. [Сценарии](../../../tests/lan_tests.cpp)
Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6)
+50 -3
View File
@@ -1,10 +1,57 @@
# S17. D3D11-рендеринг, камера и визуальное состояние
Статус — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — S17-W01 и ограниченный объёмный API S17-02 реализованы и проверены в Windows x64/Wine, ожидают независимой приёмки. Подключение объёмного API к обычному игровому кадру выполняется отдельной задачей S18/World. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
`D3DScene::render` принимает `const World&`, заново собирает геометрию карты, ресурсов, построек и жителей, загружает её и вызывает D3D11. `SceneView` хранит положение камеры, выбор и предпросмотр. Вызов происходит из `WM_PAINT`, а симуляция — из `WM_TIMER` того же окна. Основой нового клиента остаётся имеющийся Win32/D3D11-путь. [Интерфейс сцены](../../../app/d3d_scene_win32.hpp) · [Текущий рендер](../../../app/d3d_scene_win32.cpp)
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 остаются клиентскими данными.
## Объёмная сцена S17-02
[`prepare_voxel_scene`](../../../app/voxel_scene.hpp) принимает настоящий `VoxelRegion` S02, UUID экземпляра сессии, конечный объём показа внутри региона и включительный верхний слой `slice`. Результат совместно владеет неизменяемым снимком страниц, открытыми гранями и отсортированными `ChunkStamp` всех прочитанных страниц, включая отсутствующие и соседние. `current(region, session)` проверяет описание региона, экземпляр сессии и прочитанные ревизии. Изменение непрочитанной страницы оставляет геометрию пригодной. При замене мира вызывающая сторона меняет UUID.
Клетка занимает `[x,x+1) × [y,y+1) × [z,z+1)`. Почва, камень и закрытая дверь образуют непрозрачный куб. Воздух и открытая дверь дают видимый проход. Внутренние грани смежных занятых клеток не выпускаются, в том числе через границы страниц −32, 0 и 32. Отсечение объёмом показа и слоем открывает соответствующие граничные поверхности. Отсутствующие страницы показываются непрозрачными серыми гранями, а выбор останавливается с `Unavailable`, поэтому загруженный объект за неизвестной областью нельзя выбрать насквозь.
`D3DScene::prepare_voxels(scene)` создаёт настоящий CPU-пакет `PreparedGeometry`. `render(packet, VoxelCamera, capture)` загружает его в D3D11 и рисует треугольники. Координаты вершин отсчитываются от нижнего угла объёма показа, что сохраняет точность клеток рядом с `INT32_MIN` и `INT32_MAX`. Позиция этого угла на экране задаётся `origin_x/y`. Проекция сохраняет базис `(x-y)*halfTile.x, (x+y)*halfTile.y-z*16`, масштаб и смещение камеры. Глубина нормируется по объёму сцены. Прежний плоский пакет сохраняет прежние коэффициенты глубины `.96/.009`.
`pick_voxel_screen` использует тот же удержанный `VoxelScene` и ту же `VoxelCamera`, что и показанный пакет. Результат содержит регион, UUID сессии, клетку, одну нормаль грани, материал, расстояние и прочитанные ревизии. Соседняя клетка возвращается только при представимых координатах и может оказаться за границами региона, поэтому её допустимость для действия проверяет симуляция. `trace_voxels` также принимает произвольный конечный луч. Нулевое направление и нечисловые входы отвергаются. Начало внутри занятой клетки даёт `Inside` без грани. На точной плоскости знак направления выбирает следующую клетку, нулевой компонент оставляет луч в клетке, владеющей полуоткрытой границей. При одновременном переходе по нескольким осям меняются все эти координаты, а нормаль выбирается в порядке X, Y, Z. Клетки, которых луч касается только ребром, пропускаются. Масштабирование направления степенью двойки сохраняет точные отношения компонентов, включая проверенный случай 1:3.
По умолчанию подготовка ограничена 2 097 152 просматриваемыми клетками, 262 144 гранями, 1 024 прочитанными страницами, 4 096 клетками по каждой оси и 64 МиБ для граней, ёмкости каталога ревизий и развёрнутых CPU-вершин. Независимый предел оси 65 536 сохраняет представимость локальных координат даже при повышении бюджета. Грани сначала подсчитываются и проверяются, затем заполняется выделенный массив. Луч ограничен 16 384 посещёнными клетками и 1 024 страницами. Ошибка лимита или выделения памяти возвращается до публикации замены. Источник страниц, старые удержанные пакеты, накладные расходы аллокатора и GPU-память учитываются вызывающей стороной отдельно. Один квадрат разворачивается в шесть вершин по 24 байта.
Камера не входит в CPU-геометрию. Сдвиг и масштаб используют тот же пакет без повторной загрузки. Возврат к удержанному старому пакету и восстановление устройства загружают его вновь. Рост GPU-буфера сначала создаёт и заполняет замену, сохраняя прежний буфер при отказе. Пустой срез рисует только фон. Асинхронный диспетчер перестроения отдельных чанков, вращение камеры, обычное управление срезом через S18 и физический профиль производительности остаются последующими работами.
### Проверка S17-02
[`settlement_voxel_scene_tests`](../../../tests/voxel_scene_tests.cpp) содержит 15 проверок CPU-контрактов и настоящего offscreen D3D11/WARP. Пиксели известных верхних и боковых граней сверяются с результатом выбора, включая масштаб, сдвиг, срез крыши, открытый дверной проём, пропуск, лимит, неизвестную страницу и крайние знаковые координаты. Отдельная сцена использует генератор S02 на 16 страницах и 6 528 клетках, выдаёт 1 998 граней и 11 988 вершин. Отказ меньшего бюджета сохраняет отображаемый пакет и счётчик GPU-загрузок. Проверки удерживают старую геометрию после изменения материалов и пересоздания устройства.
Проверка из изолированного `s17-voxel` на базе `13dc673`, GCC 16.2.0, Windows x64/Wine 11.0, Release и закреплённой VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792` выполняется командами `cmake --build /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build --parallel 6`, `flock /tmp/stoneheart-milestones.xprJ2SVp/interactive-test.lock ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build -V` и `git diff --check`. Конфигурация использует согласованные `env.sh` и cross-toolchain из `/tmp/stoneheart-verify.KoZwE4o8`, `BUILD_TESTING=ON`. Журналы находятся в `/tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-*.log`. Этот прогон не устанавливает физическую производительность 1080p60 или поведение драйвера на нативной Windows.
Наблюдаемый итог 2026-12-03 — сборка без предупреждений, 6/6 CTest за 17,60 с. Прошли 196 core, 17 LAN, 15 viewer session, 6 production controls, 15 voxel scene и отдельный настоящий frame smoke. Полный журнал — `s17-voxel-final-ctest.log`, сборка — `s17-voxel-final-build.log`. Native Windows, физическая GPU и искусственное исчерпание памяти драйвера не проверялись.
Публичные `Void::Math::Vec3` и `Void::Numeric::checked_*` используются из закреплённой версии. Локальный ограниченный 3D-обход связан с [Void/Library #12](https://git.faumaray.com/Void/Library/issues/12), каталог прочитанных ревизий — с [#13](https://git.faumaray.com/Void/Library/issues/13). Замена библиотечным API требует сохранить проверенные правила границ, неопределённости, лимитов, UUID сессии и инвалидирования соседних страниц. Форма клеток, материалы, дверной проём и включительный срез остаются игровыми правилами.
## Границы данных и потоков
@@ -16,7 +63,7 @@
## Последовательность реализации
1. **S17-W01, M01.** Ввести публикацию снимков и самостоятельный цикл кадров. Перенести обращения к миру из обработчиков отрисовки в подготовку снимка. Проверить работу камеры при искусственно долгом такте.
1. **S17-W01, M01 — реализовано, ожидает приёмки.** Неизменяемый пакет, отдельный таймер кадра и проверки камеры при удержанном рабочем/файловом вводе-выводе описаны выше.
2. **S17-W02, M02.** Построить геометрию изменившихся чанков и обработку общих граней. Добавить отсечение невидимых областей и приоритет ближних участков. В тесте редактировать грань между двумя чанками и проверять отсутствие щели и дублирующей поверхности.
3. **S17-W03, M02–M03.** Добавить вращение, масштабирование вокруг указателя, выбор по лучу и срез высоты. Выбор возвращает регион, клетку, грань и ревизию, по которым интерфейс формирует намерение. При подтверждении симуляция проверяет действие на актуальной геометрии.
4. **S17-W04, M03–M07.** Разделить статическую геометрию, жителей, предметы и эффекты. Интерполировать визуальные позы между подтверждёнными тактами. Подключить оригинальные модели, анимацию, освещение, время суток и читаемую индикацию работы.
+6
View File
@@ -49,6 +49,10 @@
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
## Публикация мира и приём команд
Клиент протокола 11 проверяет, можно ли передать ему текущее состояние. Пока он готовит приказ, владелец может опубликовать несовместимое состояние в той же партии. Проверка актуальности снимка и помещение приказа в очередь должны выполняться под одной блокировкой владельца. Тест задерживает клиента после получения старого снимка, отменяет заказ на хосте и проверяет, что номер гостевого приказа и состояние колонии сохранились. При обратном порядке уже принятый приказ должен завершиться. Публичный `FuturePool::try_submit` проверяет ёмкость своего исполнителя. Предложение связать допуск с публикацией передано сопровождающим. [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16) · [Владелец симуляции](../../engine/src/simulation_runtime.cpp) · [Сетевой адаптер](../../app/lan_session_win32.cpp)
## Подготовка воксельного мира M02
Для проверки порядка завершения реальных вычислений [S21](systems/S21.md) использует работающий `FuturePool`. У `Testing::DeterministicRun` есть очередь управляемых тестовых действий. Для потактного теста игры требуется отдельно зарегистрировать возврат конкретной функции исполнителя, переставить две такие операции и проверить тот же результат мира на 2/6/12 потоках и при заполненной очереди. Предложение относится к тестовому адаптеру реальных задач. [Void/Library #15](https://git.faumaray.com/Void/Library/issues/15) · [Адаптер исполнения игры](../../engine/include/settlement/core/worker_pool.hpp)
@@ -64,3 +68,5 @@
| [Ограниченные разреженные объёмы и атомарные правки страниц, #14](https://git.faumaray.com/Void/Library/issues/14) | [Каталог чанков S02](systems/S02.md). Проверить изменение двух чанков одной командой, точный отказ при устаревшей ревизии либо исчерпанном бюджете и воспроизводимый порядок дельт. Генератор, материалы и такт активации остаются в игре. |
[Мастер-план](../../PLAN.md)
В M02 вызов `Void::Async::FuturePool::try_submit` допускает ограниченное число работ и оставляет вызывающей стороне функцию при отказе. Закреплённая версия позволяет готовить независимые страницы и сверять результат по сохранённому идентификатору запроса. Для общего такта игра собирает все необходимые страницы и публикует каталог один раз. Готовые и устаревшие результаты также входят в бюджет игры. В существующих задачах описаны чтение ограниченного файла Windows, замена публикации и восстановление набора прочитанных ревизий. [Исследование M02](../agent-workflow/tasks/M02-R2.md) · [Исходники FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/include/Void/Async/FuturePool.hpp) · [Windows-файл](https://git.faumaray.com/Void/Library/issues/9) · [Публикации](https://git.faumaray.com/Void/Library/issues/5) · [Ревизии](https://git.faumaray.com/Void/Library/issues/13)
@@ -44,7 +44,18 @@ struct LegacyCabinPayload {
bool operator==(const LegacyCabinPayload&) const = default;
};
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload>;
struct CancelProductionPayload {
ProductionId production = 0;
bool operator==(const CancelProductionPayload&) const = default;
};
struct ResumeProductionPayload {
ProductionId production = 0;
bool operator==(const ResumeProductionPayload&) const = default;
};
using SessionPayload = std::variant<CommandPayload, LegacyCabinPayload,
CancelProductionPayload, ResumeProductionPayload>;
struct CommandEnvelope {
std::uint32_t version = command_envelope_version;
@@ -15,7 +15,7 @@
namespace settlement {
enum class RuntimeState { Running, Faulted, Closed };
enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted };
enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted, StaleSnapshot };
enum class RuntimeOutcome { Completed, Faulted, Closed, Superseded, InvalidCandidate };
enum class RuntimePhase { BeforeTick, BeforeCapture, BeforeInstallCapture };
@@ -77,6 +77,14 @@ public:
[[nodiscard]] std::optional<DispatchReceipt> lookup(
TrustedClient client, const CommandEnvelope& command) const;
[[nodiscard]] RuntimeSubmission try_submit(TrustedClient client, const CommandEnvelope& command);
// Atomically admit against the exact retained publication inspected by the
// caller. Null returns InvalidRequest; a nonrunning owner returns Closed;
// a different publication returns StaleSnapshot, before checking capacity.
// Mutex contention or full capacity returns Busy. Refusals have no future.
// Later publications never revoke work that was already admitted.
[[nodiscard]] RuntimeSubmission try_submit_if_current(
TrustedClient client, const CommandEnvelope& command,
const std::shared_ptr<const PublishedSnapshot>& expected);
[[nodiscard]] RuntimeSubmission set_ticking(bool enabled);
// Fences earlier queued operations and all eligible clock debt through the
// admission time. Advancing a ManualClock should be followed by this or notify_clock().
@@ -0,0 +1,84 @@
#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
@@ -0,0 +1,168 @@
#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
+6
View File
@@ -74,6 +74,12 @@ CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const
}
if (client.player != colony_host) return CommandStatus::Unauthorized;
if (const auto* payload = std::get_if<CancelProductionPayload>(&command.payload)) {
return world.cancel_production(payload->production);
}
if (const auto* payload = std::get_if<ResumeProductionPayload>(&command.payload)) {
return world.resume_production(payload->production);
}
if (world.scenario_active()) return CommandStatus::Unavailable;
const auto& payload = std::get<LegacyCabinPayload>(command.payload);
try {
+17 -1
View File
@@ -107,11 +107,17 @@ struct SimulationRuntime::Impl {
return published->revision + 1;
}
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = nullptr) {
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = nullptr,
const std::shared_ptr<const PublishedSnapshot>* expected = nullptr) {
auto completion = work->promise.get_future();
std::unique_lock lock(mutex, std::try_to_lock);
if (!lock.owns_lock()) return {RuntimeAdmission::Busy, {}};
if (stopping.load()) return {RuntimeAdmission::Closed, {}};
if (expected) {
if (!*expected) return {RuntimeAdmission::InvalidRequest, {}};
if (state != RuntimeState::Running) return {RuntimeAdmission::Closed, {}};
if (published != *expected) return {RuntimeAdmission::StaleSnapshot, {}};
}
if (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}};
queue.push_back(std::move(work));
if (candidate) {
@@ -333,6 +339,16 @@ RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const Comm
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::try_submit_if_current(
TrustedClient client, const CommandEnvelope& command,
const std::shared_ptr<const PublishedSnapshot>& expected) {
if (!expected) return {RuntimeAdmission::InvalidRequest, {}};
auto work = std::make_unique<Impl::Work>(Impl::Kind::Command);
work->client = client;
work->command = command;
return impl_->enqueue(std::move(work), nullptr, &expected);
}
RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Ticking);
work->enabled = enabled;
+306
View File
@@ -0,0 +1,306 @@
#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
@@ -0,0 +1,383 @@
#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
+368 -4
View File
@@ -48,6 +48,29 @@ WorldCheckpoint colony_checkpoint() {
return {make_first_colony(2), *identity, 1, std::move(*rules)};
}
std::unique_ptr<World> mixed_delivery() {
auto world = std::make_unique<World>(43, 32, 32, 2);
const auto store = world->add_storage({3, 3}, 5);
world->stock_storage(store, ItemType::Plank, 3);
world->stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world->spawn_agent({1, 3}));
world->start_scenario({6, 6});
world->queue_production({14, 3}, RecipeId::BuildCabin);
for (int tick = 0; tick < 100 && world->agents().front().inventory.empty(); ++tick) world->step();
const auto& cargo = world->agents().front().inventory;
require(cargo.item_count(ItemType::Plank) == 3 && cargo.item_count(ItemType::StoneBlock) == 2);
// Keep canceled cargo blocked at its real owner through later steps.
world->stock_storage(store, ItemType::Wood, 5);
require(world->legacy_representable());
return world;
}
void cancel_mixed_delivery(World& world) {
require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted);
require(!world.legacy_representable());
world.validate_custody();
}
template<class Pump, class Condition>
void pump_until(Pump pump, Condition condition, const char* message) {
const auto deadline = std::chrono::steady_clock::now() + 3s;
@@ -66,8 +89,7 @@ struct CaptureGate {
bool entered = false;
bool released = false;
void capture(RuntimePhase phase) {
if (phase != RuntimePhase::BeforeCapture) return;
void block() {
std::unique_lock lock(mutex);
if (!armed) return;
entered = true;
@@ -77,6 +99,10 @@ struct CaptureGate {
}
}
void capture(RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) block();
}
void arm() { std::lock_guard lock(mutex); armed = true; }
bool waiting() { std::lock_guard lock(mutex); return entered; }
void release() {
@@ -115,8 +141,9 @@ struct RawGuest {
RawGuest(const RawGuest&) = delete;
RawGuest& operator=(const RawGuest&) = delete;
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value});
void command(std::uint64_t sequence, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0,
AgentId resident = 0) {
const auto bytes = lan_wire::encode_command({2, sequence, kind, cell, value, {}, resident});
lan_wire::append_frame(output, lan_wire::Message::Command, std::string_view(bytes));
}
@@ -163,6 +190,14 @@ struct LanTests : Void::Testing::Suite<LanTests> {
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_retains_slot_work_across_reconnect();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_reauthenticates_after_pending_rollback();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_host_rejects_nondefault_rules_and_faults();
[[= Void::Testing::tag("lan-owner")]] Test test_legacy_custody_refuses_handshake_and_preserves_modern_owner();
[[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work();
[[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_discards_queued_snapshot_before_admission();
[[= Void::Testing::tag("lan-admission")]] Test test_guest_admission_cannot_cross_incompatible_publication();
[[= Void::Testing::tag("lan-admission")]] Test test_guest_retries_same_sequence_after_compatible_publication();
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_preserves_accepted_work_and_reports_refusals();
[[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_rejects_faulted_owner_with_retained_publication();
};
Test LanTests::test_protocol_11_fixed_messages() {
@@ -617,4 +652,333 @@ Test LanTests::test_runtime_host_rejects_nondefault_rules_and_faults() {
require(!guest.take_result());
}
Test LanTests::test_legacy_custody_refuses_handshake_and_preserves_modern_owner() {
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
cancel_mixed_delivery(*initial.world);
const auto encoded = encode_checkpoint(*initial.world, initial.world_id, initial.city, initial.rules);
require(encoded.has_value());
auto packages = builtin_rule_packages();
require(packages.has_value());
auto restored = decode_checkpoint(*encoded, *packages, 2);
require(restored.has_value() && !restored->world->legacy_representable());
SimulationRuntime runtime(std::move(*restored), {.ticking = false});
LanSession host, guest;
host.host(0, true);
const auto port = host.port();
guest.join("127.0.0.1", host.join_code(), port);
for (int attempt = 0; attempt < 20; ++attempt) {
host.poll_host(runtime);
require(!guest.poll_guest());
}
require(host.state() == LanState::Hosting && host.port() == port && !host.detail().empty());
require(guest.state() != LanState::GuestConnected && !guest.take_result());
const auto before = runtime.latest();
const auto& id = before->identity;
auto local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
require(runtime.view().state == RuntimeState::Running && runtime.latest()->world->paused());
const auto current = runtime.latest();
auto saved = encode_checkpoint(*current->world, id.world, id.city, *current->rules);
require(saved.has_value() && decode_checkpoint(*saved, *packages, 2).has_value());
require(current->next_requests[1] == before->next_requests[1]);
}
Test LanTests::test_standalone_custody_discards_queued_snapshot_and_command() {
auto world = mixed_delivery();
// A real historical snapshot larger than one 64 KiB flush leaves output
// queued; gating only a subsequent send_snapshot call misses this case.
for (int job = 0; job < 4096; ++job) static_cast<void>(world->add_job({20, 20}, 1));
std::ostringstream bytes(std::ios::binary);
world->write_save(bytes);
require(bytes.view().size() > 64 * 1024);
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
guest.poll();
pump_until([&] { static_cast<void>(host.poll(*world)); },
[&] { return host.state() == LanState::HostConnected; }, "Standalone guest did not authenticate.");
guest.poll();
require(!guest.input.empty() && !guest.snapshot);
const auto partial = guest.input.size();
const auto profession = world->agents().front().profession;
cancel_mixed_delivery(*world);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
world->agents().front().id);
guest.poll();
pump_until([&] { static_cast<void>(host.poll(*world)); guest.poll(); },
[&] { return guest.closed; }, "Unsupported standalone peer stayed connected.");
require(host.state() == LanState::Hosting && !host.detail().empty());
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
require(world->next_command_sequence(2) == 1 && world->agents().front().profession == profession);
const auto tick = world->tick();
world->step();
require(world->tick() == tick + 1);
world->validate_custody();
auto compatible = mixed_delivery();
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { static_cast<void>(host.poll(*compatible)); next.poll(); };
pump_until(pump, [&] { return next.snapshot != nullptr; }, "Representable counterpart could not join.");
next.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner),
compatible->agents().front().id);
pump_until(pump, [&] { return !next.receipts.empty(); }, "Representable counterpart command did not settle.");
require(next.receipts.front().status == CommandStatus::Accepted);
}
Test LanTests::test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work() {
CaptureGate gate;
RuntimeOptions options{.ticking = false};
options.observer = [&](RuntimePhase phase) { gate.capture(phase); };
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
SimulationRuntime runtime(std::move(initial), options);
auto release = Void::Scope::on_exit([&] { gate.release(); });
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Custody guest did not join.");
const auto before = runtime.latest();
const auto id = before->identity;
const CommandPayload accepted{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
gate.arm();
guest.command(1, accepted.kind, {}, accepted.value, resident);
pump_until(pump, [&] { return gate.waiting(); }, "Guest work did not reach blocked capture.");
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CancelProductionPayload{production}});
require(canceled.admission == RuntimeAdmission::Accepted);
// This later wire intent is already in TCP when cancellation publishes.
guest.command(2, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Builder), resident);
guest.poll();
gate.release();
require(canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
pump_until(pump, [&] { return guest.closed; }, "Incompatible runtime guest stayed connected.");
require(host.state() == LanState::Hosting && runtime.view().state == RuntimeState::Running);
require(guest.receipts.empty());
const auto current = runtime.latest();
require(current->next_requests[1] == 2 && current->world->next_command_sequence(2) == 2);
require(current->world->agents().front().profession == Profession::Miner);
const auto retained = runtime.lookup({2}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[1], accepted});
require(retained && retained->status == DispatchStatus::Completed && retained->command_status == CommandStatus::Accepted);
require(encode_checkpoint(*current->world, id.world, id.city, *current->rules).has_value());
// A later compatible incarnation can reconnect; neither the retained work
// nor its old socket's reply leaks into the new connection.
auto ticket = runtime.begin_load();
require(ticket.has_value());
auto replacement = colony_checkpoint();
auto installed = runtime.try_install(*ticket, replacement);
require(installed.admission == RuntimeAdmission::Accepted && installed.completion.wait_for(3s) == std::future_status::ready);
require(installed.completion.get().outcome == RuntimeOutcome::Completed);
RawGuest next(host.port(), std::stoull(host.join_code(), nullptr, 16));
pump_until([&] { host.poll_host(runtime); next.poll(); },
[&] { return next.snapshot != nullptr; }, "Guest could not reconnect after custody cutoff.");
require(next.receipts.empty() && next.snapshot->next_command_sequence(2) == 1);
}
Test LanTests::test_runtime_custody_discards_queued_snapshot_before_admission() {
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
for (int job = 0; job < 4096; ++job) static_cast<void>(initial.world->add_job({20, 20}, 1));
SimulationRuntime runtime(std::move(initial), {.ticking = false});
LanSession host;
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
guest.poll();
pump_until([&] { host.poll_host(runtime); }, [&] { return host.state() == LanState::HostConnected; },
"Queued-snapshot guest did not authenticate.");
guest.poll();
require(!guest.input.empty() && !guest.snapshot);
const auto partial = guest.input.size();
const auto before = runtime.latest();
const auto id = before->identity;
auto canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
before->next_requests[0], CancelProductionPayload{production}});
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
guest.poll();
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
"Guest receiving queued snapshot was not dropped.");
require(runtime.latest()->identity.session == id.session && !runtime.latest()->world->legacy_representable());
require(runtime.view().state == RuntimeState::Running && host.state() == LanState::Hosting);
require(guest.input.size() == partial && !guest.snapshot && guest.receipts.empty());
require(runtime.latest()->next_requests[1] == 1 && runtime.latest()->world->next_command_sequence(2) == 1);
}
Test LanTests::test_guest_admission_cannot_cross_incompatible_publication() {
CaptureGate admission;
auto initial = colony_checkpoint();
initial.world = mixed_delivery();
const auto production = initial.world->production_orders().front().id;
const auto resident = initial.world->agents().front().id;
SimulationRuntime runtime(std::move(initial), {.ticking = false});
LanSession host({.before_command_admission = [&] { admission.block(); }});
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.snapshot != nullptr; },
"Admission-race guest did not join.");
const auto checked = runtime.latest();
const auto id = checked->identity;
const auto old_profession = checked->world->agents().front().profession;
const CommandPayload intent{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, resident};
const CommandEnvelope envelope{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[1], intent};
admission.arm();
guest.command(1, intent.kind, {}, intent.value, resident);
guest.poll();
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
auto release = Void::Scope::on_exit([&] { admission.release(); });
pump_until([] {}, [&] { return admission.waiting(); }, "Guest did not reach pre-admission barrier.");
// This is a genuine owner publication between the adapter's compatibility
// check of S and admission of the remote command, without an epoch change.
RuntimeSubmission canceled{RuntimeAdmission::Busy, {}};
pump_until([&] {
canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CancelProductionPayload{production}});
}, [&] { return canceled.admission != RuntimeAdmission::Busy; }, "Cancel could not obtain owner admission.");
require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready);
require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto cutoff = runtime.latest();
require(cutoff != checked && cutoff->identity.session == id.session && !cutoff->world->legacy_representable());
admission.release();
require(polling.wait_for(3s) == std::future_status::ready);
polling.get();
RuntimeSubmission fence{RuntimeAdmission::Busy, {}};
pump_until([&] { fence = runtime.synchronize(); }, [&] { return fence.admission != RuntimeAdmission::Busy; },
"Owner fence could not be admitted.");
require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(3s) == std::future_status::ready);
require(fence.completion.get().outcome == RuntimeOutcome::Completed);
const auto after = runtime.latest();
const auto evidence = "Guest command crossed incompatible publication: next_request=" +
std::to_string(after->next_requests[1]);
if (after->next_requests[1] != checked->next_requests[1]) throw std::runtime_error(evidence);
require(after->world->next_command_sequence(2) == checked->world->next_command_sequence(2));
require(after->world->agents().front().profession == old_profession && !runtime.lookup({2}, envelope));
require(after == cutoff && runtime.view().state == RuntimeState::Running);
pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; },
"Race-cutoff peer was not disconnected.");
require(host.state() == LanState::Hosting && guest.receipts.empty());
require(encode_checkpoint(*after->world, id.world, id.city, *after->rules).has_value());
}
Test LanTests::test_guest_retries_same_sequence_after_compatible_publication() {
CaptureGate admission;
SimulationRuntime runtime(colony_checkpoint(), {.ticking = false});
LanSession host({.before_command_admission = [&] { admission.block(); }});
host.host(0, true);
RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16));
const auto pump = [&] { host.poll_host(runtime); guest.poll(); };
pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Compatible-race guest did not join.");
const auto checked = runtime.latest();
const auto id = checked->identity;
const auto resident = checked->world->agents().back().id;
admission.arm();
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
guest.poll();
auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); });
auto release = Void::Scope::on_exit([&] { admission.release(); });
pump_until([] {}, [&] { return admission.waiting(); }, "Compatible command did not reach admission barrier.");
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
pump_until([&] {
local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}});
}, [&] { return local.admission != RuntimeAdmission::Busy; }, "Compatible local change could not be admitted.");
require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready);
require(local.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto changed = runtime.latest();
require(changed != checked && changed->identity.session == id.session && changed->world->legacy_representable());
admission.release();
require(polling.wait_for(3s) == std::future_status::ready);
polling.get();
pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Compatible revision did not report retryable Busy.");
require(guest.receipts.front().status == CommandStatus::Busy && guest.receipts.front().next_sequence == 1);
require(runtime.latest() == changed && changed->next_requests[1] == 1 && host.state() == LanState::HostConnected);
guest.command(1, CommandKind::AssignProfession, {}, static_cast<std::uint8_t>(Profession::Miner), resident);
pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Same-sequence guest retry did not settle.");
require(guest.receipts.back().status == CommandStatus::Accepted && guest.receipts.back().next_sequence == 2);
require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->agents().back().profession == Profession::Miner);
}
Test LanTests::test_conditional_admission_preserves_accepted_work_and_reports_refusals() {
CaptureGate owner;
RuntimeOptions options{.capacity = 2, .ticking = false};
options.observer = [&](RuntimePhase phase) { owner.capture(phase); };
SimulationRuntime runtime(colony_checkpoint(), options);
auto release = Void::Scope::on_exit([&] { owner.release(); });
const auto checked = runtime.latest();
const auto id = checked->identity;
const CommandEnvelope local_command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
const CommandEnvelope guest_command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[1], CommandPayload{CommandKind::AssignProfession, {},
static_cast<std::uint8_t>(Profession::Miner), {}, checked->world->agents().back().id}};
const auto invalid = runtime.try_submit_if_current({2}, guest_command, {});
require(invalid.admission == RuntimeAdmission::InvalidRequest && !invalid.completion.valid());
owner.arm();
RuntimeSubmission local{RuntimeAdmission::Busy, {}};
pump_until([&] { local = runtime.try_submit({1}, local_command); },
[&] { return local.admission != RuntimeAdmission::Busy; }, "Local work did not enter owner queue.");
require(local.admission == RuntimeAdmission::Accepted);
pump_until([] {}, [&] { return owner.waiting(); }, "Owner did not reach capture barrier.");
RuntimeSubmission accepted{RuntimeAdmission::Busy, {}};
pump_until([&] { accepted = runtime.try_submit_if_current({2}, guest_command, checked); },
[&] { return accepted.admission != RuntimeAdmission::Busy; }, "Conditional work did not enter remaining slot.");
require(accepted.admission == RuntimeAdmission::Accepted);
const auto full = runtime.try_submit_if_current({2}, guest_command, checked);
require(full.admission == RuntimeAdmission::Busy && !full.completion.valid());
// Both operations were admitted while S was current. Publishing the local
// result must not revoke the already queued guarded guest operation.
owner.release();
require(local.completion.wait_for(3s) == std::future_status::ready &&
local.completion.get().receipt->command_status == CommandStatus::Accepted);
require(accepted.completion.wait_for(3s) == std::future_status::ready &&
accepted.completion.get().receipt->command_status == CommandStatus::Accepted);
const auto current = runtime.latest();
require(current != checked && current->next_requests[1] == 2);
RuntimeSubmission stale{RuntimeAdmission::Busy, {}};
pump_until([&] { stale = runtime.try_submit_if_current({2}, guest_command, checked); },
[&] { return stale.admission != RuntimeAdmission::Busy; }, "Stale snapshot refusal remained contended.");
require(stale.admission == RuntimeAdmission::StaleSnapshot && !stale.completion.valid());
require(runtime.latest() == current);
runtime.shutdown();
const auto closed = runtime.try_submit_if_current({2}, guest_command, current);
require(closed.admission == RuntimeAdmission::Closed && !closed.completion.valid());
}
Test LanTests::test_conditional_admission_rejects_faulted_owner_with_retained_publication() {
RuntimeOptions options{.ticking = false};
options.observer = [](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected guarded-admission fault.");
};
SimulationRuntime runtime(colony_checkpoint(), options);
const auto checked = runtime.latest();
const auto id = checked->identity;
const CommandEnvelope command{command_envelope_version, id.world, id.session, id.city,
checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}};
RuntimeSubmission fault{RuntimeAdmission::Busy, {}};
pump_until([&] { fault = runtime.try_submit({1}, command); },
[&] { return fault.admission != RuntimeAdmission::Busy; }, "Fault trigger remained contended.");
require(fault.admission == RuntimeAdmission::Accepted && fault.completion.wait_for(3s) == std::future_status::ready);
require(fault.completion.get().outcome == RuntimeOutcome::Faulted);
require(runtime.latest() == checked && runtime.view().state == RuntimeState::Faulted);
RuntimeSubmission denied{RuntimeAdmission::Busy, {}};
pump_until([&] { denied = runtime.try_submit_if_current({1}, command, checked); },
[&] { return denied.admission != RuntimeAdmission::Busy; }, "Faulted owner refusal remained contended.");
require(denied.admission == RuntimeAdmission::Closed && !denied.completion.valid());
require(runtime.latest() == checked && !runtime.lookup({1}, command));
}
} // namespace
+275
View File
@@ -0,0 +1,275 @@
#include "settlement/core/simulation_runtime.hpp"
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <limits>
#include <stdexcept>
#include <thread>
namespace {
using namespace settlement;
using Void::Testing::Test;
using namespace std::chrono_literals;
constexpr TrustedClient host{colony_host};
void require(bool condition, const char* message = "production command invariant failed") {
if (!condition) throw std::runtime_error(message);
}
SessionIdentity identity() {
SessionIdentity result;
result.world.bytes.back() = 61;
result.session.bytes.back() = 62;
return result;
}
CommandEnvelope envelope(std::uint64_t request, SessionPayload payload, SessionIdentity context = identity()) {
return {command_envelope_version, context.world, context.session, context.city, request, std::move(payload)};
}
DispatchReceipt send(World& world, CommandDispatcher& dispatcher, SessionPayload payload) {
return dispatcher.dispatch(world, host, envelope(dispatcher.next_request(host), std::move(payload)));
}
void accepted(const DispatchReceipt& receipt) {
require(receipt.status == DispatchStatus::Completed && receipt.command_status == CommandStatus::Accepted,
"production command was not accepted");
}
template<class Predicate>
void step_until(World& world, Predicate done) {
for (int tick = 0; tick < 600 && !done(); ++tick) world.step();
require(done(), "actual work did not reach the required phase");
world.validate_custody();
}
std::unique_ptr<World> cabin() {
auto world = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
const auto store = world->add_storage({3, 3}, 20);
world->stock_storage(store, ItemType::Plank, 3);
world->stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world->spawn_agent({1, 3}));
world->queue_production({14, 3}, RecipeId::BuildCabin);
return world;
}
RuntimeResult finish(RuntimeSubmission submission) {
require(submission.admission == RuntimeAdmission::Accepted);
require(submission.completion.wait_for(5s) == std::future_status::ready);
auto result = submission.completion.get();
require(result.outcome == RuntimeOutcome::Completed && result.receipt.has_value());
return result;
}
struct [[= Void::Testing::name("ProductionCommandsTests")]] ProductionCommandsTests
: Void::Testing::Suite<ProductionCommandsTests> {
[[= Void::Testing::tag("production-command")]] Test exact_results_and_conflicts_use_durable_ids();
[[= Void::Testing::tag("production-command")]] Test context_and_guest_denials_leave_orders_untouched();
[[= Void::Testing::tag("production-command")]] Test cancel_at_each_phase_returns_actual_cargo_once();
[[= Void::Testing::tag("production-command")]] Test full_storage_preserves_return_until_space_exists();
[[= Void::Testing::tag("production-command")]] Test resume_keeps_partial_bed_and_installed_loom_identity();
[[= Void::Testing::tag("production-command")]] Test runtime_publishes_and_retains_modern_receipts();
};
Test ProductionCommandsTests::exact_results_and_conflicts_use_durable_ids() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.queue_production({8, 8}, RecipeId::SawPlank);
world.queue_production({8, 8}, RecipeId::SawPlank);
const auto first = world.production_orders().front().id;
const auto second = world.production_orders().back().id;
CommandDispatcher dispatcher(identity());
const auto cancel = envelope(1, CancelProductionPayload{first});
const auto result = dispatcher.dispatch(world, host, cancel);
accepted(result);
require(result.revision == 1 && world.find_production(first) == nullptr && world.find_production(second),
"cancel selected by vector position or cell instead of exact durable id");
require(dispatcher.dispatch(world, host, cancel) == result && dispatcher.lookup(host, cancel) == result);
for (const SessionPayload changed : {SessionPayload{CancelProductionPayload{second}},
SessionPayload{ResumeProductionPayload{first}}, SessionPayload{CommandPayload{}},
SessionPayload{LegacyCabinPayload{{8, 8}, {2, 2}, {3, 2}}}}) {
require(dispatcher.dispatch(world, host, envelope(1, changed)).status == DispatchStatus::Conflict,
"same request accepted a different id or payload variant");
}
const auto refused = envelope(2, ResumeProductionPayload{first});
const auto rejection = dispatcher.dispatch(world, host, refused);
require(rejection.status == DispatchStatus::Completed && rejection.command_status == CommandStatus::InvalidTarget &&
rejection.revision == 1 && dispatcher.dispatch(world, host, refused) == rejection);
const auto zero = envelope(3, CancelProductionPayload{0});
const auto zero_result = dispatcher.dispatch(world, host, zero);
require(zero_result.command_status == CommandStatus::InvalidTarget && dispatcher.dispatch(world, host, zero) == zero_result);
accepted(send(world, dispatcher, CancelProductionPayload{second}));
require(world.production_orders().empty() && dispatcher.revision() == 2 &&
world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1,
"modern command changed legacy accepted-command numbering");
require(dispatcher.dispatch(world, host, cancel) == result, "removed target lost the original retained receipt");
world.validate_custody();
}
Test ProductionCommandsTests::context_and_guest_denials_leave_orders_untouched() {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.queue_production({8, 8}, RecipeId::BuildCabin);
const auto id = world.production_orders().front().id;
CommandDispatcher dispatcher(identity());
auto command = envelope(1, CancelProductionPayload{id});
command.world.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld);
command = envelope(1, CancelProductionPayload{id});
command.session.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::StaleSession);
command = envelope(1, CancelProductionPayload{id});
require(dispatcher.dispatch(world, {0}, command).status == DispatchStatus::UnauthorizedClient);
require(dispatcher.dispatch(world, {3}, command).status == DispatchStatus::UnauthorizedClient);
require(dispatcher.receipt_count(host) == 0 && dispatcher.revision() == 0 && world.find_production(id));
const auto guest_result = dispatcher.dispatch(world, {2}, command);
require(guest_result.command_status == CommandStatus::Unauthorized &&
dispatcher.dispatch(world, {2}, command) == guest_result);
const auto guest_resume = envelope(2, ResumeProductionPayload{id});
require(dispatcher.dispatch(world, {2}, guest_resume).command_status == CommandStatus::Unauthorized);
command.city = 2;
const auto denied = dispatcher.dispatch(world, host, command);
require(denied.command_status == CommandStatus::Unauthorized && denied.revision == 0 &&
dispatcher.dispatch(world, host, command) == denied && world.find_production(id));
command.city = 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::Conflict);
command.request = 2;
accepted(dispatcher.dispatch(world, host, command));
command.world.bytes.back() ^= 1;
require(dispatcher.dispatch(world, host, command).status == DispatchStatus::WrongWorld,
"cached receipt bypassed world identity check");
require(world.next_command_sequence(1) == 1 && world.next_command_sequence(2) == 1);
}
Test ProductionCommandsTests::cancel_at_each_phase_returns_actual_cargo_once() {
for (int phase = 0; phase < 3; ++phase) {
auto world = cabin();
const auto id = world->production_orders().front().id;
const auto storage = world->storages().front().id;
step_until(*world, [&] {
const auto& agent = world->agents().front();
return phase == 0 ? agent.state == AgentState::FetchingMaterials && agent.inventory.empty() :
phase == 1 ? !agent.inventory.empty() : agent.state == AgentState::Working;
});
CommandDispatcher dispatcher(identity());
const auto sequence = world->next_command_sequence(1);
require(send(*world, dispatcher, CommandPayload{CommandKind::DemolishObject, {3, 3}}).command_status == CommandStatus::Busy);
require(send(*world, dispatcher, CommandPayload{CommandKind::MoveObject, {3, 3}, 0, {4, 3}}).command_status == CommandStatus::Busy);
const auto cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id});
const auto result = dispatcher.dispatch(*world, host, cancel);
accepted(result);
if (phase != 0) require(world->agents().front().state == AgentState::Returning &&
!world->agents().front().inventory.empty(), "cancellation erased carried or worksite input");
require(dispatcher.dispatch(*world, host, cancel) == result);
step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; });
require(world->find_storage(storage)->item_count(ItemType::Plank) == 3 &&
world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2 &&
world->agents().front().inventory.empty() && world->find_production(id) == nullptr,
"cancelled material was lost, duplicated or left assigned");
for (int tick = 0; tick < 4; ++tick) world->step();
require(dispatcher.dispatch(*world, host, cancel) == result && world->next_command_sequence(1) == sequence &&
world->find_storage(storage)->item_count(ItemType::Plank) == 3 &&
world->find_storage(storage)->item_count(ItemType::StoneBlock) == 2);
world->validate_custody();
}
}
Test ProductionCommandsTests::full_storage_preserves_return_until_space_exists() {
auto world = cabin();
const auto id = world->production_orders().front().id;
const auto original = world->storages().front().id;
step_until(*world, [&] { return !world->agents().front().inventory.empty(); });
world->stock_storage(original, ItemType::Wood, 20);
CommandDispatcher dispatcher(identity());
accepted(send(*world, dispatcher, CancelProductionPayload{id}));
for (int tick = 0; tick < 10; ++tick) world->step();
const auto& waiting = world->agents().front();
require(waiting.state == AgentState::Returning && waiting.execution &&
(waiting.execution->blocked == CustodyStatus::NoDestination || waiting.execution->blocked == CustodyStatus::Capacity) &&
waiting.inventory.item_count(ItemType::Plank) == 3 && waiting.inventory.item_count(ItemType::StoneBlock) == 2,
"full storage did not preserve the cargo and meaningful blocked reason");
const auto destination = world->add_storage({4, 3}, 5);
step_until(*world, [&] { return world->agents().front().state != AgentState::Returning; });
require(world->find_storage(destination)->item_count(ItemType::Plank) == 3 &&
world->find_storage(destination)->item_count(ItemType::StoneBlock) == 2 &&
world->find_storage(original)->item_count(ItemType::Wood) == 20);
}
Test ProductionCommandsTests::resume_keeps_partial_bed_and_installed_loom_identity() {
for (const bool bed : {true, false}) {
World world(43, 32, 32, 1, ExecutionMode::SerialReference);
world.start_scenario({2, 2});
const auto storage = world.add_storage({3, 3}, 20);
world.stock_storage(storage, ItemType::Wood, 2);
static_cast<void>(world.spawn_agent({1, 3}));
CommandDispatcher dispatcher(identity());
if (bed) {
accepted(send(world, dispatcher, CommandPayload{CommandKind::PlaceBed, {9, 3}}));
} else {
world.queue_production({9, 3}, RecipeId::BuildLoom);
}
const auto id = world.production_orders().back().id;
step_until(world, [&] {
const auto* order = world.find_production(id);
return bed ? order->bed_stage == BedStage::Bedding : order->recipe == RecipeId::WeaveCloth;
});
const auto before_cancel = world.capture();
const auto stage = world.find_production(id)->bed_stage;
const auto sequence = world.next_command_sequence(1);
accepted(send(world, dispatcher, CancelProductionPayload{id}));
require(world.find_production(id) && world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && !world.can_place_storage({9, 3}),
"cancel removed installed progress or its occupied site");
const auto suspended_cancel = envelope(dispatcher.next_request(host), CancelProductionPayload{id});
const auto busy = dispatcher.dispatch(world, host, suspended_cancel);
require(busy.status == DispatchStatus::Completed && busy.command_status == CommandStatus::Busy &&
dispatcher.dispatch(world, host, suspended_cancel) == busy);
for (int tick = 0; tick < 5; ++tick) world.step();
const auto resume = envelope(dispatcher.next_request(host), ResumeProductionPayload{id});
const auto resumed = dispatcher.dispatch(world, host, resume);
accepted(resumed);
require(world.find_production(id) && !world.find_production(id)->suspended &&
world.find_production(id)->bed_stage == stage && dispatcher.dispatch(world, host, resume) == resumed &&
world.next_command_sequence(1) == sequence && !before_cancel->find_production(id)->suspended);
require(dispatcher.dispatch(world, host, suspended_cancel) == busy && !world.find_production(id)->suspended,
"old refused cancellation changed after the same durable order was resumed");
world.stock_storage(storage, bed ? ItemType::Cloth : ItemType::Flax, 2);
step_until(world, [&] { return bed ? world.find_production(id)->state == JobState::Completed :
world.find_storage(storage)->item_count(ItemType::Cloth) > 0; });
require(world.find_storage(storage)->item_count(ItemType::Wood) == (bed ? 1U : 0U),
"resume charged for an already installed stage twice");
if (bed) {
const auto refused = send(world, dispatcher, CancelProductionPayload{id});
require(refused.command_status == CommandStatus::Busy,
"completed final bed accepted cancel");
}
}
}
Test ProductionCommandsTests::runtime_publishes_and_retains_modern_receipts() {
auto world = cabin();
step_until(*world, [&] { return !world->agents().front().inventory.empty(); });
const auto id = world->production_orders().front().id;
const auto rules = default_rules_manifest();
require(rules.has_value());
SimulationRuntime runtime(WorldCheckpoint{std::move(world), identity().world, 1, *rules}, {.ticking = false});
const auto opening = runtime.latest();
const auto cancel = envelope(1, CancelProductionPayload{id}, opening->identity);
const auto first = finish(runtime.try_submit(host, cancel));
accepted(*first.receipt);
require(first.snapshot->world->find_production(id) == nullptr &&
first.snapshot->world->agents().front().state == AgentState::Returning &&
opening->world->find_production(id) && opening->world->agents().front().state != AgentState::Returning,
"modern runtime effect was not published with independent old snapshot");
const auto repeat = finish(runtime.try_submit(host, cancel));
require(repeat.receipt == first.receipt && runtime.lookup(host, cancel) == first.receipt &&
repeat.snapshot->revision == first.snapshot->revision && repeat.snapshot->next_requests[0] == 2);
const auto changed = finish(runtime.try_submit(host, envelope(1, ResumeProductionPayload{id}, opening->identity)));
require(changed.receipt->status == DispatchStatus::Conflict);
const auto refusal = envelope(2, ResumeProductionPayload{id}, opening->identity);
const auto denied = finish(runtime.try_submit(host, refusal));
require(denied.receipt->command_status == CommandStatus::InvalidTarget &&
finish(runtime.try_submit(host, refusal)).receipt == denied.receipt &&
runtime.latest()->world->next_command_sequence(1) == 1 && runtime.view().state == RuntimeState::Running);
runtime.latest()->world->validate_custody();
}
} // namespace
+330
View File
@@ -0,0 +1,330 @@
// Exercise the real private Win32 controls and modal handlers in their own
// executable, without adding test hooks to the shipping UI or wire protocol.
#include "../app/viewer_win32.cpp"
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <functional>
namespace production_controls {
using namespace settlement;
using Void::Testing::Test;
using namespace std::chrono_literals;
void require(bool condition, const char* message = "production controls invariant failed") {
if (!condition) throw std::runtime_error(message);
}
constexpr UINT_PTR drive_timer = 904;
struct MenuStep { UINT command; std::function<void()> before_select; };
std::vector<MenuStep> steps;
std::vector<std::vector<std::wstring>> observed_menus;
HMENU active_menu = nullptr;
std::string driver_error;
unsigned timer_attempts = 0;
void key(std::vector<INPUT>& input, WORD code) {
INPUT down{};
down.type = INPUT_KEYBOARD;
down.ki.wVk = code;
input.push_back(down);
down.ki.dwFlags = KEYEVENTF_KEYUP;
input.push_back(down);
}
LRESULT CALLBACK test_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
if (message == WM_INITMENUPOPUP) {
active_menu = reinterpret_cast<HMENU>(wparam);
std::vector<std::wstring> labels;
for (int index = 0; index < GetMenuItemCount(active_menu); ++index) {
wchar_t label[512]{};
GetMenuStringW(active_menu, static_cast<UINT>(index), label, 512, MF_BYPOSITION);
labels.emplace_back(label);
}
observed_menus.push_back(std::move(labels));
}
if (message == WM_TIMER && wparam == drive_timer) {
if (++timer_attempts > 100) {
driver_error = "real popup did not accept input: menus=" + std::to_string(observed_menus.size()) +
" remaining=" + std::to_string(steps.size()) + " active=" + std::to_string(active_menu != nullptr);
KillTimer(window, drive_timer);
EndMenu();
return 0;
}
if (!active_menu || steps.empty()) return 0;
const auto menu = std::exchange(active_menu, nullptr);
auto step = std::move(steps.front());
steps.erase(steps.begin());
int target = -1;
for (int index = 0; index < GetMenuItemCount(menu); ++index) {
if (GetMenuItemID(menu, index) == step.command) { target = index; break; }
}
if (target < 0) {
driver_error = "expected action absent from actual popup";
EndMenu();
return 0;
}
try {
if (step.before_select) step.before_select();
} catch (const std::exception& error) {
driver_error = error.what();
EndMenu();
return 0;
}
std::vector<INPUT> input;
key(input, VK_HOME);
for (int index = 0; index < target; ++index) {
if ((GetMenuState(menu, static_cast<UINT>(index), MF_BYPOSITION) & MF_SEPARATOR) == 0) key(input, VK_DOWN);
}
key(input, VK_RETURN);
if (SendInput(static_cast<UINT>(input.size()), input.data(), sizeof(INPUT)) != input.size()) {
driver_error = "SendInput failed for actual popup";
EndMenu();
}
return 0;
}
return window_proc(window, message, wparam, lparam);
}
struct Window {
HWND handle = nullptr;
std::filesystem::path user_data;
std::wstring old_user_data;
explicit Window(std::unique_ptr<World> initial) {
const auto uuid = Void::Uuid::try_v4();
require(uuid.has_value());
user_data = std::filesystem::temp_directory_path() / ("settlement-order-controls-" + uuid->to_string());
require(std::filesystem::create_directory(user_data));
wchar_t old[32768]{};
const auto size = GetEnvironmentVariableW(L"LOCALAPPDATA", old, 32768);
old_user_data.assign(old, size < 32768 ? size : 0);
require(SetEnvironmentVariableW(L"LOCALAPPDATA", user_data.c_str()));
auto rules = default_rules_manifest();
require(rules.has_value());
session = std::make_unique<settlement::viewer::ViewerSession>(
WorldCheckpoint{std::move(initial), *uuid, 1, *rules}, 2);
world = session->world();
showing_title = true;
has_session = true;
lan = std::make_unique<settlement::viewer::LanSession>();
displayed_lan_state = LanState::Offline;
placement_mode = PlacementMode::None;
camera = {};
placement_message.clear();
steps.clear();
observed_menus.clear();
active_menu = nullptr;
driver_error.clear();
timer_attempts = 0;
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES};
require(InitCommonControlsEx(&controls));
WNDCLASSW type{};
type.lpfnWndProc = test_window_proc;
type.hInstance = GetModuleHandleW(nullptr);
type.lpszClassName = L"SettlementProductionControlsTest";
type.hCursor = LoadCursorW(nullptr, IDC_ARROW);
require(RegisterClassW(&type) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS);
handle = CreateWindowExW(0, type.lpszClassName, L"Production controls test",
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 32, 32, 1120, 752, nullptr, nullptr, type.hInstance, nullptr);
require(handle != nullptr);
show_title_screen(handle, false);
file_dialog_active = true; // Freeze ticks while exercising UI receipt delivery.
KillTimer(handle, timer_id);
session->set_ticking(false);
ShowWindow(handle, SW_SHOW);
UpdateWindow(handle);
SetForegroundWindow(handle);
}
~Window() {
if (handle) DestroyWindow(handle);
session.reset();
world.reset();
file_dialog_active = false;
MSG message{};
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {}
SetEnvironmentVariableW(L"LOCALAPPDATA", old_user_data.empty() ? nullptr : old_user_data.c_str());
std::error_code error;
std::filesystem::remove_all(user_data, error);
}
void menu(std::vector<MenuStep> actions, const std::function<void()>& open) {
steps = std::move(actions);
require(SetTimer(handle, drive_timer, 50, nullptr) != 0);
open();
KillTimer(handle, drive_timer);
require(driver_error.empty(), driver_error.c_str());
require(steps.empty(), "not all popup pages were reachable");
}
void pump_until(const std::function<bool()>& done) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (!done()) {
SendMessageW(handle, WM_TIMER, timer_id, 0);
require(std::chrono::steady_clock::now() < deadline, "UI receipt/replacement did not finish");
std::this_thread::yield();
}
}
void activate_tool() {
menu({{manage_orders_id, {}}}, [&] { SendMessageW(work_list_button, BM_CLICK, 0, 0); });
// The normal work menu posts WM_COMMAND after closing its popup.
MSG message{};
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
require(placement_mode == PlacementMode::ManageOrders, "Работы menu did not activate order management");
}
void click_cell(GridPosition cell) {
RECT client{};
GetClientRect(handle, &client);
const auto scale = camera.scale();
const auto offset = camera.offset();
POINT point{static_cast<LONG>((client.right / 2.0 + (cell.x - cell.y) * tile_width / 2.0) * scale + offset.x),
static_cast<LONG>((map_origin_y + (cell.x + cell.y) * tile_height / 2.0) * scale + offset.y)};
require(map_cell(client, point) == cell, "normal map hit test did not select the target cell");
auto screen = point;
ClientToScreen(handle, &screen);
SetCursorPos(screen.x, screen.y);
const auto coordinates = MAKELPARAM(point.x, point.y);
SendMessageW(handle, WM_LBUTTONDOWN, MK_LBUTTON, coordinates);
SendMessageW(handle, WM_LBUTTONUP, 0, coordinates);
}
};
std::unique_ptr<World> orders(unsigned count = 2) {
auto result = std::make_unique<World>(43, 32, 32, 1, ExecutionMode::SerialReference);
for (unsigned index = 0; index < count; ++index) result->queue_production({8, 8}, RecipeId::SawPlank);
return result;
}
struct [[= Void::Testing::name("ProductionControlsTests")]] ProductionControlsTests
: Void::Testing::Suite<ProductionControlsTests> {
[[= Void::Testing::tag("production-controls")]] Test real_work_menu_selects_exact_id_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test real_resume_choice_keeps_installed_loom_and_waits_for_receipt();
[[= Void::Testing::tag("production-controls")]] Test every_order_remains_accessible_across_popup_pages();
[[= Void::Testing::tag("production-controls")]] Test replacement_during_popup_cannot_cancel_in_new_world();
[[= Void::Testing::tag("production-controls")]] Test legacy_guest_has_no_action_or_modern_submission();
[[= Void::Testing::tag("production-controls")]] Test returning_resident_explains_wait_for_storage();
};
Test ProductionControlsTests::real_work_menu_selects_exact_id_and_waits_for_receipt() {
Window fixture(orders());
const auto first = world->production_orders().front().id;
const auto second = world->production_orders().back().id;
fixture.activate_tool();
fixture.menu({{2, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(second) && world->find_production(first) &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos,
"UI forged success before a committed receipt");
require(observed_menus.back().at(1).find(L"Отменить: Распилить доску №" + std::to_wstring(second)) != std::wstring::npos &&
observed_menus.back().at(1).find(L"[9, 9]") != std::wstring::npos,
"actual popup lost the order name, durable id or user-facing position");
fixture.pump_until([&] { return !world->find_production(second); });
require(world->find_production(first) && placement_message.find(L"Заказ отменён") != std::wstring::npos &&
session->runtime().latest()->next_requests[0] == 2 && world->next_command_sequence(1) == 1);
}
Test ProductionControlsTests::every_order_remains_accessible_across_popup_pages() {
Window fixture(orders(35));
const auto last = world->production_orders().back().id;
fixture.activate_tool();
fixture.menu({{101, {}}, {101, {}}, {3, {}}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !world->find_production(last); });
require(world->production_orders().size() == 34 && world->production_orders().front().id == 1);
for (const auto& page : observed_menus) require(page.size() <= 19, "popup page exceeded its bounded display size");
}
Test ProductionControlsTests::real_resume_choice_keeps_installed_loom_and_waits_for_receipt() {
auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::WeaveCloth);
const auto id = initial->production_orders().front().id;
require(initial->cancel_production(id) == CommandStatus::Accepted && initial->find_production(id)->suspended);
Window fixture(std::move(initial));
fixture.activate_tool();
fixture.menu({{1, {}}}, [&] { fixture.click_cell({8, 8}); });
require(world->find_production(id)->suspended &&
placement_message.find(L"ожидает подтверждения") != std::wstring::npos);
require(observed_menus.back().at(0).find(L"Возобновить: Ткать ткань №" + std::to_wstring(id)) != std::wstring::npos);
fixture.pump_until([&] { return !world->find_production(id)->suspended; });
require(world->find_production(id)->recipe == RecipeId::WeaveCloth &&
placement_message.find(L"возобновлена") != std::wstring::npos && world->next_command_sequence(1) == 1);
}
Test ProductionControlsTests::replacement_during_popup_cannot_cancel_in_new_world() {
for (const bool complete_replacement : {false, true}) {
Window fixture(orders());
const auto opening = session->runtime().latest();
fixture.activate_tool();
fixture.menu({{1, [&] {
session->new_colony();
if (complete_replacement) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (session->changing_world()) {
static_cast<void>(session->poll());
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
}
world = session->world();
}
}}}, [&] { fixture.click_cell({8, 8}); });
fixture.pump_until([&] { return !session->changing_world(); });
const auto current = session->runtime().latest();
require(current->identity != opening->identity && current->next_requests[0] == 1 &&
current->world->next_command_sequence(1) == 1,
"stale popup enqueued a production command into the new session");
require(opening->world->production_orders().size() == 2, "modal selection invalidated pinned snapshot");
}
}
Test ProductionControlsTests::legacy_guest_has_no_action_or_modern_submission() {
Window fixture(orders());
const auto host_id = Void::Uuid::try_v4();
const auto rules = default_rules_manifest();
require(host_id.has_value() && rules.has_value());
SimulationRuntime host_runtime(WorldCheckpoint{make_first_colony(2), *host_id, 1, *rules}, {.ticking = false});
settlement::viewer::LanSession host_peer;
host_peer.host(0, true);
session->enter_guest();
lan->join("127.0.0.1", host_peer.join_code(), host_peer.port());
const auto deadline = std::chrono::steady_clock::now() + 5s;
while (lan->state() != LanState::GuestConnected) {
host_peer.poll_host(host_runtime);
if (auto incoming = lan->poll_guest()) session->receive_guest(std::move(incoming));
require(std::chrono::steady_clock::now() < deadline, "real legacy guest did not connect");
std::this_thread::yield();
}
world = session->world();
require(lan->is_guest() && session->guest());
const auto before = session->runtime().latest();
const auto menu = create_work_menu();
require(menu != nullptr && GetMenuState(menu, manage_orders_id, MF_BYCOMMAND) == static_cast<UINT>(-1),
"legacy guest saw the modern management action");
DestroyMenu(menu);
SendMessageW(fixture.handle, WM_COMMAND, manage_orders_id, 0);
require(placement_mode != PlacementMode::ManageOrders && !can_manage_orders());
placement_mode = PlacementMode::ManageOrders;
edit_at_cell(fixture.handle, {8, 8});
require(!enqueue_command(CancelProductionPayload{1}) && !enqueue_command(ResumeProductionPayload{1}) &&
session->runtime().latest() == before && guest_intents.empty(),
"legacy guest admitted a modern order payload");
}
Test ProductionControlsTests::returning_resident_explains_wait_for_storage() {
auto initial = orders(0);
initial->queue_production({8, 8}, RecipeId::BuildCabin);
const auto storage = initial->add_storage({3, 3}, 5);
initial->stock_storage(storage, ItemType::Plank, 3);
initial->stock_storage(storage, ItemType::StoneBlock, 2);
const auto resident = initial->spawn_agent({1, 3});
for (int tick = 0; tick < 100 && initial->agents().front().inventory.empty(); ++tick) initial->step();
require(!initial->agents().front().inventory.empty());
initial->stock_storage(storage, ItemType::Wood, 5);
require(initial->cancel_production(initial->production_orders().front().id) == CommandStatus::Accepted);
for (int tick = 0; tick < 5; ++tick) initial->step();
Window fixture(std::move(initial));
selected_resident = resident;
const auto details = resident_details();
require(details.find(L"Возвращает материалы") != std::wstring::npos &&
(details.find(L"нет доступного склада с местом") != std::wstring::npos ||
details.find(L"на складе недостаточно места") != std::wstring::npos) &&
details.find(L"доски ×3") != std::wstring::npos && details.find(L"блоки ×2") != std::wstring::npos,
"real returning resident did not expose actual cargo and waiting reason");
}
} // namespace production_controls
+325
View File
@@ -0,0 +1,325 @@
// 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::Current15);
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;
}
}
+35 -1
View File
@@ -118,6 +118,7 @@ struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void
[[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches();
[[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins();
[[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules();
[[= Void::Testing::tag("viewer-session")]] Test test_legacy_host_requires_representable_published_custody();
};
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
@@ -529,7 +530,7 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa
if (mode == 2) candidate.world = std::make_unique<World>(17, 32, 32, 2);
const auto expected = bytes(*candidate.world);
ViewerSession session(std::move(candidate), 2);
require(bytes(*session.world()) == expected && session.can_host_legacy());
require(bytes(*session.world()) == expected && session.can_host_legacy() == (mode != 2));
write(files.root / "legacy.settlement", expected);
session.load(files.root / "legacy.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
@@ -543,4 +544,37 @@ Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_defa
require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy());
}
Test ViewerSessionTests::test_legacy_host_requires_representable_published_custody() {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
candidate.world = std::make_unique<World>(43, 32, 32, 2);
auto& world = *candidate.world;
const auto store = world.add_storage({3, 3}, 5);
world.stock_storage(store, ItemType::Plank, 3);
world.stock_storage(store, ItemType::StoneBlock, 2);
static_cast<void>(world.spawn_agent({1, 3}));
world.start_scenario({6, 6});
world.queue_production({14, 3}, RecipeId::BuildCabin);
for (int tick = 0; tick < 100 && world.agents().front().inventory.empty(); ++tick) world.step();
require(world.agents().front().inventory.item_count(ItemType::Plank) == 3 &&
world.agents().front().inventory.item_count(ItemType::StoneBlock) == 2);
world.stock_storage(store, ItemType::Wood, 5);
require(world.legacy_representable());
require(world.cancel_production(world.production_orders().front().id) == CommandStatus::Accepted);
require(!world.legacy_representable());
ViewerSession session(std::move(candidate), 2);
const auto published = session.runtime().latest();
require(!session.can_host_legacy() && session.can_submit());
require(session.world() == published->world && session.runtime().view().state == RuntimeState::Running);
TempFiles files;
session.save(files.root / "custody.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
session.load(files.root / "custody.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(!session.can_host_legacy() && !session.world()->legacy_representable() && session.can_submit());
session.new_colony();
require(session.changing_world() && !session.can_host_legacy());
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(session.can_host_legacy());
}
} // namespace
+392
View File
@@ -0,0 +1,392 @@
#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
@@ -0,0 +1,479 @@
#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
+429
View File
@@ -0,0 +1,429 @@
#define NOMINMAX
#include "d3d_scene_win32.hpp"
#include "voxel_scene.hpp"
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>
namespace {
using namespace settlement;
using namespace settlement::viewer;
using Void::Testing::Test;
using Mark = std::pair<VoxelPosition, MaterialId>;
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
void require(bool condition, const char* message = "voxel scene invariant failed") {
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;
}
void load_page(VoxelRegion& region, ChunkCoordinate coordinate, std::span<const Mark> marks = {}) {
std::vector<MaterialId> cells(voxel_chunk_cells, MaterialId::Air);
for (const auto& [position, material] : marks) {
const auto address = split_voxel(position);
if (address.chunk == coordinate) cells[*voxel_index(address.local)] = material;
}
const auto candidate = region.prepare_restored(coordinate, 1, cells);
require(candidate.has_value(), "restored fixture page refused");
require(region.activate(std::span(&*candidate, 1)).has_value(), "fixture activation refused");
}
VoxelRegion loaded(VoxelBounds bounds, std::initializer_list<Mark> marks = {}) {
VoxelRegion region({7, 42, voxel_generator_version, bounds});
const auto first = 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 last = 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 = first.z; z <= last.z; ++z) for (auto y = first.y; y <= last.y; ++y) {
for (auto x = first.x; x <= last.x; ++x) load_page(region, {x, y, z}, {marks.begin(), marks.size()});
}
return region;
}
std::shared_ptr<const VoxelScene> prepare(const VoxelRegion& region, std::int32_t slice = largest) {
auto result = prepare_voxel_scene(region, epoch(), {region.descriptor().bounds, slice});
require(result.has_value(), "scene preparation refused");
return *result;
}
void edit(VoxelRegion& region, VoxelPosition cell, MaterialId material) {
const VoxelEdit change{cell, material, region.sample(cell).stamp.revision};
require(region.edit(std::span(&change, 1)).has_value(), "fixture edit refused");
}
bool has_face(const VoxelScene& scene, VoxelPosition cell, VoxelPosition normal) {
return std::ranges::any_of(scene.faces(), [&](const auto& face) { return face.cell == cell && face.normal == normal; });
}
VoxelPick trace(const VoxelScene& scene, VoxelPoint origin, VoxelPoint direction, double distance = 100) {
auto result = trace_voxels(scene, {origin, direction, distance});
require(result.has_value(), "valid ray refused");
return *result;
}
void hit(const VoxelPick& pick, VoxelPosition cell, VoxelPosition normal) {
require(pick.status == VoxelPickStatus::Hit, "ray did not hit");
require(pick.cell == cell, "ray selected wrong cell");
require(pick.normal == normal, "ray selected wrong face");
}
template<class T> void error(const std::expected<T, VoxelSceneError>& result, VoxelSceneError expected) {
require(!result && result.error() == expected, "wrong error or successful refusal");
}
VoxelPick pixel_probe(D3DScene& renderer, std::shared_ptr<const PreparedGeometry> geometry,
const VoxelScene& scene, VoxelCamera camera, VoxelPoint point, VoxelPosition cell, VoxelPosition normal) {
const auto projected = project_voxel_point(scene, camera, point);
require(projected.has_value(), "projection refused");
const auto x = static_cast<int>(std::floor(projected->x));
const auto y = static_cast<int>(std::floor(projected->y));
require(x >= 0 && x < camera.width && y >= 0 && y < camera.height, "test point outside viewport");
const auto pick = pick_voxel_screen(scene, camera, {x + .5, y + .5});
require(pick.has_value(), "pixel ray refused");
hit(*pick, cell, normal);
std::vector<std::uint32_t> pixels;
require(renderer.render(std::move(geometry), camera, &pixels), "offscreen D3D11 draw failed");
const auto expected = voxel_face_color({pick->cell, pick->normal, pick->material,
pick->status == VoxelPickStatus::Unavailable});
const auto actual = pixels[static_cast<std::size_t>(y) * camera.width + x] & 0x00ffffffu;
if (actual != expected) {
std::cerr << "pixel " << x << ',' << y << " color " << std::hex << actual << " expected " << expected << std::dec << '\n';
throw std::runtime_error("D3D pixel does not show the picked face");
}
return *pick;
}
struct [[= Void::Testing::name("VoxelSceneTests")]] VoxelSceneTests : Void::Testing::Suite<VoxelSceneTests> {
[[= Void::Testing::tag("voxel-scene")]] Test exposed_faces_cross_signed_chunk_boundaries();
[[= Void::Testing::tag("voxel-scene")]] Test slice_is_inclusive_and_snapshots_survive_edits();
[[= Void::Testing::tag("voxel-scene")]] Test read_stamps_include_missing_and_neighbors_with_session_guard();
[[= Void::Testing::tag("voxel-scene")]] Test unrelated_pages_do_not_invalidate_bounded_scene();
[[= Void::Testing::tag("voxel-scene")]] Test closed_door_blocks_open_door_reveals_farther_surface();
[[= Void::Testing::tag("voxel-scene")]] Test exact_plane_edge_and_corner_ties_are_directional();
[[= Void::Testing::tag("voxel-scene")]] Test axis_rays_inside_parallel_and_misses();
[[= Void::Testing::tag("voxel-scene")]] Test bounded_rays_and_nonfinite_inputs_are_refused();
[[= Void::Testing::tag("voxel-scene")]] Test signed_extremes_use_checked_adjacent_cells();
[[= Void::Testing::tag("voxel-scene")]] Test generation_budgets_fail_before_publishing_replacement();
[[= Void::Testing::tag("voxel-scene")]] Test projection_and_pick_share_camera_and_slice();
[[= Void::Testing::tag("voxel-scene")]] Test generated_signed_terrain_is_meshed_and_drawn();
[[= Void::Testing::tag("voxel-scene")]] Test warp_pixels_match_faces_pan_zoom_and_retained_geometry();
[[= Void::Testing::tag("voxel-scene")]] Test warp_slice_and_open_door_match_picks();
[[= Void::Testing::tag("voxel-scene")]] Test warp_extreme_coordinates_missing_and_empty_scenes();
};
Test VoxelSceneTests::exposed_faces_cross_signed_chunk_boundaries() {
for (int seam : {-32, 0, 32}) {
const auto region = loaded({{seam - 2, -1, 0}, {seam + 2, 1, 2}},
{{{seam - 1, -1, 0}, MaterialId::Soil}, {{seam, -1, 0}, MaterialId::Stone}});
const auto scene = prepare(region);
require(scene->faces().size() == 10, "adjacent pages emitted duplicate internal faces");
require(!has_face(*scene, {seam - 1, -1, 0}, {1, 0, 0}));
require(!has_face(*scene, {seam, -1, 0}, {-1, 0, 0}));
hit(trace(*scene, {seam - 3., -.5, .5}, {1, 0, 0}), {seam - 1, -1, 0}, {-1, 0, 0});
hit(trace(*scene, {seam + 3., -.5, .5}, {-1, 0, 0}), {seam, -1, 0}, {1, 0, 0});
require(scene->reads().size() == 4, "signed display pages absent from read set");
}
}
Test VoxelSceneTests::slice_is_inclusive_and_snapshots_survive_edits() {
auto region = loaded({{-1, -1, -1}, {2, 2, 3}},
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::Soil}});
const auto complete = prepare(region), cut = prepare(region, 0);
require(complete->faces().size() == 10 && cut->faces().size() == 6);
require(has_face(*cut, {0, 0, 0}, {0, 0, 1}) && !has_face(*complete, {0, 0, 0}, {0, 0, 1}));
hit(trace(*complete, {.5, .5, 5}, {0, 0, -1}), {0, 0, 1}, {0, 0, 1});
hit(trace(*cut, {.5, .5, 5}, {0, 0, -1}), {0, 0, 0}, {0, 0, 1});
edit(region, {0, 0, 1}, MaterialId::Air);
const auto changed = prepare(region);
require(changed->faces().size() == 6 && complete->faces().size() == 10);
require(!complete->current(region, epoch()) && changed->current(region, epoch()));
hit(trace(*complete, {.5, .5, 5}, {0, 0, -1}), {0, 0, 1}, {0, 0, 1});
require(prepare(region, -2)->faces().empty());
}
Test VoxelSceneTests::read_stamps_include_missing_and_neighbors_with_session_guard() {
VoxelRegion region({7, 42, voxel_generator_version, {{30, 0, 0}, {34, 1, 1}}});
const std::array marks{Mark{{31, 0, 0}, MaterialId::Stone}};
load_page(region, {0, 0, 0}, marks);
const auto before = prepare(region);
require(before->reads().size() == 2 && before->reads()[1].availability == VoxelAvailability::Unavailable);
require(!has_face(*before, {31, 0, 0}, {1, 0, 0}), "unknown adjacent page must occlude the shared face");
const auto unresolved = trace(*before, {35, .5, .5}, {-1, 0, 0});
require(unresolved.status == VoxelPickStatus::Unavailable && unresolved.cell == VoxelPosition{33, 0, 0});
require(unresolved.current(region, epoch()) && !unresolved.current(region, epoch(2)));
load_page(region, {1, 0, 0});
require(!before->current(region, epoch()) && !unresolved.current(region, epoch()));
const auto after = prepare(region);
require(after->faces().size() == 6 && has_face(*after, {31, 0, 0}, {1, 0, 0}));
require(!after->current(region, epoch(2)));
hit(trace(*after, {35, .5, .5}, {-1, 0, 0}), {31, 0, 0}, {1, 0, 0});
require(trace(*before, {35, .5, .5}, {-1, 0, 0}).status == VoxelPickStatus::Unavailable);
}
Test VoxelSceneTests::unrelated_pages_do_not_invalidate_bounded_scene() {
auto region = loaded({{0, 0, 0}, {65, 1, 1}}, {{{0, 0, 0}, MaterialId::Stone}});
const auto scene = prepare_voxel_scene(region, epoch(), {{{0, 0, 0}, {2, 1, 1}}, 0});
require(scene.has_value() && (*scene)->reads().size() == 1);
edit(region, {64, 0, 0}, MaterialId::Stone);
require((*scene)->current(region, epoch()), "unconsulted page invalidated geometry");
edit(region, {1, 0, 0}, MaterialId::Stone);
require(!(*scene)->current(region, epoch()));
}
Test VoxelSceneTests::closed_door_blocks_open_door_reveals_farther_surface() {
auto region = loaded({{30, -1, 0}, {34, 2, 3}},
{{{32, 0, 1}, MaterialId::DoorClosed}, {{30, 0, 1}, MaterialId::Stone}});
const auto closed = prepare(region);
hit(trace(*closed, {34, .5, 1.5}, {-1, 0, 0}), {32, 0, 1}, {1, 0, 0});
edit(region, {32, 0, 1}, MaterialId::DoorOpen);
const auto open = prepare(region);
require(closed->faces().size() == 12 && open->faces().size() == 6);
hit(trace(*open, {34, .5, 1.5}, {-1, 0, 0}), {30, 0, 1}, {1, 0, 0});
hit(trace(*closed, {34, .5, 1.5}, {-1, 0, 0}), {32, 0, 1}, {1, 0, 0});
}
Test VoxelSceneTests::exact_plane_edge_and_corner_ties_are_directional() {
const auto region = loaded({{-2, -2, -2}, {2, 2, 2}},
{{{0, 0, 0}, MaterialId::Stone}, {{-1, -1, -1}, MaterialId::Soil},
{{-1, -1, 0}, MaterialId::Stone}});
const auto scene = prepare(region);
hit(trace(*scene, {0, .5, .5}, {1, 0, 0}), {0, 0, 0}, {-1, 0, 0});
require(trace(*scene, {0, .5, .5}, {-1, 0, 0}).status == VoxelPickStatus::Miss);
hit(trace(*scene, {0, 0, 0}, {1, 1, 1}), {0, 0, 0}, {-1, 0, 0});
hit(trace(*scene, {0, 0, 0}, {-1, -1, -1}), {-1, -1, -1}, {1, 0, 0});
hit(trace(*scene, {1.5, 1.5, 1.5}, {-1, -1, -1}), {0, 0, 0}, {1, 0, 0});
hit(trace(*scene, {1.5, 1.5, .5}, {-1, -1, 0}), {0, 0, 0}, {1, 0, 0});
const auto edge_only = prepare(loaded({{-2, -2, 0}, {2, 2, 1}},
{{{-1, 0, 0}, MaterialId::Stone}, {{0, -1, 0}, MaterialId::Stone}}));
require(trace(*edge_only, {1.5, 1.5, .5}, {-1, -1, 0}).status == VoxelPickStatus::Miss,
"diagonal ray hit a voxel touched only along an edge");
require(trace(*edge_only, {-.5, -1.5, .5}, {1, 3, 0}).status == VoxelPickStatus::Miss,
"normalizing a 1:3 ray split an exact corner crossing");
hit(trace(*scene, {-.5, -1.5, .5}, {1, 3, 0}), {-1, -1, 0}, {0, -1, 0});
}
Test VoxelSceneTests::axis_rays_inside_parallel_and_misses() {
const auto scene = prepare(loaded({{-2, -2, -2}, {3, 3, 3}}, {{{0, 0, 0}, MaterialId::Stone}}));
const std::array origins{VoxelPoint{-3, .5, .5}, VoxelPoint{4, .5, .5}, VoxelPoint{.5, -3, .5},
VoxelPoint{.5, 4, .5}, VoxelPoint{.5, .5, -3}, VoxelPoint{.5, .5, 4}};
const std::array directions{VoxelPoint{1, 0, 0}, VoxelPoint{-1, 0, 0}, VoxelPoint{0, 1, 0},
VoxelPoint{0, -1, 0}, VoxelPoint{0, 0, 1}, VoxelPoint{0, 0, -1}};
const std::array normals{VoxelPosition{-1, 0, 0}, VoxelPosition{1, 0, 0}, VoxelPosition{0, -1, 0},
VoxelPosition{0, 1, 0}, VoxelPosition{0, 0, -1}, VoxelPosition{0, 0, 1}};
for (std::size_t i = 0; i < origins.size(); ++i) {
const auto picked = trace(*scene, origins[i], directions[i]);
hit(picked, {0, 0, 0}, normals[i]);
require(picked.adjacent == normals[i] && picked.distance == 3);
}
const auto inside = trace(*scene, {.5, .5, .5}, {1, 0, 0});
require(inside.status == VoxelPickStatus::Inside && inside.distance == 0 &&
inside.normal == VoxelPosition{} && !inside.adjacent);
require(trace(*scene, {-3, 3, .5}, {1, 0, 0}).status == VoxelPickStatus::Miss);
require(trace(*scene, {-3, .5, .5}, {1, 0, 0}, 2.9).status == VoxelPickStatus::Miss);
hit(trace(*scene, {-3, .5, .5}, {1, 0, 0}, 3), {0, 0, 0}, {-1, 0, 0});
}
Test VoxelSceneTests::bounded_rays_and_nonfinite_inputs_are_refused() {
const auto scene = prepare(loaded({{-2, 0, 0}, {4, 1, 1}}, {{{3, 0, 0}, MaterialId::Stone}}));
error(trace_voxels(*scene, {{-3, .5, .5}, {1, 0, 0}, 20}, {2, 10}), VoxelSceneError::LimitExceeded);
error(trace_voxels(*scene, {{-3, .5, .5}, {1, 0, 0}, 20}, {20, 1}), VoxelSceneError::LimitExceeded);
error(trace_voxels(*scene, {{0, .5, .5}, {}, 20}), VoxelSceneError::InvalidInput);
error(trace_voxels(*scene, {{0, .5, .5}, {1, 0, 0}, -1}), VoxelSceneError::InvalidInput);
const auto nan = std::numeric_limits<double>::quiet_NaN(), inf = std::numeric_limits<double>::infinity();
error(trace_voxels(*scene, {{nan, 0, 0}, {1, 0, 0}, 20}), VoxelSceneError::InvalidInput);
error(trace_voxels(*scene, {{0, 0, 0}, {inf, 0, 0}, 20}), VoxelSceneError::InvalidInput);
error(trace_voxels(*scene, {{0, 0, 0}, {1, 0, 0}, inf}), VoxelSceneError::InvalidInput);
}
Test VoxelSceneTests::signed_extremes_use_checked_adjacent_cells() {
for (auto value : {smallest, largest}) {
const std::int64_t first = value == smallest ? value : std::int64_t{value} - 1;
const auto scene = prepare(loaded({{first, first, first}, {first + 2, first + 2, first + 2}},
{{{value, value, value}, MaterialId::Stone}}));
const double v = value;
const auto origin = value == smallest ? VoxelPoint{v - 1, v + .5, v + .5} : VoxelPoint{v + 2, v + .5, v + .5};
const auto direction = value == smallest ? VoxelPoint{1, 0, 0} : VoxelPoint{-1, 0, 0};
const VoxelPosition normal{value == smallest ? -1 : 1, 0, 0};
const auto pick = trace(*scene, origin, direction);
hit(pick, {value, value, value}, normal);
require(!pick.adjacent, "adjacent cell overflowed a signed coordinate");
require(scene->faces().size() == 6);
}
}
Test VoxelSceneTests::generation_budgets_fail_before_publishing_replacement() {
const auto region = loaded({{0, 0, 0}, {2, 2, 2}}, {{{0, 0, 0}, MaterialId::Stone}});
const auto held = prepare(region);
auto options = held->options();
options.limits.max_cells = 7;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
options = held->options(); options.limits.max_faces = 5;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
options = held->options(); options.limits.max_read_chunks = 0;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
options = held->options(); options.limits.max_bytes = 1;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
options = held->options(); options.limits.max_axis = 1;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
options = held->options(); options.bounds.lower.x = -1;
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::InvalidInput);
require(held->current(region, epoch()) && held->faces().size() == 6);
}
Test VoxelSceneTests::projection_and_pick_share_camera_and_slice() {
const auto scene = prepare(loaded({{-3, -3, -2}, {4, 4, 4}},
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::Soil}}), 0);
for (double scale : {.65, 1., 2.5, 4.}) {
const VoxelCamera camera{800, 600, 400.25, 300.75, scale};
const auto point = project_voxel_point(*scene, camera, {.5, .5, 1});
require(point.has_value());
const auto pick = pick_voxel_screen(*scene, camera, *point);
require(pick.has_value());
hit(*pick, {0, 0, 0}, {0, 0, 1});
}
VoxelCamera camera{800, 600, 400, 300, 1};
error(pick_voxel_screen(*scene, camera, {800, 0}), VoxelSceneError::InvalidInput);
error(pick_voxel_screen(*scene, camera, {0, -1}), VoxelSceneError::InvalidInput);
camera.scale = 0;
require(!valid_voxel_camera(camera) && !project_voxel_point(*scene, camera, {.5, .5, 1}));
}
Test VoxelSceneTests::generated_signed_terrain_is_meshed_and_drawn() {
const VoxelBounds bounds{{-34, -2, -12}, {34, 2, 12}};
VoxelRegion region({7, 42, voxel_generator_version, bounds});
std::vector<PreparedVoxelChunk> pages;
for (int z = -1; z <= 0; ++z) for (int y = -1; y <= 0; ++y) {
for (int x = -2; x <= 1; ++x) {
const auto candidate = region.prepare_generated({x, y, z});
require(candidate.has_value());
pages.push_back(*candidate);
}
}
require(region.activate(pages).has_value());
const auto scene = prepare(region);
require(scene->reads().size() == 16 && !scene->faces().empty());
const auto top = [&](int x, int y) {
for (int z = 11; z >= -12; --z) {
if (voxel_blocks_passage(region.sample({x, y, z}).material)) return z;
}
throw std::runtime_error("generated column lacks solid terrain");
};
for (int x : {-33, -32, -1, 0, 31, 32, 33}) {
const int z = top(x, 1);
hit(trace(*scene, {x + .5, 1.5, 13}, {0, 0, -1}), {x, 1, z}, {0, 0, 1});
require(has_face(*scene, {x, 1, z}, {0, 0, 1}));
}
const auto geometry = D3DScene::prepare_voxels(scene);
require(geometry.has_value());
D3DScene renderer;
require(renderer.initialize(nullptr, true));
const VoxelCamera camera{1280, 800, 200, 200, 1};
const int z = top(33, 1);
pixel_probe(renderer, *geometry, *scene, camera, {33.5, 1.5, z + 1.}, {33, 1, z}, {0, 0, 1});
const auto missed = pick_voxel_screen(*scene, camera, {20.5, 20.5});
require(missed && missed->status == VoxelPickStatus::Miss);
std::vector<std::uint32_t> pixels;
require(renderer.render(*geometry, camera, &pixels));
require(pixels[20 * camera.width + 20] == pixels.front(), "missed ray has terrain pixels");
const auto point = project_voxel_point(*scene, camera, {33.5, 1.5, z + 1.});
require(point.has_value());
error(pick_voxel_screen(*scene, camera, *point, {0, 1024}), VoxelSceneError::LimitExceeded);
auto refused = scene->options();
refused.limits.max_faces = scene->faces().size() - 1;
error(prepare_voxel_scene(region, epoch(), refused), VoxelSceneError::LimitExceeded);
pixel_probe(renderer, *geometry, *scene, camera, {33.5, 1.5, z + 1.}, {33, 1, z}, {0, 0, 1});
require(renderer.uploads() == 1, "refusal replaced the retained GPU geometry");
std::cout << "WARP generated signed terrain: 6528 cells, 16 consulted pages, " << scene->faces().size()
<< " faces, " << scene->faces().size() * 6 << " vertices; miss and budget refusal preserve displayed packet\n";
}
Test VoxelSceneTests::warp_pixels_match_faces_pan_zoom_and_retained_geometry() {
auto region = loaded({{-2, -2, -2}, {3, 3, 3}}, {{{0, 0, 0}, MaterialId::Stone}});
const auto scene = prepare(region);
const auto geometry = D3DScene::prepare_voxels(scene);
require(geometry.has_value());
D3DScene renderer;
require(renderer.initialize(nullptr, true), "WARP device unavailable");
VoxelCamera camera{640, 480, 320, 230, 3};
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
pixel_probe(renderer, *geometry, *scene, camera, {1, .5, .5}, {0, 0, 0}, {1, 0, 0});
pixel_probe(renderer, *geometry, *scene, camera, {.5, 1, .5}, {0, 0, 0}, {0, 1, 0});
camera.origin_x += 31; camera.origin_y -= 17; camera.scale = 2;
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
require(renderer.uploads() == 1, "camera-only render uploaded geometry again");
edit(region, {0, 0, 0}, MaterialId::Soil);
const auto changed = prepare(region);
const auto next_geometry = D3DScene::prepare_voxels(changed);
require(next_geometry.has_value());
pixel_probe(renderer, *next_geometry, *changed, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
require(renderer.uploads() == 3, "return to immutable old packet did not upload it");
renderer.reset();
require(renderer.initialize(nullptr, true));
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
require(renderer.uploads() == 4);
std::cout << "WARP terrain: 6 faces, 36 vertices; top/+X/+Y pixel probes, pan/zoom, old packet and reset passed\n";
}
Test VoxelSceneTests::warp_slice_and_open_door_match_picks() {
auto region = loaded({{-2, -2, -1}, {3, 3, 4}},
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::DoorClosed},
{{0, 0, 2}, MaterialId::Soil}, {{-1, -1, 0}, MaterialId::Stone}});
const auto complete = prepare(region), cut = prepare(region, 1);
const auto complete_geometry = D3DScene::prepare_voxels(complete), cut_geometry = D3DScene::prepare_voxels(cut);
require(complete_geometry.has_value() && cut_geometry.has_value());
D3DScene renderer;
require(renderer.initialize(nullptr, true));
const VoxelCamera camera{640, 480, 320, 280, 4};
pixel_probe(renderer, *complete_geometry, *complete, camera, {.5, .5, 3}, {0, 0, 2}, {0, 0, 1});
pixel_probe(renderer, *cut_geometry, *cut, camera, {.5, .5, 2}, {0, 0, 1}, {0, 0, 1});
pixel_probe(renderer, *cut_geometry, *cut, camera, {1, .5, 1.5}, {0, 0, 1}, {1, 0, 0});
edit(region, {0, 0, 1}, MaterialId::DoorOpen);
const auto open = prepare(region, 1);
const auto open_geometry = D3DScene::prepare_voxels(open);
require(open_geometry.has_value());
pixel_probe(renderer, *open_geometry, *open, camera, {1, .5, 1.5}, {-1, -1, 0}, {1, 0, 0});
pixel_probe(renderer, *cut_geometry, *cut, camera, {1, .5, 1.5}, {0, 0, 1}, {1, 0, 0});
std::cout << "WARP cutaway: inclusive roof/door slices and open aperture select the actual farther stone pixel\n";
}
Test VoxelSceneTests::warp_extreme_coordinates_missing_and_empty_scenes() {
D3DScene renderer;
require(renderer.initialize(nullptr, true));
const VoxelCamera camera{640, 480, 320, 280, 4};
for (auto value : {smallest, largest}) {
const std::int64_t first = value == smallest ? value : std::int64_t{value} - 1;
const auto scene = prepare(loaded({{first, first, first}, {first + 2, first + 2, first + 2}},
{{{value, value, value}, MaterialId::Stone}}));
const auto geometry = D3DScene::prepare_voxels(scene);
require(geometry.has_value());
const double v = value;
pixel_probe(renderer, *geometry, *scene, camera, {v + .5, v + .5, v + 1}, {value, value, value}, {0, 0, 1});
}
VoxelRegion unknown({7, 42, voxel_generator_version, {{0, 0, 0}, {1, 1, 1}}});
const auto scene = prepare(unknown);
const auto geometry = D3DScene::prepare_voxels(scene);
require(geometry.has_value());
const auto point = project_voxel_point(*scene, camera, {.5, .5, 1});
require(point.has_value());
const auto pick = pick_voxel_screen(*scene, camera, *point);
require(pick && pick->status == VoxelPickStatus::Unavailable);
std::vector<std::uint32_t> pixels;
require(renderer.render(*geometry, camera, &pixels));
const auto index = static_cast<std::size_t>(std::floor(point->y)) * camera.width + static_cast<std::size_t>(std::floor(point->x));
require((pixels[index] & 0xffffffu) == voxel_face_color({{0, 0, 0}, {0, 0, 1}, MaterialId::Air, true}));
const auto empty_scene = prepare(unknown, -1);
const auto empty_geometry = D3DScene::prepare_voxels(empty_scene);
require(empty_geometry.has_value());
require(renderer.render(*empty_geometry, camera, &pixels), "empty terrain draw failed");
require(std::ranges::all_of(pixels, [&](auto pixel) { return pixel == pixels.front(); }));
const auto miss = pick_voxel_screen(*empty_scene, camera, *point);
require(miss && miss->status == VoxelPickStatus::Miss);
require(renderer.render(*geometry, camera));
std::cout << "WARP terrain: INT32_MIN/INT32_MAX local coordinates, unknown occlusion, empty slice passed\n";
}
} // namespace