Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15887d5613 | ||
|
|
51311ca104 | ||
|
|
69ce32c2b6 | ||
|
|
cd75eab191 | ||
|
|
f60375a9f3 | ||
|
|
5dd0e35093 | ||
|
|
77781a5f1f | ||
|
|
22420e9fe2 | ||
|
|
89bbb81317 | ||
|
|
ba00651b45 |
No files matched your search
+3
-16
@@ -50,7 +50,6 @@ add_library(settlement_core
|
||||
engine/src/save_service_win32.cpp
|
||||
engine/src/simulation_runtime.cpp
|
||||
engine/src/worker_pool.cpp
|
||||
engine/src/voxel_region.cpp
|
||||
engine/src/world.cpp
|
||||
engine/src/world_save.cpp
|
||||
)
|
||||
@@ -95,22 +94,17 @@ 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 settlement_voxel_scene user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan 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)
|
||||
@@ -143,7 +137,6 @@ if(BUILD_TESTING)
|
||||
tests/save_service_tests.cpp
|
||||
tests/session_tests.cpp
|
||||
tests/snapshot_tests.cpp
|
||||
tests/voxel_region_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
@@ -155,7 +148,7 @@ if(BUILD_TESTING)
|
||||
|
||||
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
|
||||
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan
|
||||
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
|
||||
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
|
||||
@@ -166,14 +159,8 @@ if(BUILD_TESTING)
|
||||
|
||||
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
|
||||
target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan
|
||||
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()
|
||||
+7
-78
@@ -11,8 +11,6 @@
|
||||
#include <cstring>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
@@ -470,8 +468,6 @@ 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; };
|
||||
@@ -481,8 +477,7 @@ 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,
|
||||
depthParameters.x - (p.x + p.y + p.z * 1.5) * depthParameters.y, 1.0);
|
||||
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
|
||||
result.color = input.color;
|
||||
return result;
|
||||
}
|
||||
@@ -494,8 +489,6 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
|
||||
class PreparedGeometry {
|
||||
public:
|
||||
Mesh mesh;
|
||||
std::shared_ptr<const VoxelScene> voxel_scene;
|
||||
float depth_bias = .96f, depth_scale = .009f;
|
||||
};
|
||||
|
||||
struct D3DScene::Backend {
|
||||
@@ -546,28 +539,21 @@ struct D3DScene::Backend {
|
||||
}
|
||||
|
||||
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, &replacement))) return false;
|
||||
destination = replacement.Get();
|
||||
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
|
||||
buffer_bytes = desc.ByteWidth;
|
||||
}
|
||||
D3D11_MAPPED_SUBRESOURCE mapped{};
|
||||
if (FAILED(context->Map(destination, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
|
||||
context->Unmap(destination, 0);
|
||||
if (replacement) {
|
||||
geometry = std::move(replacement);
|
||||
buffer_bytes = static_cast<UINT>(bytes);
|
||||
}
|
||||
context->Unmap(geometry.Get(), 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -635,7 +621,7 @@ bool D3DScene::initialize(HWND target, bool software) {
|
||||
raster.CullMode = D3D11_CULL_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
D3D11_BUFFER_DESC constants{};
|
||||
constants.ByteWidth = 48;
|
||||
constants.ByteWidth = 32;
|
||||
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
|
||||
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
|
||||
vertex->GetBufferSize(), &graphics->layout)) ||
|
||||
@@ -670,62 +656,6 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
|
||||
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
|
||||
@@ -749,8 +679,7 @@ bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const Sc
|
||||
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,
|
||||
geometry->depth_bias, geometry->depth_scale, 0, 0};
|
||||
viewport.Width, viewport.Height, view.scale, 0};
|
||||
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
|
||||
constexpr UINT stride = sizeof(Vertex);
|
||||
constexpr UINT offset = 0;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -56,10 +55,6 @@ public:
|
||||
[[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;
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
#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
|
||||
@@ -1,113 +0,0 @@
|
||||
#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
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Текущий план разработки расположен в [PLAN.md](../../PLAN.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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -1,48 +0,0 @@
|
||||
# Review finite voxel region contracts before implementation
|
||||
|
||||
Task ID: M02-F1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Read-only preflight of M02-P1 initial design from actual 455630f M02 worktree. The signed 32³ sparse page foundation is independent of M01 custody 539cea0 now in progress. Existing renderer already uses z as vertical height via x−y, (x+y)−z and existing viewer picks the z=0 plane. Library first M02-R1 confirmed pin 7b0fea6, upstream #11 signed division and #14 sparse atomic edits, #12 ray traversal, #13 revision readsets, #10 RNG; actual public math/binary/hash available.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently decide whether bounded S02 geometry/generation contract is safe to implement now. Review the later S03/normal runtime/save/presentation boundaries insofar as they constrain S02 data. Send foundation verdict early; root may later supply planner final addendum.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only M02 correctness preflight with first S02 slice priority. No implementation, release/PR acceptance, M03+ design or approval of unchecked future code.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real M02 worktree docs/agent-workflow/tasks/M02-P1.md, M02-R1 and plans M02/S02/S03/S15/S17/S18, void-library.md; root existing world.hpp, world.cpp WorldState::capture, worker_pool, world_save and checkpoint, app/map_camera.hpp, d3d_scene_win32.cpp shader, viewer_win32.cpp pick_grid, first_colony and actual tests; private current15 in /tmp/stoneheart-milestones.xprJ2SVp/combined-custody. Inspect exact graph root only if relevant; direct sibling sources required.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switching, user contact or children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Attack proposed NEW VoxelRegion/value view with nonzero RegionId, int32 voxel xyz, finite half-open bounds, ordered key directory/sharing immutable 32³ pages, generator keyed by exact seed+version+absolute xyz, queries separate outside/unloaded/loaded air. Page publication precedes ready only at logical designated step. Edits validate all expected revisions/bounds/materials/caps/unsupported operations, finite canonical order and no partial mutation, publish touched revisions once and invalidate face neighbors without fictitious content changes. Focus on material id stability, thin bounds intersecting pages and border operations. Query correctness at both signed extremes and boundary examples, no pointer/reference mutation. Check which exact domain is expected to be represented.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Review ownership/constructor/geometry exposure, immutable page pointers vs mutable alias to page/cache/directory, exact all-or-nothing publication, result visibility/cache invalidation incl reads of inactive/neighbors, validity of one stable geometry revision for render and path when head changes due to activation/deactivation. Propose minimal interfaces and stable tests without duplicating future WorldState. Check D3D renderer z-up and slice/face tie contract.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Foundation worker has isolated file ownership in NEW voxel_region.hpp/cpp/test plus CMake and S02 docs. World/runtime/save protocol integrating with S15/16 requires final agreed schema and cannot clobber S06 custody15. Preserve protocol11 by explicit representability; original 2D first colony must remain readable/playable.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative division at INT_MIN and max half-open bounds, dirty neighbor overflow at extreme chunk ids, seed sign/ordering/algorithm version, bounded page/batch memory and worst-case old snapshot retention, revision rollover/admission, no-op/duplicates/conflicting expectations; negative/zero ray incl edge tie, stale auth, work/tick exposure, failed chunk activation/crossing. Differentiate genre policies/materials and requested Void issues.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or BLOCKED with precise mandatory first-slice fixes and testable criteria. 2. State if parallel independent implementation is sound within compiled M02 base before M01 finished. 3. Capture edge behavior and feasible tests for generation, bounds, stale atomic recompute, immutable view, deterministic batch and subsequent consumers. 4. Mark unknown physical target verification. Do not review a future code diff prematurely.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse and source refs in the M02 and combined worktrees. Compare pinned source with M02-R1 and note no binary evidence unless reading actual existing logs. Project index root-only; direct reads for sibling files. Later CTest should use exact Windows x64 GCC16/Wine test setup in M02-P1.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No approval of M01 scope or M02 implementation, no code, no Git/Gitea changes/children. If a substantial missing contract is identifiable, provide counterexample and precise remedy without tacking on speculative features.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested end-to-end milestone implementation and library gap filing. Preflight gates first edits, not engineering judgment on reversible local choices. Root integrates findings into worker specs and owns upstream effects.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-F1 preflight with earliest foundation assessment then notes for remaining consumers, actual source references, required tests and stop conditions for implementation.
|
||||
@@ -1,48 +0,0 @@
|
||||
# Design the first playable editable voxel region and its integration
|
||||
|
||||
Task ID: M02-P1
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
The user approved implementing M00–M12 on milestone and system branches. M01 currently provides a 50 ms authoritative World, immutable snapshots, authenticated commands, released rules profiles, protocol11 and modern checkpoints. M02 worktree at 455630f has S17 immutable frames and S21 real scheduler tests. Local M01 candidate 539cea0 adds modern raw15/checkpoint3 transfer persistence. An independent pin/API audit M02-R1 at Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 found library gaps reported as Void/Library #10–14. This is a preparatory design while M01 exit evidence is in flight.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide actionable dependency boundaries for M02 and the first implementable S02 region/chunk/component that can be built now without conflicting with M01 custody work. Continue to cover S03, S17/S18, S15 and normal owner/runtime end to end so the first terrain output has real consumers.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only milestone architecture and phased, playable acceptance. Focus limited M02 editable voxel scenario through two levels and chunk edge. Defer M03 colony storage/building changes, water, other worlds, plugin changes and release. No arbitrary lowering of approved roadmap scope or new UI product choice.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M01.md and M02.md; docs/plan/systems/{S02,S03,S15,S17,S18,S21}.md, docs/plan/void-library.md and M02-R1; engine/include/settlement/core/{world,simulation_runtime,command_dispatcher,worker_pool,deterministic_rng}.hpp and world/first_colony/world_save CPU paths; app/d3d_scene_win32.*, map_camera.hpp, viewer_win32.cpp, tests/frame/replay/identity/checkpoint. Use actual names in results. Read sibling custody.hpp and checkpoint.hpp at combined 539cea0 to avoid schema collision. No fetching private data outside project.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No edits, branch/remote ops, builds that modify worktrees, project switch or children. Parent persists results. Root and sibling agents are working in separate checkouts. For isolated M02 use direct files and avoid changing shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map owner/tick/frame/file architecture, deterministic generation keyed by signed world location, gates for snapshots/cache and async activation. Specify finite 32³ sparse page representation and signed Euclidean division, fatal and retriable edit paths, exact row/coordinate order, native Win32 interaction scenario, known old-save/old-LAN behavior and how these can be tested using real consumers. Identify the first S02 slice that can receive an independent concrete coding contract at once; send it early.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Propose NEW clear types and methods by responsibility with essentials only: region identities/int coords with z up, bounds/limits, material query/source/support+edit revision set and undo on failure, copy-on-write pages immutable to snapshots, deterministic per-chunk source and edit overlay; S03 use cases incl stable ties, minimum profile/door/stairs and consulted revision sets incl misses and neighbors; ray/pick face from D3D Y-up conversion and actual commands; M02 persistent version/generator identity; reconcile normal M01 World lifecycle, actual public source/test consumers and authored test scenario. Distinguish proposed APIs from existing ones.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root reconciles M02-R1, planner, independent preflight and starts S02 in an isolated branch before coupling to mutable M01 sources when safe. Make ownership/dependency ordering and concrete integration points clear. Source-only private S06/S15 candidates must never be treated as published.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound coordinate overflow (INT_MIN, ±32), sparse memory and checked edit count, stale/mixed revisions, border invalidation, optimistic deterministic admission/queued jobs, signed normal/cell at equally crossed faces, old saves and LAN projections of edited maps, delayed/out-of-order and corrupted chunk I/O, camera/view consistency and finite scheduling. Respect pinned Void API/tests and replacement cases for #10–14 in repository matrix.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Concrete HOW/WHAT for S02 first worker including new files/headers/CMake and behavioral tests with cross-boundary negative coordinates, immutable snapshots, failed multi-page edit and independent generation. 2. Bounded follow-on packages S03, authoritative/edit/tick+save, real UI and exit verification with actual dependencies. 3. Identify genuine missing library contract only after checking pin and issues. 4. Normal small scenario is visible, editable, traversable and survives save/restore across thread order.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git -C <m02> rev-parse HEAD/status/diff and git -C /tmp/stoneheart-milestones.xprJ2SVp/combined-custody show as needed; use direct source in sibling worktrees. Give real proposed CMake GCC16 cross and CTest commands for later workers based on /tmp/stoneheart-verify.KoZwE4o8/env.sh and existing target. Native Windows cannot be asserted from Wine.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop and report if a required product choice truly blocks first slice; use reversible decisions matching approved M02 otherwise. No source mutation, speculative library ticket, user messages, or children. Do not claim test execution.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User explicitly asks to implement all milestones, reuse library APIs and file concrete gaps. Root owns all side effects. User authorization already covers bounded M02 foundation and branch/MRs.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-P1 PLAN with early immediately implementable S02 slice, dependency order/ownership, immutable contracts, concrete tests/risks/source refs and remaining evidence. No approval or merge decisions.
|
||||
@@ -1,50 +0,0 @@
|
||||
# Implement immutable finite voxel regions and atomic multi-chunk edits
|
||||
|
||||
Task ID: S02-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s02-voxel-world at 0d71bcf, parent milestone/m02-voxel-world. M02-P1 plan and F1 independently accepted first slice. Existing first colony WorldState copied on capture and flat terrain remains, renderer z-up. Cross-toolchain CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Void Math::Numeric checked arithmetic, Binary::Writer and Hash public, signed split/atomic pages absent and tracked upstream #11/#14. M01 final custody in isolated siblings, no overlapping source needed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build a tested, ready-to-integrate finite authoritative voxel region with deterministic versioned terrain, signed coords and immutable chunk pages, checked all-or-nothing multi-page edits and accurate surface invalidation. The first file consumers are S03 nav queries, S17 surfaces and M02 World/serializer/activation. Freeze a usable header early and send actual declarations to root.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only memory representation, generation, prepared page installation, querying and edits for the finite one-region M02 foundation. No unrelated RNG, terrain viewer, WorldState or format edits, S03 path solver, resource ledger, gameplay or network. Input/outcome types below are NEW and may be named idiomatically.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02 + S03, dependency matrix section M02 + actual pin headers/tests for Math/Numeric, Binary and Hash. Inspect world.hpp/world.cpp capture, default 2D semantics, actual 3D shader at app/d3d_scene_win32.cpp, CMake targets and registered Void::Testing suites. S06 / S15 provisional custody data unneeded. Read M02-P1/F1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: NEW engine/include/settlement/core/voxel_region.hpp; NEW engine/src/voxel_region.cpp; NEW tests/voxel_region_tests.cpp; CMakeLists.txt only two source/test entries; docs/plan/systems/S02.md
|
||||
Your isolated s02 checkout only. Others work in separate WTs, do not overwrite or revert their changes. No Git/remote operations, shared Serena switch, children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define checked nonzero uint64 RegionId, int32 xyz with z-up, int64 half-open endpoints verifying within [INT32_MIN,INT32_MAX+1], strictly positive volume per axis (finite coordinate bounds need not densely allocate), chunk/local split no -INT_MIN, x-fast 32³ index. Stable material identifiers air/soil/stone, configurable bounded resident pages (default256), edit count (default4096), and actual checked staging/result/directory sizes (default allow full bounded batch). Region copies or dedicated immutable views share complete directory/pages via const ownership; no retained mutable aliases or mutable raw span. Immutable generator candidate is keyed by metadata/coords, source initialized independent of job ordering, deterministic generator1 with plausible soil surface/stone below and canonical absolute-coordinate encoding via actual Void Binary/Hash, uses no shared RNG. Mask all cells outside partial region.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Ordinary query distinguishes outside bounds vs unavailable vs loaded air; returns stable coordinate/read stamp matching caller lifetime. Separate pure generation/preparation from explicit all-or-nothing publication so later M02 owner controls logical tick. Region may not install result from a different region/seed/generator/coordinate or expired expectation. Keep page/availability paths usable by future persistence. A bounded atomic edit requires exact revision expectations for each touched chunk (including no-op), rejects duplicate cells, unsupported material/coords/bad expectations before publishing. Empty/all-identical edit has no changes. Sort changed cells/pages and actual neighbor invalidations canonically; increment once per truly changed page, unchanged neighbors keep material stamp, loading must be observable by dependencies. Extreme revision denies change before first effect. No need for unload until a later consumer, if implemented prevent ABA with persistent stamp. Define what finite bounds/unavailable neighbor contributes to dirty key.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Host only builds Windows; unit checks linked in actual settlement_core_tests. Root merges S02 into M02 and cumulative only after review. Need write stable header before dependent S03/S17 and alert parent if implementation materially changes contract. Other workers own old World/codec/camera, never edit those. Local implementation explicitly references Void/Library #11/#14 in S02 docs with exact replacement tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Widen origins, local indexes and neighbor math before conversion; avoid INT overflow/padding/endian and unbounded directory/grid construction. Bound working + staging memory before allocations and reject insufficient limits unchanged. Stage all pages and result list before final nonthrowing swap; preserve original content/pointer/revision on bad batch, allocation failure and MAX counter. External retained snapshots own memory separately, state its limit precisely. Prefer compact materials and deterministic column generation; full active 256 pages must not cause unrelated pages to be recopied on each edit. No nondeterministic unordered serialization or generation.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Exact split/join and x-fast indices at INT_MIN,−33,−32,−1,0,31,32,INT_MAX incl [max,max+1) and partial negative/extreme bounds. 2. Canonical full material content and revisions independent of forward/reverse/parallel preparation, real neighboring signed coordinate continuity/golden seed, precise different availability/air. 3. Two-page edit succeeds atomically and old view unchanged; stale second/unloaded/duplicate/unknown/budget/MAX fail unchanged, unchanged writes validate expectation and do not increment; correct face vs edge neighbor invalidation across boundaries. 4. No additional unlinked generic shim outside #11/#14; real release compilation and focused/full CTest, report actual footprint/copy behavior and evidence. 5. Document useful public operations in S02 and share frozen header.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run --tag voxel-region at your build, complete CTest -V (coordinate any real windows via root) and git diff --check; logs /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-*.log. Native Windows beyond cross tests not verified. Test revision exhaustion via meaningful persistence/import or narrow deterministic seam without exposing an unchecked arbitrary setter.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently expand M02 to full renderer/World or change prior save formats. If dependency contract missing, verify pin plus check existing issues, report exact consumer/guarantee and root handles any filing. Two unsuccessful same-cause fixes escalate with original contract/evidence. No publishing or other checkout edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system coding, Gitea PRs and true Void gaps. Root chose region identity and finite signed z-up cells, M02 product decisions in milestone doc; planner/preflight complete for this slice. Concrete bounded storage/container choices delegated.
|
||||
|
||||
## 14. Return format
|
||||
Return S02-01 READY or PARTIAL, early frozen API and relevant coordinate/frame assumptions, controlled failure cases, working paths, actual verification counts/measurements/limits and remaining integration seams.
|
||||
|
||||
The M02 door uses two stable non-generated cell kinds, `MaterialId::DoorClosed` and `MaterialId::DoorOpen`, appended after Air, Soil and Stone. A closed door blocks body clearance; an open door and air permit clearance. Only Soil and Stone provide standing support. Publish NEW `voxel_blocks_passage(MaterialId)` and `voxel_provides_support(MaterialId)` queries for the navigation and presentation owners. Both halves of a door can be changed in the same checked edit batch. Invalid materials remain rejected. The generator produces natural materials only, and the gameplay owner controls who may operate or mine a door. Add tests for these shared semantics, both updating over a page boundary if applicable, and tell root when the adjusted header is frozen. This prevents a second source of door geometry, occupancy and invalidation in navigation.
|
||||
@@ -1,48 +0,0 @@
|
||||
# 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.
|
||||
@@ -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)
|
||||
|
||||
## Первый переход с текущего клиента
|
||||
|
||||
### Потактный эталон прототипа
|
||||
|
||||
@@ -22,18 +22,6 @@
|
||||
|
||||
## Проверки и выход
|
||||
|
||||
### Контракты первой реализации
|
||||
|
||||
Воксели имеют знаковые 32-битные координаты, высота растёт по оси `z`. Границы конечного региона задаются полуинтервалами с 64-битными концами, чтобы в них можно было включить последний положительный воксель. Чанк содержит 32³ ячеек; быстрее всего меняется индекс `x`. Отдельные результаты чтения обозначают воздух, недоступный чанк и координату за пределами региона. Генератор получает версию, seed и абсолютные координаты. Порядок подготовки страниц не влияет на материал.
|
||||
|
||||
Снимок региона разделяет неизменяемые страницы. Операция проверяет все ожидаемые ревизии, размер и бюджет до публикации. Пустая операция или запись прежнего материала сохраняет ревизию после проверки ожиданий. Дублированная координата отклоняет весь запрос. Изменение на грани оповещает соседний чанк, сохраняя его собственную ревизию материала. Реализация и проверки замены библиотечным API связаны с задачами о [знаковых координатах](https://git.faumaray.com/Void/Library/issues/11), [транзакциях страниц](https://git.faumaray.com/Void/Library/issues/14) и [зависимостях по ревизиям](https://git.faumaray.com/Void/Library/issues/13).
|
||||
|
||||
Житель занимает одну клетку в плане и две по высоте, поднимается на одну ступень. Поиск учитывает опору, свободное место для головы, дверь и соседние чанки, включая чтения, из-за которых путь не найден. Перед очередным перемещением житель перепроверяет переход. Удаление следующей ступени сохраняет его собственную позицию, груз и цель. Поиск через ещё не подготовленный чанк либо за пределами бюджета имеет отдельный результат.
|
||||
|
||||
Добыча создаёт авторитетный заказ с доступной соседней рабочей позицией. При завершении мир заранее проверяет правку и возможность зачислить материал по правилам S06. Удаление грунта и передача добычи выполняются одной операцией. Если для добычи нет места, заказ ждёт с указанием причины. Повтор принятой команды находит исходный заказ. Режим тестовой колонии имеет собственный манифест с версией генератора и определениями материалов.
|
||||
|
||||
Координатор принимает подготовленные чанки на назначенной границе такта в порядке координат. Во время ожидания он обслуживает загрузку и завершение программы. В сохранение попадают требуемые чанки, назначения работ и безопасная позиция после правки. Прежние колонии сохраняют прежнюю геометрию на высоте ноль. Форматы нового региона согласуются с подтверждённой версией сохранений M01. Текущий шейдер уже проецирует высоту `z`; луч выбора и видимый срез должны пользоваться той же проекцией. [Проектирование](../../agent-workflow/tasks/M02-P1.md) · [Проверка контрактов](../../agent-workflow/tasks/M02-F1.md)
|
||||
|
||||
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
|
||||
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
|
||||
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
|
||||
|
||||
@@ -10,34 +10,6 @@
|
||||
|
||||
## Данные и ответственность
|
||||
|
||||
### Исполняемая основа ограниченного региона
|
||||
|
||||
`VoxelRegion` хранит ненулевой ID, seed, версию генератора и границы. Ячейки имеют знаковые координаты `int32`, а концы полуинтервалов используют `int64`, включая верхнюю границу `INT32_MAX + 1`. Деление на размер чанка округляет вниз, поэтому координата −1 попадает в чанк −1 и локальную ячейку 31. Индекс внутри страницы вычисляется как `x + 32 * (y + 32 * z)`. Результат `sample()` различает загруженный воздух, недоступную страницу и выход за границы. [Публичный контракт](../../../engine/include/settlement/core/voxel_region.hpp) · [Реализация](../../../engine/src/voxel_region.cpp)
|
||||
|
||||
Копия региона разделяет каталог и страницы через неизменяемые объекты. `directory()` возвращает владеющую ссылку на прежний каталог. Изменение создаёт новый каталог и копирует затронутые страницы. Срок жизни снимка охватывает все его материалы. Номер региона и `ChunkStamp` связывают чтение с состоянием доступности и ревизией страницы. Владелец мира дополнительно проверяет инкарнацию сеанса при загрузке партии.
|
||||
|
||||
`prepare_generated()` независимо готовит страницу генератора 1. Он кодирует seed, версию и координаты опорных столбцов в little-endian через `Void::Binary::Writer`, затем использует FNV-1a из `Void::Hash`. Интерполяция сетки с шагом 16 даёт высоты от −8 до 8. Верхние три слоя состоят из почвы, нижние — из камня. Соседние столбцы по горизонтальной оси отличаются по высоте максимум на одну ячейку. Область вне частичного чанка заполнена воздухом. Для seed 42 чанк (−1, −1, −1) имеет FNV-1a `13302332479434111011`; этот результат отдельно воспроизведён по закодированным полям. Подготовка не меняет каталог региона.
|
||||
|
||||
`prepare_restored()` проверяет полный размер страницы, ненулевую ревизию, материалы и воздух за границами, затем копирует данные вызывающего кода. `activate()` принимает весь набор подготовленных страниц одной операцией. Она проверяет точный дескриптор региона, дубликаты, бюджет и отсутствие уже опубликованной страницы. `edit()` проверяет ожидаемую ревизию каждой ячейки, даже если материал уже совпадает. Повтор координаты отклоняет весь запрос. Пустая и тождественная запись сохраняют ревизии. Исчерпанная ревизия запрещает изменение страницы. Все новые страницы, каталог и результат готовятся до публикации. При отказе прежние указатели, материалы и ревизии сохраняются.
|
||||
|
||||
Список изменённых чанков упорядочен по координатам `x,y,z`; список ячеек — по мировым координатам. Правка на грани добавляет пересекающего регион соседа в `dirty_chunks`. Это касается и недоступных соседей. Диагонали не включаются. Неизменившийся сосед сохраняет свою ревизию материала. Активация страницы оповещает все её соседние грани. Выгрузка страниц появится с отдельным контрактом сохранения их ревизий.
|
||||
|
||||
| Материал | Значение | Проход | Опора |
|
||||
| --- | --- | --- | --- |
|
||||
| Воздух | 0 | Свободен | Нет |
|
||||
| Почва | 1 | Занят | Есть |
|
||||
| Камень | 2 | Занят | Есть |
|
||||
| Закрытая дверь | 3 | Занят | Нет |
|
||||
| Открытая дверь | 4 | Свободен | Нет |
|
||||
|
||||
Навигация и изображение используют общие `voxel_blocks_passage()` и `voxel_provides_support()`. Генератор создаёт природные материалы. Игровая команда определяет право изменить дверь и обновляет обе её ячейки одной операцией, в том числе через границу страниц.
|
||||
|
||||
По умолчанию разрешены 256 страниц и 4096 ячеек в запросе. Лимиты полезных данных резидентного региона и одной транзакции равны 16 МиБ каждый. Проверяемая арифметика учитывает объекты страниц, каталог, сортируемый запрос, временную страницу и массивы результата до их выделения. На проверенной Windows x64-сборке страница занимает 32 776 байтов, запись каталога — 32 байта, каталог с 256 страницами — 8 398 872 байта. Служебные данные распределителя, подготовленные страницы и старые снимки, удерживаемые потребителями, имеют отдельный расход памяти. Будущий владелец ограничивает число таких потребителей.
|
||||
|
||||
Проверки `--tag voxel-region` покрывают отрицательные и предельные координаты, частичные страницы, порядок завершения настоящих задач на 2/6/12 исполнителях, границы двери, загрузку, точный отказ целого набора и неизменяемые снимки. На заполненном каталоге правка одной ячейки сохранила прежние 255 страниц. Отдельная программа по очереди вызвала отказ каждого выделения памяти при генерации, восстановлении, активации и правке двух страниц; все отказы сохранили прежний каталог. Переход на библиотечную реализацию должен повторить эти проверки. [Тесты региона](../../../tests/voxel_region_tests.cpp) · [Знаковая арифметика в VoidLibrary](https://git.faumaray.com/Void/Library/issues/11) · [Атомарные страницы в VoidLibrary](https://git.faumaray.com/Void/Library/issues/14)
|
||||
|
||||
Windows x64 Release с GCC 16.2 под Wine 11 прошла 14 проверок региона и весь CTest — 155 тестов ядра, 9 LAN, 14 клиента и испытание кадра с видимым D3D11 и WARP. В одном прогоне подготовка и активация 256 страниц заняли 57 917 мкс, правка одной ячейки — 11 мкс. Это измерение относится к данному прогону под Wine. Нативная Windows и аппаратная частота кадров ещё не проверены.
|
||||
|
||||
| Новый контракт | Содержимое и владелец |
|
||||
| --- | --- |
|
||||
| Позиция мира | Постоянный ID региона и знаковые целочисленные координаты вокселя. Вертикальная ось — `z`, горизонтальная плоскость — `x,y`. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# S17. D3D11-рендеринг, камера и визуальное состояние
|
||||
|
||||
Статус — 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)
|
||||
Статус — S17-W01 реализован и проверен в Windows x64/Wine; ожидает независимой приёмки. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
@@ -29,30 +29,6 @@ S17-W01 сохраняет существующую плоскую карту и
|
||||
|
||||
Общий примитив публикации остаётся связан с [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 сессии и инвалидирования соседних страниц. Форма клеток, материалы, дверной проём и включительный срез остаются игровыми правилами.
|
||||
|
||||
## Границы данных и потоков
|
||||
|
||||
Предлагаемый новый `PresentationSnapshot` содержит номер завершённого такта, экземпляр мира, постоянные идентификаторы видимых объектов, их позы и необходимые визуальные признаки. Геометрия чанка передаётся по идентификатору и ревизии. Каждый снимок неизменяем на всём сроке чтения. Ссылка рендера на изменяемый `World` заменяется чтением снимка.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
using RegionId = std::uint64_t;
|
||||
inline constexpr std::int32_t voxel_chunk_side = 32;
|
||||
inline constexpr std::size_t voxel_chunk_cells = 32 * 32 * 32;
|
||||
inline constexpr std::uint32_t voxel_generator_version = 1;
|
||||
|
||||
struct VoxelPosition {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const VoxelPosition&) const = default;
|
||||
};
|
||||
struct ChunkCoordinate {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const ChunkCoordinate&) const = default;
|
||||
};
|
||||
struct VoxelEndpoint {
|
||||
std::int64_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const VoxelEndpoint&) const = default;
|
||||
};
|
||||
struct VoxelBounds {
|
||||
VoxelEndpoint lower, upper;
|
||||
[[nodiscard]] bool contains(VoxelPosition position) const noexcept;
|
||||
bool operator==(const VoxelBounds&) const = default;
|
||||
};
|
||||
struct LocalVoxel {
|
||||
std::uint8_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const LocalVoxel&) const = default;
|
||||
};
|
||||
struct VoxelAddress {
|
||||
ChunkCoordinate chunk;
|
||||
LocalVoxel local;
|
||||
};
|
||||
|
||||
[[nodiscard]] VoxelAddress split_voxel(VoxelPosition position) noexcept;
|
||||
[[nodiscard]] std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept;
|
||||
[[nodiscard]] std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept;
|
||||
|
||||
enum class MaterialId : std::uint8_t { Air = 0, Soil = 1, Stone = 2, DoorClosed = 3, DoorOpen = 4 };
|
||||
[[nodiscard]] bool valid_voxel_material(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_blocks_passage(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_provides_support(MaterialId material) noexcept;
|
||||
|
||||
struct VoxelRegionDescriptor {
|
||||
RegionId id = 0;
|
||||
std::uint64_t seed = 0;
|
||||
std::uint32_t generator_version = voxel_generator_version;
|
||||
VoxelBounds bounds;
|
||||
bool operator==(const VoxelRegionDescriptor&) const = default;
|
||||
};
|
||||
struct VoxelLimits {
|
||||
std::size_t max_resident_chunks = 256;
|
||||
std::size_t max_edit_cells = 4096;
|
||||
// Budgets charge object and vector payloads. Allocator bookkeeping and
|
||||
// snapshots/prepared pages retained by the caller have separate lifetimes.
|
||||
std::size_t max_resident_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_transaction_bytes = 16 * 1024 * 1024;
|
||||
};
|
||||
enum class VoxelAvailability : std::uint8_t { Outside, Unavailable, Loaded };
|
||||
struct ChunkStamp {
|
||||
RegionId region = 0;
|
||||
ChunkCoordinate coordinate;
|
||||
VoxelAvailability availability = VoxelAvailability::Unavailable;
|
||||
std::uint64_t revision = 0;
|
||||
bool operator==(const ChunkStamp&) const = default;
|
||||
};
|
||||
struct VoxelSample {
|
||||
VoxelAvailability availability = VoxelAvailability::Outside;
|
||||
MaterialId material = MaterialId::Air;
|
||||
ChunkStamp stamp;
|
||||
};
|
||||
|
||||
class VoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
|
||||
[[nodiscard]] std::span<const MaterialId, voxel_chunk_cells> cells() const noexcept { return cells_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells);
|
||||
std::uint64_t revision_;
|
||||
std::array<MaterialId, voxel_chunk_cells> cells_;
|
||||
};
|
||||
struct VoxelChunkEntry {
|
||||
ChunkCoordinate coordinate;
|
||||
std::shared_ptr<const VoxelChunk> chunk;
|
||||
};
|
||||
using VoxelDirectory = std::vector<VoxelChunkEntry>;
|
||||
|
||||
class PreparedVoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] ChunkCoordinate coordinate() const noexcept { return coordinate_; }
|
||||
[[nodiscard]] const std::shared_ptr<const VoxelChunk>& chunk() const noexcept { return chunk_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk);
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
ChunkCoordinate coordinate_;
|
||||
std::shared_ptr<const VoxelChunk> chunk_;
|
||||
};
|
||||
|
||||
enum class VoxelError : std::uint8_t {
|
||||
InvalidCoordinate, InvalidMaterial, InvalidRevision, InvalidSource,
|
||||
Duplicate, Unavailable, Stale, RevisionExhausted, LimitExceeded, AllocationFailed
|
||||
};
|
||||
struct VoxelEdit {
|
||||
VoxelPosition position;
|
||||
MaterialId material = MaterialId::Air;
|
||||
std::uint64_t expected_revision = 0;
|
||||
};
|
||||
struct VoxelChange {
|
||||
VoxelPosition position;
|
||||
MaterialId before = MaterialId::Air;
|
||||
MaterialId after = MaterialId::Air;
|
||||
bool operator==(const VoxelChange&) const = default;
|
||||
};
|
||||
struct VoxelCommit {
|
||||
std::vector<ChunkStamp> changed_chunks;
|
||||
std::vector<VoxelChange> changed_cells;
|
||||
// Changed chunks and intersecting face-neighbors, including unavailable
|
||||
// neighbors. Unchanged neighbors keep their own material revision.
|
||||
std::vector<ChunkCoordinate> dirty_chunks;
|
||||
};
|
||||
|
||||
// Copies retain the complete immutable directory. A reader keeps its own copy
|
||||
// while the single owner publishes changes. Session identity fences snapshots
|
||||
// across save/load; this layer does not unload or reuse chunk revisions.
|
||||
class VoxelRegion {
|
||||
public:
|
||||
explicit VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits = {});
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] const VoxelLimits& limits() const noexcept { return limits_; }
|
||||
[[nodiscard]] std::shared_ptr<const VoxelDirectory> directory() const noexcept { return directory_; }
|
||||
[[nodiscard]] std::size_t resident_bytes() const noexcept;
|
||||
[[nodiscard]] bool intersects(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] ChunkStamp chunk_stamp(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] bool matches(const ChunkStamp& stamp) const noexcept;
|
||||
[[nodiscard]] VoxelSample sample(VoxelPosition position) const noexcept;
|
||||
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_generated(ChunkCoordinate coordinate) const;
|
||||
// Validated, deep-copied import for persistence, including exhausted valid
|
||||
// revisions. Cells outside a partial region must be canonical air.
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const;
|
||||
// Activation only accepts unavailable chunks from this exact descriptor.
|
||||
// Every candidate is installed together or the directory is preserved.
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> activate(std::span<const PreparedVoxelChunk> candidates);
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> edit(std::span<const VoxelEdit> edits);
|
||||
|
||||
private:
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
VoxelLimits limits_;
|
||||
std::shared_ptr<const VoxelDirectory> directory_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -1,383 +0,0 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
constexpr auto coordinate_min = std::int64_t{std::numeric_limits<std::int32_t>::min()};
|
||||
constexpr auto coordinate_end = std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1;
|
||||
|
||||
bool valid_interval(std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return lower >= coordinate_min && upper <= coordinate_end && lower < upper;
|
||||
}
|
||||
std::pair<std::int32_t, std::uint8_t> split_axis(std::int32_t value) noexcept {
|
||||
auto chunk = value / voxel_chunk_side;
|
||||
auto local = value % voxel_chunk_side;
|
||||
if (local < 0) {
|
||||
--chunk;
|
||||
local += voxel_chunk_side;
|
||||
}
|
||||
return {chunk, static_cast<std::uint8_t>(local)};
|
||||
}
|
||||
VoxelEndpoint chunk_origin(ChunkCoordinate coordinate) noexcept {
|
||||
return {std::int64_t{coordinate.x} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.y} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.z} * voxel_chunk_side};
|
||||
}
|
||||
bool overlapping_axis(std::int64_t origin, std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return origin < upper && origin + voxel_chunk_side > lower;
|
||||
}
|
||||
auto find_chunk(const VoxelDirectory& directory, ChunkCoordinate coordinate) noexcept {
|
||||
return std::lower_bound(directory.begin(), directory.end(), coordinate,
|
||||
[](const auto& entry, auto key) { return entry.coordinate < key; });
|
||||
}
|
||||
class PayloadBudget {
|
||||
public:
|
||||
explicit PayloadBudget(std::size_t limit) : remaining_(limit) {}
|
||||
bool take(std::size_t count, std::size_t size) noexcept {
|
||||
const auto bytes = Void::Numeric::checked_mul(count, size);
|
||||
if (!bytes || *bytes > remaining_) return false;
|
||||
remaining_ -= *bytes;
|
||||
return true;
|
||||
}
|
||||
private:
|
||||
std::size_t remaining_;
|
||||
};
|
||||
|
||||
std::uint64_t terrain_hash(std::uint64_t seed, std::int64_t x, std::int64_t y) {
|
||||
std::array<std::byte, 40> bytes{};
|
||||
Void::Binary::Writer writer(bytes);
|
||||
if (!writer.writeLittle(seed) || !writer.writeLittle(voxel_generator_version) ||
|
||||
!writer.writeLittle(std::uint32_t{1}) || !writer.writeLittle(x) ||
|
||||
!writer.writeLittle(y) || !writer.writeLittle(std::int64_t{0})) {
|
||||
throw std::logic_error("voxel generator field layout exceeds its fixed buffer");
|
||||
}
|
||||
return Void::Hash::fnv1a64(writer.written());
|
||||
}
|
||||
std::int64_t surface_height(std::uint64_t seed, std::int32_t x, std::int32_t y) {
|
||||
// Interpolate absolute lattice columns to keep adjacent heights within one
|
||||
// voxel. Widened lattice endpoints also cover the final int32 column.
|
||||
const auto lattice = [](std::int32_t value) {
|
||||
std::int64_t quotient = value / 16;
|
||||
if (value % 16 < 0) --quotient;
|
||||
return quotient * 16;
|
||||
};
|
||||
const auto x0 = lattice(x), y0 = lattice(y);
|
||||
const auto dx = std::int64_t{x} - x0, dy = std::int64_t{y} - y0;
|
||||
const auto height = [seed](std::int64_t a, std::int64_t b) {
|
||||
return static_cast<std::int64_t>(terrain_hash(seed, a, b) % 17) - 8;
|
||||
};
|
||||
const auto numerator = height(x0, y0) * (16 - dx) * (16 - dy) +
|
||||
height(x0 + 16, y0) * dx * (16 - dy) +
|
||||
height(x0, y0 + 16) * (16 - dx) * dy + height(x0 + 16, y0 + 16) * dx * dy;
|
||||
auto result = numerator / 256;
|
||||
if (numerator % 256 < 0) --result;
|
||||
return result;
|
||||
}
|
||||
void add_neighbor(const VoxelRegion& region, std::vector<ChunkCoordinate>& dirty,
|
||||
ChunkCoordinate coordinate, int axis, int delta) {
|
||||
std::array<std::int64_t, 3> values{coordinate.x, coordinate.y, coordinate.z};
|
||||
values[static_cast<std::size_t>(axis)] += delta;
|
||||
if (values[static_cast<std::size_t>(axis)] < coordinate_min ||
|
||||
values[static_cast<std::size_t>(axis)] >= coordinate_end) return;
|
||||
const ChunkCoordinate neighbor{static_cast<std::int32_t>(values[0]),
|
||||
static_cast<std::int32_t>(values[1]), static_cast<std::int32_t>(values[2])};
|
||||
if (region.intersects(neighbor)) dirty.push_back(neighbor);
|
||||
}
|
||||
void canonicalize(std::vector<ChunkCoordinate>& coordinates) {
|
||||
std::sort(coordinates.begin(), coordinates.end());
|
||||
coordinates.erase(std::unique(coordinates.begin(), coordinates.end()), coordinates.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool VoxelBounds::contains(VoxelPosition position) const noexcept {
|
||||
return position.x >= lower.x && position.x < upper.x &&
|
||||
position.y >= lower.y && position.y < upper.y &&
|
||||
position.z >= lower.z && position.z < upper.z;
|
||||
}
|
||||
VoxelAddress split_voxel(VoxelPosition position) noexcept {
|
||||
const auto [cx, lx] = split_axis(position.x);
|
||||
const auto [cy, ly] = split_axis(position.y);
|
||||
const auto [cz, lz] = split_axis(position.z);
|
||||
return {{cx, cy, cz}, {lx, ly, lz}};
|
||||
}
|
||||
std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept {
|
||||
if (local.x >= voxel_chunk_side || local.y >= voxel_chunk_side || local.z >= voxel_chunk_side) return {};
|
||||
return std::size_t{local.x} + 32 * (std::size_t{local.y} + 32 * std::size_t{local.z});
|
||||
}
|
||||
std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept {
|
||||
if (!voxel_index(local)) return {};
|
||||
const auto origin = chunk_origin(chunk);
|
||||
const auto x = origin.x + local.x, y = origin.y + local.y, z = origin.z + local.z;
|
||||
if (x < coordinate_min || x >= coordinate_end || y < coordinate_min || y >= coordinate_end ||
|
||||
z < coordinate_min || z >= coordinate_end) return {};
|
||||
return VoxelPosition{static_cast<std::int32_t>(x), static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
|
||||
}
|
||||
bool valid_voxel_material(MaterialId material) noexcept {
|
||||
return material >= MaterialId::Air && material <= MaterialId::DoorOpen;
|
||||
}
|
||||
bool voxel_blocks_passage(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone || material == MaterialId::DoorClosed;
|
||||
}
|
||||
bool voxel_provides_support(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone;
|
||||
}
|
||||
|
||||
VoxelChunk::VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells)
|
||||
: revision_(revision) {
|
||||
std::copy(cells.begin(), cells.end(), cells_.begin());
|
||||
}
|
||||
PreparedVoxelChunk::PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk)
|
||||
: descriptor_(descriptor), coordinate_(coordinate), chunk_(std::move(chunk)) {}
|
||||
|
||||
VoxelRegion::VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits)
|
||||
: descriptor_(descriptor), limits_(limits) {
|
||||
const auto& bounds = descriptor.bounds;
|
||||
if (!descriptor.id || descriptor.generator_version != voxel_generator_version ||
|
||||
!valid_interval(bounds.lower.x, bounds.upper.x) || !valid_interval(bounds.lower.y, bounds.upper.y) ||
|
||||
!valid_interval(bounds.lower.z, bounds.upper.z) || !limits.max_resident_chunks || !limits.max_edit_cells ||
|
||||
limits.max_resident_bytes < sizeof(VoxelDirectory) || !limits.max_transaction_bytes) {
|
||||
throw std::invalid_argument("invalid voxel region descriptor or limits");
|
||||
}
|
||||
directory_ = std::make_shared<const VoxelDirectory>();
|
||||
}
|
||||
std::size_t VoxelRegion::resident_bytes() const noexcept {
|
||||
return sizeof(VoxelDirectory) + directory_->size() * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk));
|
||||
}
|
||||
bool VoxelRegion::intersects(ChunkCoordinate coordinate) const noexcept {
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
const auto& bounds = descriptor_.bounds;
|
||||
return overlapping_axis(origin.x, bounds.lower.x, bounds.upper.x) &&
|
||||
overlapping_axis(origin.y, bounds.lower.y, bounds.upper.y) &&
|
||||
overlapping_axis(origin.z, bounds.lower.z, bounds.upper.z);
|
||||
}
|
||||
ChunkStamp VoxelRegion::chunk_stamp(ChunkCoordinate coordinate) const noexcept {
|
||||
ChunkStamp result{descriptor_.id, coordinate, VoxelAvailability::Outside, 0};
|
||||
if (!intersects(coordinate)) return result;
|
||||
const auto entry = find_chunk(*directory_, coordinate);
|
||||
result.availability = VoxelAvailability::Unavailable;
|
||||
if (entry != directory_->end() && entry->coordinate == coordinate) {
|
||||
result.availability = VoxelAvailability::Loaded;
|
||||
result.revision = entry->chunk->revision();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
bool VoxelRegion::matches(const ChunkStamp& stamp) const noexcept {
|
||||
return chunk_stamp(stamp.coordinate) == stamp;
|
||||
}
|
||||
VoxelSample VoxelRegion::sample(VoxelPosition position) const noexcept {
|
||||
const auto address = split_voxel(position);
|
||||
VoxelSample result{VoxelAvailability::Outside, MaterialId::Air, chunk_stamp(address.chunk)};
|
||||
if (!descriptor_.bounds.contains(position)) return result;
|
||||
result.availability = result.stamp.availability;
|
||||
if (result.availability == VoxelAvailability::Loaded) {
|
||||
result.material = find_chunk(*directory_, address.chunk)->chunk->cells()[*voxel_index(address.local)];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_generated(ChunkCoordinate coordinate) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
PayloadBudget budget(limits_.max_transaction_bytes);
|
||||
if (!budget.take(1, sizeof(VoxelChunk)) || !budget.take(voxel_chunk_cells, sizeof(MaterialId))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
std::array<MaterialId, voxel_chunk_cells> cells{};
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
for (std::int32_t y = 0; y < voxel_chunk_side; ++y) {
|
||||
for (std::int32_t x = 0; x < voxel_chunk_side; ++x) {
|
||||
const auto px = static_cast<std::int32_t>(origin.x + x);
|
||||
const auto py = static_cast<std::int32_t>(origin.y + y);
|
||||
const auto height = surface_height(descriptor_.seed, px, py);
|
||||
for (std::int32_t z = 0; z < voxel_chunk_side; ++z) {
|
||||
const VoxelPosition position{px, py, static_cast<std::int32_t>(origin.z + z)};
|
||||
if (!descriptor_.bounds.contains(position) || position.z > height) continue;
|
||||
const auto material = position.z > height - 3 ? MaterialId::Soil : MaterialId::Stone;
|
||||
const auto index = static_cast<std::size_t>(x + 32 * (y + 32 * z));
|
||||
cells[index] = material;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(1, cells));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (!revision) return std::unexpected(VoxelError::InvalidRevision);
|
||||
if (cells.size() != voxel_chunk_cells) return std::unexpected(VoxelError::InvalidSource);
|
||||
if (limits_.max_transaction_bytes < sizeof(VoxelChunk)) return std::unexpected(VoxelError::LimitExceeded);
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
if (!valid_voxel_material(cells[i])) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto position = join_voxel(coordinate,
|
||||
{static_cast<std::uint8_t>(i % 32), static_cast<std::uint8_t>((i / 32) % 32),
|
||||
static_cast<std::uint8_t>(i / 1024)});
|
||||
if (!position || (!descriptor_.bounds.contains(*position) && cells[i] != MaterialId::Air)) {
|
||||
return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const std::span<const MaterialId, voxel_chunk_cells> fixed(cells.data(), voxel_chunk_cells);
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, fixed));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::activate(std::span<const PreparedVoxelChunk> candidates) {
|
||||
if (candidates.empty()) return VoxelCommit{};
|
||||
if (candidates.size() > limits_.max_resident_chunks - directory_->size()) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
const auto count = directory_->size() + candidates.size();
|
||||
PayloadBudget resident(limits_.max_resident_bytes);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
const auto dirty_count = Void::Numeric::checked_mul(candidates.size(), std::size_t{7});
|
||||
if (!dirty_count || !resident.take(1, sizeof(VoxelDirectory)) ||
|
||||
!resident.take(count, sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) ||
|
||||
!staging.take(1, sizeof(VoxelDirectory)) || !staging.take(count, sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(candidates.size(), sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
auto next = std::make_shared<VoxelDirectory>();
|
||||
next->reserve(count);
|
||||
next->insert(next->end(), directory_->begin(), directory_->end());
|
||||
VoxelCommit result;
|
||||
result.changed_chunks.reserve(candidates.size());
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (const auto& candidate : candidates) {
|
||||
if (candidate.descriptor_ != descriptor_ || !candidate.chunk_ || !intersects(candidate.coordinate_)) {
|
||||
return std::unexpected(VoxelError::InvalidSource);
|
||||
}
|
||||
if (chunk_stamp(candidate.coordinate_).availability != VoxelAvailability::Unavailable) {
|
||||
return std::unexpected(VoxelError::Stale);
|
||||
}
|
||||
next->push_back({candidate.coordinate_, candidate.chunk_});
|
||||
result.changed_chunks.push_back({descriptor_.id, candidate.coordinate_,
|
||||
VoxelAvailability::Loaded, candidate.chunk_->revision()});
|
||||
result.dirty_chunks.push_back(candidate.coordinate_);
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, -1);
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, 1);
|
||||
}
|
||||
}
|
||||
std::sort(next->begin(), next->end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
for (std::size_t i = 1; i < next->size(); ++i) {
|
||||
if ((*next)[i - 1].coordinate == (*next)[i].coordinate) return std::unexpected(VoxelError::Duplicate);
|
||||
}
|
||||
std::sort(result.changed_chunks.begin(), result.changed_chunks.end(),
|
||||
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::edit(std::span<const VoxelEdit> edits) {
|
||||
if (edits.empty()) return VoxelCommit{};
|
||||
if (edits.size() > limits_.max_edit_cells) return std::unexpected(VoxelError::LimitExceeded);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
if (!staging.take(edits.size(), sizeof(VoxelEdit))) return std::unexpected(VoxelError::LimitExceeded);
|
||||
try {
|
||||
std::vector<VoxelEdit> ordered(edits.begin(), edits.end());
|
||||
std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
|
||||
const auto ca = split_voxel(a.position).chunk, cb = split_voxel(b.position).chunk;
|
||||
return ca == cb ? a.position < b.position : ca < cb;
|
||||
});
|
||||
std::size_t changed_pages = 0, changed_cells = 0;
|
||||
std::optional<ChunkCoordinate> last_changed;
|
||||
for (std::size_t i = 0; i < ordered.size(); ++i) {
|
||||
const auto& change = ordered[i];
|
||||
if (i && ordered[i - 1].position == change.position) return std::unexpected(VoxelError::Duplicate);
|
||||
if (!valid_voxel_material(change.material)) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto current = sample(change.position);
|
||||
if (current.availability == VoxelAvailability::Outside) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (current.availability == VoxelAvailability::Unavailable) return std::unexpected(VoxelError::Unavailable);
|
||||
if (current.stamp.revision != change.expected_revision) return std::unexpected(VoxelError::Stale);
|
||||
if (current.material == change.material) continue;
|
||||
if (current.stamp.revision == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::unexpected(VoxelError::RevisionExhausted);
|
||||
}
|
||||
++changed_cells;
|
||||
if (!last_changed || *last_changed != current.stamp.coordinate) {
|
||||
++changed_pages;
|
||||
last_changed = current.stamp.coordinate;
|
||||
}
|
||||
}
|
||||
if (!changed_cells) return VoxelCommit{};
|
||||
const auto dirty_count = Void::Numeric::checked_mul(changed_cells, std::size_t{4});
|
||||
if (!dirty_count || !staging.take(1, sizeof(VoxelDirectory)) ||
|
||||
!staging.take(directory_->size(), sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(changed_pages, sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(voxel_chunk_cells, sizeof(MaterialId)) ||
|
||||
!staging.take(changed_cells, sizeof(VoxelChange)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
auto next = std::make_shared<VoxelDirectory>(*directory_);
|
||||
VoxelCommit result;
|
||||
result.changed_cells.reserve(changed_cells);
|
||||
result.changed_chunks.reserve(changed_pages);
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (std::size_t first = 0; first < ordered.size();) {
|
||||
const auto coordinate = split_voxel(ordered[first].position).chunk;
|
||||
auto last = first + 1;
|
||||
while (last < ordered.size() && split_voxel(ordered[last].position).chunk == coordinate) ++last;
|
||||
const auto old = find_chunk(*directory_, coordinate);
|
||||
std::array<MaterialId, voxel_chunk_cells> cells;
|
||||
std::copy(old->chunk->cells().begin(), old->chunk->cells().end(), cells.begin());
|
||||
const auto count_before = result.changed_cells.size();
|
||||
for (auto i = first; i < last; ++i) {
|
||||
const auto& change = ordered[i];
|
||||
const auto local = split_voxel(change.position).local;
|
||||
auto& material = cells[*voxel_index(local)];
|
||||
if (material == change.material) continue;
|
||||
result.changed_cells.push_back({change.position, material, change.material});
|
||||
material = change.material;
|
||||
result.dirty_chunks.push_back(coordinate);
|
||||
const std::array<std::uint8_t, 3> axes{local.x, local.y, local.z};
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
if (axes[static_cast<std::size_t>(axis)] == 0) add_neighbor(*this, result.dirty_chunks, coordinate, axis, -1);
|
||||
if (axes[static_cast<std::size_t>(axis)] == 31) add_neighbor(*this, result.dirty_chunks, coordinate, axis, 1);
|
||||
}
|
||||
}
|
||||
if (result.changed_cells.size() != count_before) {
|
||||
const auto revision = old->chunk->revision() + 1;
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, cells));
|
||||
const auto index = static_cast<std::size_t>(old - directory_->begin());
|
||||
(*next)[index].chunk = std::move(chunk);
|
||||
result.changed_chunks.push_back({descriptor_.id, coordinate, VoxelAvailability::Loaded, revision});
|
||||
}
|
||||
first = last;
|
||||
}
|
||||
std::sort(result.changed_cells.begin(), result.changed_cells.end(),
|
||||
[](const auto& a, const auto& b) { return a.position < b.position; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -1,479 +0,0 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include "settlement/core/worker_pool.hpp"
|
||||
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
|
||||
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
|
||||
constexpr auto exhausted = std::numeric_limits<std::uint64_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "voxel region invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
VoxelRegionDescriptor descriptor(VoxelBounds bounds = {{-64, -64, -32}, {64, 64, 32}}) {
|
||||
return {7, 42, voxel_generator_version, bounds};
|
||||
}
|
||||
PreparedVoxelChunk generated(const VoxelRegion& region, ChunkCoordinate coordinate) {
|
||||
auto candidate = region.prepare_generated(coordinate);
|
||||
require(candidate.has_value(), "valid chunk generation refused");
|
||||
return std::move(*candidate);
|
||||
}
|
||||
void activate(VoxelRegion& region, std::span<const ChunkCoordinate> coordinates) {
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (auto coordinate : coordinates) candidates.push_back(generated(region, coordinate));
|
||||
require(region.activate(candidates).has_value(), "valid chunk activation refused");
|
||||
}
|
||||
VoxelEdit change(const VoxelRegion& region, VoxelPosition position) {
|
||||
const auto sample = region.sample(position);
|
||||
require(sample.availability == VoxelAvailability::Loaded);
|
||||
return {position, sample.material == MaterialId::Air ? MaterialId::Stone : MaterialId::Air, sample.stamp.revision};
|
||||
}
|
||||
void equivalent(const VoxelRegion& left, const VoxelRegion& right) {
|
||||
require(left.descriptor() == right.descriptor());
|
||||
const auto a = left.directory(), b = right.directory();
|
||||
require(a->size() == b->size());
|
||||
for (std::size_t i = 0; i < a->size(); ++i) {
|
||||
require((*a)[i].coordinate == (*b)[i].coordinate &&
|
||||
(*a)[i].chunk->revision() == (*b)[i].chunk->revision());
|
||||
require(std::equal((*a)[i].chunk->cells().begin(), (*a)[i].chunk->cells().end(), (*b)[i].chunk->cells().begin()),
|
||||
"complete material pages differ");
|
||||
}
|
||||
}
|
||||
template<class T> void error(const std::expected<T, VoxelError>& result, VoxelError expected) {
|
||||
require(!result && result.error() == expected, "unexpected operation result");
|
||||
}
|
||||
bool contains(const std::vector<ChunkCoordinate>& coordinates, ChunkCoordinate coordinate) {
|
||||
return std::binary_search(coordinates.begin(), coordinates.end(), coordinate);
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("VoxelRegionTests")]] VoxelRegionTests : Void::Testing::Suite<VoxelRegionTests> {
|
||||
[[= Void::Testing::tag("voxel-region")]] Test signed_coordinates_and_x_fast_layout();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test descriptor_validation_and_sparse_extreme_bounds();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test generated_pages_have_fixed_materials_and_continuous_surface();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test preparation_order_and_worker_order_preserve_complete_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test partial_pages_mask_outside_and_validate_import();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test availability_and_snapshot_lifetimes();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test atomic_multichunk_edit_reuses_unchanged_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test refused_batches_and_identical_writes_preserve_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test face_neighbors_and_unavailable_boundaries();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test activation_checks_source_duplicates_and_prior_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test imported_revision_exhaustion_preserves_all_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test page_edit_and_staging_budgets_are_atomic();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test doorway_crossing_two_chunks_opens_atomically();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test full_resident_directory_copies_one_changed_page();
|
||||
};
|
||||
|
||||
Test VoxelRegionTests::signed_coordinates_and_x_fast_layout() {
|
||||
constexpr std::array values{smallest, -33, -32, -1, 0, 31, 32, largest};
|
||||
constexpr std::array chunks{-67108864, -2, -1, -1, 0, 0, 1, 67108863};
|
||||
constexpr std::array locals{0, 31, 0, 31, 0, 31, 0, 31};
|
||||
for (std::size_t i = 0; i < values.size(); ++i) {
|
||||
for (auto y : values) for (auto z : values) {
|
||||
const VoxelPosition position{values[i], y, z};
|
||||
const auto address = split_voxel(position);
|
||||
require(address.chunk.x == chunks[i] && address.local.x == locals[i]);
|
||||
require(join_voxel(address.chunk, address.local) == position);
|
||||
}
|
||||
}
|
||||
require(voxel_index({1, 0, 0}) == 1 && voxel_index({0, 1, 0}) == 32 &&
|
||||
voxel_index({0, 0, 1}) == 1024 && voxel_index({31, 31, 31}) == voxel_chunk_cells - 1);
|
||||
require(!voxel_index({32, 0, 0}) && !voxel_index({0, 255, 0}));
|
||||
require(!join_voxel({67108864, 0, 0}, {}) && !join_voxel({-67108865, 0, 0}, {31, 0, 0}));
|
||||
require(!join_voxel({}, {0, 0, 32}));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::descriptor_validation_and_sparse_extreme_bounds() {
|
||||
const auto rejected = [](VoxelRegionDescriptor definition) {
|
||||
try { const VoxelRegion region(definition); }
|
||||
catch (const std::invalid_argument&) { return true; }
|
||||
return false;
|
||||
};
|
||||
auto definition = descriptor(); definition.id = 0; require(rejected(definition));
|
||||
definition = descriptor(); definition.generator_version = 0; require(rejected(definition));
|
||||
definition.generator_version = 2; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.x = definition.bounds.lower.x; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.lower.z = std::int64_t{smallest} - 1; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.y = std::int64_t{largest} + 2; require(rejected(definition));
|
||||
VoxelRegion sparse(descriptor({{smallest, smallest, smallest},
|
||||
{std::int64_t{largest} + 1, std::int64_t{largest} + 1, std::int64_t{largest} + 1}}));
|
||||
require(sparse.directory()->empty() && sparse.resident_bytes() == sizeof(VoxelDirectory));
|
||||
const std::array coordinates{ChunkCoordinate{-67108864, -67108864, -67108864},
|
||||
ChunkCoordinate{67108863, 67108863, 67108863}};
|
||||
activate(sparse, coordinates);
|
||||
require(sparse.sample({smallest, smallest, smallest}).material == MaterialId::Stone);
|
||||
require(sparse.sample({largest, largest, largest}).availability == VoxelAvailability::Loaded &&
|
||||
sparse.sample({largest, largest, largest}).material == MaterialId::Air);
|
||||
error(sparse.prepare_generated({largest, 0, 0}), VoxelError::InvalidCoordinate);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::generated_pages_have_fixed_materials_and_continuous_surface() {
|
||||
VoxelRegion region(descriptor());
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -1; x <= 0; ++x) for (int y = -1; y <= 0; ++y) for (int z = -1; z <= 0; ++z) {
|
||||
coordinates.push_back({x, y, z});
|
||||
}
|
||||
activate(region, coordinates);
|
||||
const auto height = [&](int x, int y) {
|
||||
int top = -20;
|
||||
for (int z = -16; z < 16; ++z) if (region.sample({x, y, z}).material != MaterialId::Air) top = z;
|
||||
require(top >= -8 && top <= 8);
|
||||
require(region.sample({x, y, top}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 2}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 3}).material == MaterialId::Stone &&
|
||||
region.sample({x, y, top + 1}).material == MaterialId::Air);
|
||||
return top;
|
||||
};
|
||||
for (int x = -31; x < 31; ++x) for (int y = -31; y < 31; ++y) {
|
||||
const auto top = height(x, y);
|
||||
require(std::abs(top - height(x + 1, y)) <= 1 && std::abs(top - height(x, y + 1)) <= 1,
|
||||
"generator has a discontinuous chunk/lattice surface");
|
||||
}
|
||||
const auto page = region.directory()->front().chunk;
|
||||
const auto hash = Void::Hash::fnv1a64(std::as_bytes(page->cells()));
|
||||
std::cout << "generator1 seed42 chunk(-1,-1,-1) fnv1a64=" << hash << '\n';
|
||||
// Recorded against the canonical little-endian generator, independently
|
||||
// reproduced by the fixture calculation before accepting this revision.
|
||||
require(hash == 13302332479434111011ULL, "canonical generator fixture changed");
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::preparation_order_and_worker_order_preserve_complete_pages() {
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{-1, 0, 0},
|
||||
ChunkCoordinate{0, -1, -1}, ChunkCoordinate{1, 1, 0}};
|
||||
VoxelRegion forward(descriptor());
|
||||
activate(forward, coordinates);
|
||||
VoxelRegion reverse(descriptor());
|
||||
auto reversed = coordinates; std::reverse(reversed.begin(), reversed.end());
|
||||
activate(reverse, reversed);
|
||||
equivalent(forward, reverse);
|
||||
for (std::size_t workers : {2, 6, 12}) for (bool reverse_completion : {false, true}) {
|
||||
VoxelRegion parallel(descriptor());
|
||||
WorkerPool pool(workers);
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (std::size_t pair = 0; pair < coordinates.size(); pair += 2) {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
int ready = 0;
|
||||
std::array<bool, 2> permitted{};
|
||||
bool released = false;
|
||||
std::array<std::future<std::expected<PreparedVoxelChunk, VoxelError>>, 2> futures;
|
||||
// Release and drain every accepted task before its captured gate
|
||||
// dies, including a failed submission or assertion.
|
||||
auto release = Void::Scope::on_exit([&] {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
for (auto& future : futures) if (future.valid()) future.wait();
|
||||
});
|
||||
for (std::size_t index = 0; index < 2; ++index) {
|
||||
futures[index] = pool.submit([&, parallel, coordinate = coordinates[pair + index], index] {
|
||||
auto result = parallel.prepare_generated(coordinate);
|
||||
std::unique_lock lock(mutex);
|
||||
++ready;
|
||||
changed.notify_all();
|
||||
changed.wait(lock, [&] { return released || permitted[index]; });
|
||||
return result;
|
||||
});
|
||||
}
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return ready == 2; }),
|
||||
"two real generator tasks did not reach completion gates");
|
||||
}
|
||||
const std::array<std::size_t, 2> order = reverse_completion ?
|
||||
std::array<std::size_t, 2>{1, 0} : std::array<std::size_t, 2>{0, 1};
|
||||
for (auto index : order) {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
permitted[index] = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
require(futures[index].wait_for(std::chrono::seconds(5)) == std::future_status::ready);
|
||||
auto result = futures[index].get();
|
||||
require(result.has_value());
|
||||
candidates.push_back(std::move(*result));
|
||||
}
|
||||
}
|
||||
require(parallel.activate(candidates).has_value());
|
||||
equivalent(forward, parallel);
|
||||
}
|
||||
auto other_definition = descriptor(); ++other_definition.seed;
|
||||
VoxelRegion other(other_definition); activate(other, coordinates);
|
||||
require(!std::equal(forward.directory()->front().chunk->cells().begin(),
|
||||
forward.directory()->front().chunk->cells().end(), other.directory()->front().chunk->cells().begin()));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::partial_pages_mask_outside_and_validate_import() {
|
||||
const std::array bounds{VoxelBounds{{-1, -1, -1}, {1, 1, 1}},
|
||||
VoxelBounds{{largest, largest, largest}, {std::int64_t{largest} + 1,
|
||||
std::int64_t{largest} + 1, std::int64_t{largest} + 1}},
|
||||
VoxelBounds{{smallest, smallest, smallest}, {std::int64_t{smallest} + 1,
|
||||
std::int64_t{smallest} + 1, std::int64_t{smallest} + 1}}};
|
||||
for (const auto& bound : bounds) {
|
||||
VoxelRegion region(descriptor(bound));
|
||||
const VoxelPosition position{static_cast<std::int32_t>(bound.lower.x),
|
||||
static_cast<std::int32_t>(bound.lower.y), static_cast<std::int32_t>(bound.lower.z)};
|
||||
const auto coordinate = split_voxel(position).chunk;
|
||||
auto candidate = generated(region, coordinate);
|
||||
const auto cells = candidate.chunk()->cells();
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
const auto p = join_voxel(coordinate, {static_cast<std::uint8_t>(i % 32),
|
||||
static_cast<std::uint8_t>((i / 32) % 32), static_cast<std::uint8_t>(i / 1024)});
|
||||
require(p.has_value());
|
||||
if (!bound.contains(*p)) require(cells[i] == MaterialId::Air);
|
||||
}
|
||||
auto restored = region.prepare_restored(coordinate, 72, cells);
|
||||
require(restored.has_value() && restored->chunk()->revision() == 72);
|
||||
std::array<MaterialId, voxel_chunk_cells> owned;
|
||||
std::copy(cells.begin(), cells.end(), owned.begin());
|
||||
auto independent = region.prepare_restored(coordinate, 1, owned);
|
||||
require(independent.has_value());
|
||||
const auto index = *voxel_index(split_voxel(position).local);
|
||||
owned[index] = static_cast<MaterialId>(200);
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidMaterial);
|
||||
require(independent->chunk()->cells()[index] == cells[index], "import retained caller's mutable cells");
|
||||
owned[index] = cells[index];
|
||||
const auto outside_index = (index + 1234) % voxel_chunk_cells;
|
||||
owned[outside_index] = MaterialId::Stone;
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidCoordinate);
|
||||
error(region.prepare_restored(coordinate, 0, cells), VoxelError::InvalidRevision);
|
||||
error(region.prepare_restored(coordinate, 1, cells.first(100)), VoxelError::InvalidSource);
|
||||
}
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::availability_and_snapshot_lifetimes() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto absent = region.sample({0, 0, 20});
|
||||
require(absent.availability == VoxelAvailability::Unavailable);
|
||||
const auto outside = region.sample({64, 0, 20});
|
||||
require(outside.availability == VoxelAvailability::Outside);
|
||||
auto held = region;
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
require(!region.matches(absent.stamp) && held.matches(absent.stamp));
|
||||
const auto loaded = region.sample({0, 0, 20});
|
||||
require(loaded.availability == VoxelAvailability::Loaded && loaded.material == MaterialId::Air);
|
||||
require(held.sample({0, 0, 20}).availability == VoxelAvailability::Unavailable);
|
||||
auto owned_directory = region.directory();
|
||||
auto retained = region;
|
||||
const std::array changes{change(region, {0, 0, 20})};
|
||||
require(region.edit(changes).has_value());
|
||||
require(retained.matches(loaded.stamp) && !region.matches(loaded.stamp));
|
||||
require(owned_directory->front().chunk->cells()[20 * 1024] == MaterialId::Air);
|
||||
auto other_stamp = loaded.stamp; ++other_stamp.region; require(!retained.matches(other_stamp));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::atomic_multichunk_edit_reuses_unchanged_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}, ChunkCoordinate{1, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {0, 2, 20}), change(region, {-1, 2, 20}), change(region, {4, 4, 20})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result.has_value() && result->changed_chunks.size() == 2 && result->changed_cells.size() == 3);
|
||||
require(result->changed_cells[0].position == VoxelPosition{-1, 2, 20} &&
|
||||
result->changed_cells[1].position == VoxelPosition{0, 2, 20});
|
||||
require(result->changed_chunks[0].coordinate == ChunkCoordinate{-1, 0, 0} &&
|
||||
result->changed_chunks[1].coordinate == ChunkCoordinate{0, 0, 0});
|
||||
for (const auto& change : changes) {
|
||||
require(region.sample(change.position).material == change.material);
|
||||
require(held.sample(change.position).material != change.material);
|
||||
require(region.sample(change.position).stamp.revision == 2);
|
||||
}
|
||||
require(region.directory()->back().chunk == held.directory()->back().chunk,
|
||||
"untouched geometry was copied");
|
||||
VoxelRegion other = held;
|
||||
auto reversed = changes; std::reverse(reversed.begin(), reversed.end());
|
||||
require(other.edit(reversed).has_value()); equivalent(region, other);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::refused_batches_and_identical_writes_preserve_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
auto changes = std::array{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
++changes[1].expected_revision;
|
||||
error(region.edit(changes), VoxelError::Stale);
|
||||
--changes[1].expected_revision; changes[1].material = static_cast<MaterialId>(255);
|
||||
error(region.edit(changes), VoxelError::InvalidMaterial);
|
||||
changes[1] = changes[0]; error(region.edit(changes), VoxelError::Duplicate);
|
||||
changes[1] = {{32, 1, 20}, MaterialId::Stone, 1}; error(region.edit(changes), VoxelError::Unavailable);
|
||||
changes[1].position.x = 64; error(region.edit(changes), VoxelError::InvalidCoordinate);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
require(region.edit({}).has_value() && region.directory() == held.directory());
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
std::array identical{VoxelEdit{{0, 1, 20}, current.material, current.stamp.revision}};
|
||||
const auto result = region.edit(identical);
|
||||
require(result && result->changed_chunks.empty() && result->changed_cells.empty() && result->dirty_chunks.empty());
|
||||
require(region.directory() == held.directory());
|
||||
--identical[0].expected_revision; error(region.edit(identical), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::face_neighbors_and_unavailable_boundaries() {
|
||||
VoxelRegion region(descriptor({{-64, -64, -64}, {64, 64, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{-1, -1, -1}, ChunkCoordinate{0, -1, -1}};
|
||||
activate(region, coordinates);
|
||||
const auto neighbor = region.chunk_stamp({0, -1, -1});
|
||||
const auto absent = region.chunk_stamp({-1, 0, -1});
|
||||
const std::array changes{change(region, {-1, -1, -1})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result && result->dirty_chunks.size() == 4);
|
||||
require(contains(result->dirty_chunks, {-1, -1, -1}) && contains(result->dirty_chunks, {0, -1, -1}) &&
|
||||
contains(result->dirty_chunks, {-1, 0, -1}) && contains(result->dirty_chunks, {-1, -1, 0}));
|
||||
require(!contains(result->dirty_chunks, {0, 0, -1}) && !contains(result->dirty_chunks, {0, 0, 0}));
|
||||
require(region.matches(neighbor) && region.matches(absent));
|
||||
const std::array interior{change(region, {-2, -2, -2})};
|
||||
const auto result2 = region.edit(interior);
|
||||
require(result2 && result2->dirty_chunks == std::vector<ChunkCoordinate>{{-1, -1, -1}});
|
||||
VoxelRegion edge(descriptor({{largest, 0, 0}, {std::int64_t{largest} + 1, 1, 1}}));
|
||||
const std::array last_chunk{split_voxel({largest, 0, 0}).chunk}; activate(edge, last_chunk);
|
||||
const std::array last_change{change(edge, {largest, 0, 0})};
|
||||
const auto last_result = edge.edit(last_change);
|
||||
require(last_result && last_result->dirty_chunks == std::vector<ChunkCoordinate>{last_chunk[0]});
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::activation_checks_source_duplicates_and_prior_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
auto candidate = generated(region, {});
|
||||
const auto empty = region.directory();
|
||||
const std::array duplicate{candidate, candidate}; error(region.activate(duplicate), VoxelError::Duplicate);
|
||||
require(region.directory() == empty);
|
||||
for (int field = 0; field < 3; ++field) {
|
||||
auto wrong = descriptor();
|
||||
if (field == 0) ++wrong.id;
|
||||
if (field == 1) ++wrong.seed;
|
||||
if (field == 2) --wrong.bounds.lower.x;
|
||||
VoxelRegion other(wrong);
|
||||
const std::array mixed{candidate, generated(other, {-1, 0, 0})};
|
||||
error(region.activate(mixed), VoxelError::InvalidSource);
|
||||
require(region.directory() == empty);
|
||||
}
|
||||
const std::array first{candidate}; require(region.activate(first).has_value());
|
||||
const auto held = region.directory();
|
||||
const std::array late{generated(region, {-1, 0, 0}), candidate};
|
||||
error(region.activate(late), VoxelError::Stale); require(region.directory() == held);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::imported_revision_exhaustion_preserves_all_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto source = generated(region, {});
|
||||
auto maximum = region.prepare_restored({}, exhausted, source.chunk()->cells());
|
||||
require(maximum.has_value());
|
||||
const std::array pages{generated(region, {-1, 0, 0}), *maximum};
|
||||
require(region.activate(pages).has_value());
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
error(region.edit(changes), VoxelError::RevisionExhausted);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
const std::array identical{VoxelEdit{{0, 1, 20}, current.material, exhausted}};
|
||||
require(region.edit(identical).has_value() && region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::page_edit_and_staging_budgets_are_atomic() {
|
||||
VoxelRegion source(descriptor());
|
||||
const std::array pages{generated(source, {}), generated(source, {-1, 0, 0})};
|
||||
VoxelLimits one; one.max_resident_chunks = 1;
|
||||
VoxelRegion bounded(descriptor(), one);
|
||||
const auto empty = bounded.directory();
|
||||
error(bounded.activate(pages), VoxelError::LimitExceeded); require(bounded.directory() == empty);
|
||||
require(bounded.activate(std::span(pages).first(1)).has_value());
|
||||
error(bounded.activate(std::span(pages).last(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits bytes; bytes.max_resident_bytes = sizeof(VoxelDirectory) + sizeof(VoxelChunkEntry) + sizeof(VoxelChunk) - 1;
|
||||
VoxelRegion small(descriptor(), bytes);
|
||||
error(small.activate(std::span(pages).first(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits transactions; transactions.max_transaction_bytes = sizeof(VoxelChunk) + 1024;
|
||||
VoxelRegion limited(descriptor(), transactions);
|
||||
error(limited.prepare_generated({}), VoxelError::LimitExceeded);
|
||||
require(limited.activate(std::span(pages).first(1)).has_value());
|
||||
const auto held = limited.directory();
|
||||
const std::array edits{change(limited, {1, 1, 20})};
|
||||
error(limited.edit(edits), VoxelError::LimitExceeded); require(limited.directory() == held);
|
||||
VoxelLimits edit_limit; edit_limit.max_edit_cells = 1;
|
||||
VoxelRegion two(descriptor(), edit_limit); require(two.activate(pages).has_value());
|
||||
const std::array too_many{change(two, {1, 1, 20}), change(two, {-1, 1, 20})};
|
||||
error(two.edit(too_many), VoxelError::LimitExceeded);
|
||||
require(two.resident_bytes() == sizeof(VoxelDirectory) + 2 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)));
|
||||
VoxelLimits hostile; hostile.max_resident_chunks = std::numeric_limits<std::size_t>::max();
|
||||
VoxelRegion sparse(descriptor(), hostile); require(sparse.directory()->empty());
|
||||
std::cout << "voxel payload: page=" << sizeof(VoxelChunk) << " directory entry=" << sizeof(VoxelChunkEntry)
|
||||
<< " active256=" << sizeof(VoxelDirectory) + 256 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) << '\n';
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::doorway_crossing_two_chunks_opens_atomically() {
|
||||
require(voxel_blocks_passage(MaterialId::DoorClosed) && !voxel_blocks_passage(MaterialId::DoorOpen));
|
||||
require(!voxel_provides_support(MaterialId::DoorClosed) && !voxel_provides_support(MaterialId::DoorOpen));
|
||||
require(!voxel_blocks_passage(MaterialId::Air) && !voxel_provides_support(MaterialId::Air));
|
||||
for (auto material : {MaterialId::Soil, MaterialId::Stone}) {
|
||||
require(voxel_blocks_passage(material) && voxel_provides_support(material));
|
||||
}
|
||||
VoxelRegion region(descriptor({{0, 0, 0}, {32, 32, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{0, 0, 1}};
|
||||
activate(region, coordinates);
|
||||
const std::array closed{VoxelEdit{{2, 2, 31}, MaterialId::DoorClosed, 1},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorClosed, 1}};
|
||||
require(region.edit(closed).has_value());
|
||||
const auto held = region;
|
||||
std::array opened{VoxelEdit{{2, 2, 31}, MaterialId::DoorOpen, 2},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorOpen, 1}};
|
||||
error(region.edit(opened), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
opened[1].expected_revision = 2;
|
||||
const auto result = region.edit(opened);
|
||||
require(result && result->changed_chunks.size() == 2 && result->changed_cells.size() == 2);
|
||||
for (auto edit : opened) {
|
||||
require(region.sample(edit.position).material == MaterialId::DoorOpen);
|
||||
require(held.sample(edit.position).material == MaterialId::DoorClosed);
|
||||
}
|
||||
auto imported = region.prepare_restored(coordinates[0], 3, region.directory()->front().chunk->cells());
|
||||
require(imported.has_value());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::full_resident_directory_copies_one_changed_page() {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
VoxelRegion region(descriptor({{-256, -256, 0}, {256, 256, 32}}));
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -8; x < 8; ++x) for (int y = -8; y < 8; ++y) coordinates.push_back({x, y, 0});
|
||||
const auto preparation_started = Clock::now();
|
||||
activate(region, coordinates);
|
||||
const auto preparation_done = Clock::now();
|
||||
const auto held = region;
|
||||
require(held.directory() == region.directory() && held.directory()->size() == 256);
|
||||
const std::array edits{change(region, {1, 1, 20})};
|
||||
const auto edit_started = Clock::now();
|
||||
const auto result = region.edit(edits);
|
||||
const auto edit_done = Clock::now();
|
||||
require(result && result->changed_chunks.size() == 1);
|
||||
std::size_t shared = 0;
|
||||
for (std::size_t i = 0; i < region.directory()->size(); ++i) {
|
||||
if ((*held.directory())[i].chunk == (*region.directory())[i].chunk) ++shared;
|
||||
}
|
||||
require(shared == 255 && region.directory() != held.directory());
|
||||
require(held.sample(edits[0].position).material != region.sample(edits[0].position).material);
|
||||
std::cout << "full256 pages: prepare+activate_us="
|
||||
<< std::chrono::duration_cast<std::chrono::microseconds>(preparation_done - preparation_started).count()
|
||||
<< " edit_us=" << std::chrono::duration_cast<std::chrono::microseconds>(edit_done - edit_started).count()
|
||||
<< " shared_pages=" << shared << " resident_payload=" << region.resident_bytes() << '\n';
|
||||
}
|
||||
} // namespace
|
||||
@@ -1,429 +0,0 @@
|
||||
#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
|
||||
Reference in new issue
Block a user