feat(rendering): draw and pick immutable voxel height slices through D3D11

This commit is contained in:
faumaray committed 2026-12-03 00:05:11 +03:00
1 parent 13dc673088
commit 37a08d4d48
8 files changed
+1049 -11

No files matched your search

+78 -7
View File
@@ -11,6 +11,8 @@
#include <cstring>
#include <iterator>
#include <limits>
#include <new>
#include <stdexcept>
#include <utility>
namespace settlement::viewer {
@@ -468,6 +470,8 @@ cbuffer Camera : register(b0) {
float2 screen;
float scale;
float padding;
float2 depthParameters;
float2 depthPadding;
};
struct Input { float3 position : POSITION; float3 color : COLOR; };
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
@@ -477,7 +481,8 @@ Pixel project(Input input) {
(p.x + p.y) * halfTile.y - p.z * 16.0);
Pixel result;
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
1.0 - screenPoint.y * 2.0 / screen.y,
depthParameters.x - (p.x + p.y + p.z * 1.5) * depthParameters.y, 1.0);
result.color = input.color;
return result;
}
@@ -489,6 +494,8 @@ 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 {
@@ -539,21 +546,28 @@ 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, geometry.ReleaseAndGetAddressOf()))) return false;
buffer_bytes = desc.ByteWidth;
if (FAILED(device->CreateBuffer(&desc, nullptr, &replacement))) return false;
destination = replacement.Get();
}
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
if (FAILED(context->Map(destination, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
context->Unmap(geometry.Get(), 0);
context->Unmap(destination, 0);
if (replacement) {
geometry = std::move(replacement);
buffer_bytes = static_cast<UINT>(bytes);
}
return true;
}
@@ -621,7 +635,7 @@ bool D3DScene::initialize(HWND target, bool software) {
raster.CullMode = D3D11_CULL_NONE;
raster.DepthClipEnable = TRUE;
D3D11_BUFFER_DESC constants{};
constants.ByteWidth = 32;
constants.ByteWidth = 48;
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
vertex->GetBufferSize(), &graphics->layout)) ||
@@ -656,6 +670,62 @@ 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
@@ -679,7 +749,8 @@ 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};
viewport.Width, viewport.Height, view.scale, 0,
geometry->depth_bias, geometry->depth_scale, 0, 0};
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
constexpr UINT stride = sizeof(Vertex);
constexpr UINT offset = 0;
+5
View File
@@ -3,6 +3,7 @@
#include <windows.h>
#include "settlement/core/world.hpp"
#include "voxel_scene.hpp"
#include <cstdint>
#include <memory>
@@ -55,6 +56,10 @@ 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;
+337
View File
@@ -0,0 +1,337 @@
#include "voxel_scene.hpp"
#include <Void/Math/Numeric.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <limits>
#include <new>
#include <stdexcept>
namespace settlement::viewer {
namespace {
constexpr std::array<VoxelPosition, 6> normals{{
{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}};
constexpr double elevation_pixels = 16;
bool finite(VoxelPoint point) noexcept {
return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
}
bool empty(VoxelBounds bounds) noexcept {
return bounds.upper.z <= bounds.lower.z;
}
bool solid(const VoxelSample& sample) noexcept {
return sample.availability == VoxelAvailability::Unavailable ||
(sample.availability == VoxelAvailability::Loaded && voxel_blocks_passage(sample.material));
}
bool record(std::vector<ChunkStamp>& reads, ChunkStamp stamp, std::size_t limit) {
const auto at = std::lower_bound(reads.begin(), reads.end(), stamp.coordinate,
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
if (at != reads.end() && at->coordinate == stamp.coordinate) return true;
if (reads.size() >= limit) return false;
reads.insert(at, stamp);
return true;
}
std::optional<VoxelPosition> neighbor(VoxelPosition cell, VoxelPosition normal) noexcept {
const auto x = Void::Numeric::checked_add(cell.x, normal.x);
const auto y = Void::Numeric::checked_add(cell.y, normal.y);
const auto z = Void::Numeric::checked_add(cell.z, normal.z);
if (!x || !y || !z) return std::nullopt;
return VoxelPosition{*x, *y, *z};
}
bool within_budget(std::size_t faces, std::size_t reads, std::size_t limit) noexcept {
// Include the eventual six expanded position/color vertices per quad, so
// this budget covers a retained CPU scene plus its prepared D3D geometry.
constexpr std::size_t face_bytes = sizeof(VoxelFace) + 6 * 6 * sizeof(float);
const auto mesh_bytes = Void::Numeric::checked_mul(faces, face_bytes);
// Account for geometric vector capacity growth in the read directory.
const auto stamp_bytes = Void::Numeric::checked_mul(reads, 2 * sizeof(ChunkStamp));
if (!mesh_bytes || !stamp_bytes) return false;
const auto total = Void::Numeric::checked_add(*mesh_bytes, *stamp_bytes);
return total && *total <= limit;
}
std::array<std::int64_t, 3> lower_array(VoxelBounds bounds) noexcept {
return {bounds.lower.x, bounds.lower.y, bounds.lower.z};
}
std::array<std::int64_t, 3> extent_array(VoxelBounds bounds) noexcept {
return {bounds.upper.x - bounds.lower.x, bounds.upper.y - bounds.lower.y,
bounds.upper.z - bounds.lower.z};
}
VoxelPosition normal_for(std::size_t axis, int sign) noexcept {
if (axis == 0) return {sign, 0, 0};
if (axis == 1) return {0, sign, 0};
return {0, 0, sign};
}
} // namespace
VoxelScene::VoxelScene(VoxelRegion region, Void::Uuid::Uuid session,
VoxelSceneOptions options, VoxelBounds visible)
: region_(std::move(region)), session_(session), options_(options), visible_(visible) {}
bool VoxelScene::current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept {
return session == session_ && region.descriptor() == region_.descriptor() &&
std::all_of(reads_.begin(), reads_.end(), [&](auto stamp) { return region.matches(stamp); });
}
std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError> prepare_voxel_scene(
const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options) {
const auto& bounds = options.bounds;
const auto& region_bounds = region.descriptor().bounds;
const auto& limits = options.limits;
if (bounds.lower.x < region_bounds.lower.x || bounds.lower.y < region_bounds.lower.y ||
bounds.lower.z < region_bounds.lower.z || bounds.upper.x > region_bounds.upper.x ||
bounds.upper.y > region_bounds.upper.y || bounds.upper.z > region_bounds.upper.z ||
bounds.lower.x >= bounds.upper.x || bounds.lower.y >= bounds.upper.y ||
bounds.lower.z >= bounds.upper.z || limits.max_axis <= 0) {
return std::unexpected(VoxelSceneError::InvalidInput);
}
const auto extents = extent_array(bounds);
for (auto extent : extents) {
// The shader uses float local vertices. Keep all cell corners exact,
// including the upper endpoint, even if a caller raises its budget.
if (extent > limits.max_axis || extent > 65536) return std::unexpected(VoxelSceneError::LimitExceeded);
}
auto visible = bounds;
visible.upper.z = std::max(bounds.lower.z,
std::min(bounds.upper.z, std::int64_t{options.slice} + 1));
auto cells = Void::Numeric::checked_mul(static_cast<std::size_t>(extents[0]),
static_cast<std::size_t>(extents[1]));
if (cells) cells = Void::Numeric::checked_mul(*cells,
static_cast<std::size_t>(visible.upper.z - visible.lower.z));
if (!cells || *cells > limits.max_cells) return std::unexpected(VoxelSceneError::LimitExceeded);
try {
auto scene = std::shared_ptr<VoxelScene>(new VoxelScene(region, session, options, visible));
std::size_t face_count = 0;
const auto record_read = [&](ChunkStamp stamp) {
const auto at = std::lower_bound(scene->reads_.begin(), scene->reads_.end(), stamp.coordinate,
[](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; });
if (at != scene->reads_.end() && at->coordinate == stamp.coordinate) return true;
if (scene->reads_.size() >= limits.max_read_chunks ||
!within_budget(face_count, scene->reads_.size() + 1, limits.max_bytes)) return false;
scene->reads_.insert(at, stamp);
return true;
};
// First pass counts and records dependencies before allocating faces.
// Second pass reads the same held immutable pages and fills exact capacity.
for (int pass = 0; pass < 2; ++pass) {
for (auto z = visible.lower.z; z < visible.upper.z; ++z) {
for (auto y = visible.lower.y; y < visible.upper.y; ++y) {
for (auto x = visible.lower.x; x < visible.upper.x; ++x) {
const VoxelPosition cell{static_cast<std::int32_t>(x),
static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
const auto sample = region.sample(cell);
if (pass == 0 && !record_read(sample.stamp))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (!solid(sample)) continue;
for (auto normal : normals) {
const auto next = neighbor(cell, normal);
if (next && visible.contains(*next)) {
const auto beside = region.sample(*next);
if (pass == 0 && !record_read(beside.stamp))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (solid(beside)) continue;
}
if (pass == 0) {
if (face_count >= limits.max_faces) return std::unexpected(VoxelSceneError::LimitExceeded);
++face_count;
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
return std::unexpected(VoxelSceneError::LimitExceeded);
} else {
scene->faces_.push_back({cell, normal, sample.material,
sample.availability == VoxelAvailability::Unavailable});
}
}
}
}
}
if (pass == 0) {
if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes))
return std::unexpected(VoxelSceneError::LimitExceeded);
scene->faces_.reserve(face_count);
}
}
return scene;
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
} catch (const std::length_error&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
}
}
bool valid_voxel_camera(const VoxelCamera& camera) noexcept {
// D3D11 maximum 2D resource dimension, with finite practical shader inputs.
// Tiny/huge scales cannot identify a cell in a pixel and are refused.
return camera.width > 0 && camera.width <= 16384 && camera.height > 0 && camera.height <= 16384 &&
std::isfinite(camera.origin_x) && std::abs(camera.origin_x) <= 1e7 &&
std::isfinite(camera.origin_y) && std::abs(camera.origin_y) <= 1e7 &&
std::isfinite(camera.scale) && camera.scale >= 0.01 && camera.scale <= 256 &&
std::isfinite(camera.tile_half_width) && camera.tile_half_width >= 1 && camera.tile_half_width <= 256 &&
std::isfinite(camera.tile_half_height) && camera.tile_half_height >= 1 && camera.tile_half_height <= 256;
}
std::optional<ScreenPoint> project_voxel_point(const VoxelScene& scene,
const VoxelCamera& camera, VoxelPoint point) noexcept {
if (!valid_voxel_camera(camera) || !finite(point)) return std::nullopt;
const auto lower = scene.options().bounds.lower;
point = point - VoxelPoint{static_cast<double>(lower.x), static_cast<double>(lower.y), static_cast<double>(lower.z)};
const ScreenPoint result{camera.origin_x + camera.scale * (point.x - point.y) * camera.tile_half_width,
camera.origin_y + camera.scale * ((point.x + point.y) * camera.tile_half_height - point.z * elevation_pixels)};
if (!std::isfinite(result.x) || !std::isfinite(result.y)) return std::nullopt;
return result;
}
std::uint32_t voxel_face_color(const VoxelFace& face) noexcept {
std::array<std::uint32_t, 3> color{128, 132, 140};
if (!face.unavailable) {
switch (face.material) {
case MaterialId::Soil: color = {166, 119, 70}; break;
case MaterialId::Stone: color = {130, 143, 157}; break;
case MaterialId::DoorClosed: color = {184, 99, 46}; break;
default: break;
}
}
const std::uint32_t percent = face.normal.z > 0 ? 100u : face.normal.x != 0 ? 82u :
face.normal.y != 0 ? 66u : 50u;
for (auto& channel : color) channel = channel * percent / 100u;
return (color[0] << 16u) | (color[1] << 8u) | color[2];
}
bool VoxelPick::current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept {
return session == current_session && region == world.descriptor().id &&
std::all_of(reads.begin(), reads.end(), [&](auto stamp) { return world.matches(stamp); });
}
std::expected<VoxelPick, VoxelSceneError> trace_voxels(
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits) {
if (!finite(ray.origin) || !finite(ray.direction) || !std::isfinite(ray.max_distance) ||
ray.max_distance < 0) return std::unexpected(VoxelSceneError::InvalidInput);
const double magnitude = std::max({std::abs(ray.direction.x), std::abs(ray.direction.y), std::abs(ray.direction.z)});
if (magnitude == 0) return std::unexpected(VoxelSceneError::InvalidInput);
// Power-of-two scaling preserves represented component ratios. Dividing by
// a Euclidean norm first would turn a 1:3 exact corner tie into two steps.
int exponent = 0;
std::frexp(magnitude, &exponent);
const std::array<long double, 3> direction{std::scalbn(static_cast<long double>(ray.direction.x), -exponent),
std::scalbn(static_cast<long double>(ray.direction.y), -exponent),
std::scalbn(static_cast<long double>(ray.direction.z), -exponent)};
const auto length = std::hypot(direction[0], direction[1], direction[2]);
VoxelPick result;
result.region = scene.region().descriptor().id;
result.session = scene.session();
const auto bounds = scene.visible_bounds();
if (empty(bounds)) return result;
const auto lower = lower_array(bounds);
const auto extent = extent_array(bounds);
const std::array<long double, 3> origin{static_cast<long double>(ray.origin.x) - lower[0],
static_cast<long double>(ray.origin.y) - lower[1], static_cast<long double>(ray.origin.z) - lower[2]};
std::array<int, 3> step{};
std::array<long double, 3> entry{};
long double start = 0, finish = ray.max_distance / length;
for (std::size_t axis = 0; axis < 3; ++axis) {
if (!std::isfinite(origin[axis])) return std::unexpected(VoxelSceneError::InvalidInput);
step[axis] = direction[axis] > 0 ? 1 : direction[axis] < 0 ? -1 : 0;
if (step[axis] == 0) {
if (origin[axis] < 0 || origin[axis] >= extent[axis]) return result;
entry[axis] = -std::numeric_limits<long double>::infinity();
continue;
}
const auto a = -origin[axis] / direction[axis];
const auto b = (extent[axis] - origin[axis]) / direction[axis];
entry[axis] = std::min(a, b);
start = std::max(start, entry[axis]);
finish = std::min(finish, std::max(a, b));
}
if (start > finish || !std::isfinite(start)) return result;
std::array<std::int64_t, 3> cell{};
VoxelPosition normal{};
bool has_normal = false;
for (std::size_t axis = 0; axis < 3; ++axis) {
auto point = std::fma(direction[axis], start, origin[axis]);
if (entry[axis] == start) point = step[axis] > 0 ? 0 : static_cast<long double>(extent[axis]);
if (!std::isfinite(point) || point < 0 || point > extent[axis])
return std::unexpected(VoxelSceneError::InvalidInput);
const auto floor = std::floor(point);
cell[axis] = static_cast<std::int64_t>(floor) - (step[axis] < 0 && point == floor ? 1 : 0);
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
if (!has_normal && step[axis] != 0 && point == floor) {
normal = normal_for(axis, -step[axis]);
has_normal = true;
}
}
try {
auto distance = start;
for (std::size_t walked = 0; ; ++walked) {
if (walked >= limits.max_steps) return std::unexpected(VoxelSceneError::LimitExceeded);
const VoxelPosition absolute{static_cast<std::int32_t>(lower[0] + cell[0]),
static_cast<std::int32_t>(lower[1] + cell[1]), static_cast<std::int32_t>(lower[2] + cell[2])};
const auto sample = scene.region().sample(absolute);
if (!record(result.reads, sample.stamp, limits.max_read_chunks))
return std::unexpected(VoxelSceneError::LimitExceeded);
if (solid(sample)) {
result.status = sample.availability == VoxelAvailability::Unavailable ? VoxelPickStatus::Unavailable :
has_normal ? VoxelPickStatus::Hit : VoxelPickStatus::Inside;
result.cell = absolute;
result.normal = normal;
if (has_normal) result.adjacent = neighbor(absolute, normal);
result.material = sample.material;
result.distance = static_cast<double>(distance * length);
return result;
}
std::array<long double, 3> crossing{};
for (std::size_t axis = 0; axis < 3; ++axis) {
crossing[axis] = step[axis] == 0 ? std::numeric_limits<long double>::infinity() :
(static_cast<long double>(cell[axis] + (step[axis] > 0 ? 1 : 0)) - origin[axis]) / direction[axis];
}
const auto next = *std::min_element(crossing.begin(), crossing.end());
if (next > finish || !std::isfinite(next)) return result;
// A distance too large to represent successive voxel planes is not
// safe for a selection. Refuse rather than returning an arbitrary cell.
if (next <= distance) return std::unexpected(VoxelSceneError::InvalidInput);
has_normal = false;
for (std::size_t axis = 0; axis < 3; ++axis) {
if (crossing[axis] != next) continue;
cell[axis] += step[axis];
if (!has_normal) {
normal = normal_for(axis, -step[axis]);
has_normal = true;
}
if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result;
}
distance = next;
}
} catch (const std::bad_alloc&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
} catch (const std::length_error&) {
return std::unexpected(VoxelSceneError::AllocationFailed);
}
}
std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point) {
if (!valid_voxel_camera(camera) || !std::isfinite(point.x) || !std::isfinite(point.y) ||
point.x < 0 || point.y < 0 || point.x >= camera.width || point.y >= camera.height)
return std::unexpected(VoxelSceneError::InvalidInput);
const auto bounds = scene.visible_bounds();
const double z = static_cast<double>(bounds.upper.z - bounds.lower.z);
const double u = (point.x - camera.origin_x) / (camera.scale * camera.tile_half_width);
const double v = (point.y - camera.origin_y) / (camera.scale * camera.tile_half_height);
const double elevated = v + z * elevation_pixels / camera.tile_half_height;
VoxelRay ray{{(u + elevated) * 0.5 + static_cast<double>(bounds.lower.x),
(elevated - u) * 0.5 + static_cast<double>(bounds.lower.y), static_cast<double>(bounds.upper.z)},
{-1, -1, -2 * camera.tile_half_height / elevation_pixels}, 0};
ray.max_distance = z * std::hypot(ray.direction.x, ray.direction.y, ray.direction.z) / -ray.direction.z;
return ray;
}
std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits) {
const auto ray = voxel_screen_ray(scene, camera, point);
if (!ray) return std::unexpected(ray.error());
return trace_voxels(scene, *ray, limits);
}
} // namespace settlement::viewer
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include "map_camera.hpp"
#include "settlement/core/voxel_region.hpp"
#include <Void/Core/Uuid.hpp>
#include <Void/Math/Vec.hpp>
#include <expected>
#include <memory>
#include <span>
#include <vector>
namespace settlement::viewer {
using VoxelPoint = Void::Math::Vec3<double>;
struct VoxelCamera {
int width = 0, height = 0;
// Screen position of the lower corner of the prepared display bounds.
double origin_x = 0, origin_y = 0;
double scale = 1;
double tile_half_width = 12, tile_half_height = 7;
};
struct VoxelSceneLimits {
std::size_t max_cells = 2 * 1024 * 1024;
std::size_t max_faces = 262144;
std::size_t max_read_chunks = 1024;
// Faces, read directory capacity and expanded CPU vertices. Shared source
// pages, allocator overhead, retained older scenes and GPU memory are separate.
std::size_t max_bytes = 64 * 1024 * 1024;
std::int64_t max_axis = 4096;
};
struct VoxelSceneOptions {
// An explicit display volume bounds work even in an enormous sparse region.
VoxelBounds bounds;
std::int32_t slice = 0; // Highest displayed cell, inclusive.
VoxelSceneLimits limits;
};
enum class VoxelSceneError {
InvalidInput, LimitExceeded, AllocationFailed
};
struct VoxelFace {
VoxelPosition cell;
VoxelPosition normal;
MaterialId material = MaterialId::Air;
bool unavailable = false;
bool operator==(const VoxelFace&) const = default;
};
class VoxelScene {
public:
[[nodiscard]] const VoxelRegion& region() const noexcept { return region_; }
[[nodiscard]] const Void::Uuid::Uuid& session() const noexcept { return session_; }
[[nodiscard]] const VoxelSceneOptions& options() const noexcept { return options_; }
[[nodiscard]] const VoxelBounds& visible_bounds() const noexcept { return visible_; }
[[nodiscard]] std::span<const VoxelFace> faces() const noexcept { return faces_; }
[[nodiscard]] std::span<const ChunkStamp> reads() const noexcept { return reads_; }
[[nodiscard]] bool current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept;
private:
friend std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
prepare_voxel_scene(const VoxelRegion&, const Void::Uuid::Uuid&, VoxelSceneOptions);
VoxelScene(VoxelRegion region, Void::Uuid::Uuid session, VoxelSceneOptions options, VoxelBounds visible);
VoxelRegion region_;
Void::Uuid::Uuid session_;
VoxelSceneOptions options_;
VoxelBounds visible_;
std::vector<VoxelFace> faces_;
std::vector<ChunkStamp> reads_;
};
// Missing cells are opaque gray terrain boundaries. Picks stop there with
// Unavailable so loaded geometry cannot be selected through unknown space.
[[nodiscard]] std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
prepare_voxel_scene(const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options);
[[nodiscard]] bool valid_voxel_camera(const VoxelCamera& camera) noexcept;
[[nodiscard]] std::optional<ScreenPoint> project_voxel_point(
const VoxelScene& scene, const VoxelCamera& camera, VoxelPoint point) noexcept;
[[nodiscard]] std::uint32_t voxel_face_color(const VoxelFace& face) noexcept;
struct VoxelRay {
VoxelPoint origin;
VoxelPoint direction;
double max_distance = 0;
};
struct VoxelPickLimits {
std::size_t max_steps = 16384;
std::size_t max_read_chunks = 1024;
};
enum class VoxelPickStatus { Miss, Hit, Inside, Unavailable };
struct VoxelPick {
RegionId region = 0;
Void::Uuid::Uuid session;
VoxelPickStatus status = VoxelPickStatus::Miss;
VoxelPosition cell;
VoxelPosition normal; // Zero for an initial occupied cell with no crossed face.
std::optional<VoxelPosition> adjacent; // May be outside the region. Validate before placement.
MaterialId material = MaterialId::Air;
double distance = 0;
std::vector<ChunkStamp> reads;
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept;
};
// Cells are [x,x+1). At an exact plane the direction selects the forward cell.
// A zero component stays in the half-open cell owning that coordinate.
// Simultaneous plane crossings advance all tied axes, selecting normal X/Y/Z
// in that priority order. Cells touched only along an edge are skipped.
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> trace_voxels(
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits = {});
[[nodiscard]] std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point);
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits = {});
} // namespace settlement::viewer