feat: bvh

This commit is contained in:
2026-11-12 15:51:33 +01:00
parent c31f3a9bc3
commit 27f660f6fb
7 changed files with 1766 additions and 837 deletions
+406
View File
@@ -0,0 +1,406 @@
//! This is an implementation of a BVH2 as a top level ray acceleration
//! structure for objects in a scene.
//! The build is done only on CPU and uploaded on GPU.
use std::collections::HashMap;
use std::mem::size_of;
use glam::Mat4;
use crate::bvh::aabb::Aabb;
use crate::bvh::build::BvhPrimitive;
use crate::bvh::build::build_bvh;
use crate::bvh::gpu::GpuBvhNode;
use crate::bvh::gpu::GpuObject;
use crate::production::ProducerId;
use crate::production::StructureAnchor;
use crate::voxel_cache::tables::DynamicStructureTable;
pub mod aabb;
pub mod build;
pub mod debug;
pub mod gpu;
/// To handle an object stored in the bvh
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct BvhHandle
{
pub anchor: StructureAnchor,
pub producer_id: ProducerId,
/// Key discriminator, there might be multiple objects with the same anchor and producer_id
/// within the bvh
pub key: u64,
}
/// An object that is stored by the BVH structure
pub struct BvhObject
{
/// Identity of the voxel data
pub anchor: StructureAnchor,
pub producer_id: ProducerId,
/// The transform of the object in the BvhSpace
pub transform: Mat4,
/// A object is a voxel chunk, which in local space is in the [0,1]^3 cube
/// This bounding_box wraps more tightly arround the actual data stored.
pub bounding_box: Aabb,
}
impl BvhObject
{
pub fn world_bounding_box(&self) -> Aabb
{
self.bounding_box.as_transformed_by(&self.transform)
}
pub fn structure_anchor(&self) -> StructureAnchor
{
self.anchor
}
}
/// A BVH-backed structure table.
///
/// GPU state is uploaded lazily: host-side mutations mark the table dirty and
/// [`Self::rebuild_if_dirty`] must be called between frames before using the
/// raytrace bind group. Buffers and the bind group may be recreated when the
/// BVH or the inner table grows, so re-fetch them after each rebuild.
///
/// Raytrace bindings:
/// 0 = `GpuBvhNode[]` (read-only), 1 = `GpuObject[]` (read-only),
/// 2 = inner structure-table pointers, 3 = inner structure-table requests.
pub struct BvhStructureTable
{
/// Handle to object in the bvh
objects: HashMap<BvhHandle, BvhObject>,
/// Objects alive in the bvh have a slot in the dynamic table
slots: HashMap<BvhHandle, u32>,
structure_table: DynamicStructureTable,
/// discriminator key allocator
current_key: u64,
/// GPU BVH nodes, indexed by [`GpuBvhNode`] order.
bvh_nodes: wgpu::Buffer,
/// GPU BVH objects, indexed by leaf `first_or_left`.
bvh_objects: wgpu::Buffer,
node_capacity: usize,
object_capacity: usize,
node_count: u32,
object_count: u32,
raytrace_bind_group_layout: wgpu::BindGroupLayout,
raytrace_bind_group: wgpu::BindGroup,
/// True when the CPU BVH no longer matches the GPU buffers.
dirty: bool,
}
#[allow(dead_code)]
impl BvhStructureTable
{
pub fn new(device: &wgpu::Device, initial_capacity: usize, max_requests: usize) -> Self
{
let structure_table = DynamicStructureTable::new(device, initial_capacity, max_requests, 0);
let raytrace_bind_group_layout = create_bvh_raytrace_bind_group_layout(device);
let bvh_nodes = create_bvh_buffer::<GpuBvhNode>(device, 1, "bvh_nodes");
let bvh_objects = create_bvh_buffer::<GpuObject>(device, 1, "bvh_objects");
let raytrace_bind_group = create_bvh_raytrace_bind_group(
device,
&raytrace_bind_group_layout,
&bvh_nodes,
&bvh_objects,
structure_table.pointers_buffer(),
structure_table.request_pages_buffer(),
);
Self {
objects: Default::default(),
slots: Default::default(),
structure_table,
current_key: 0,
bvh_nodes,
bvh_objects,
node_capacity: 1,
object_capacity: 1,
node_count: 0,
object_count: 0,
raytrace_bind_group_layout,
raytrace_bind_group,
dirty: false,
}
}
pub fn add(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
object: BvhObject,
) -> BvhHandle
{
let key = self.current_key;
self.current_key += 1;
let handle = BvhHandle {
anchor: object.anchor,
producer_id: object.producer_id,
key,
};
let slot = self
.structure_table
.allocate_or_grow(device, queue, object.anchor)
.unwrap();
self.slots.insert(handle, slot);
self.objects.insert(handle, object);
self.dirty = true;
handle
}
pub fn build(&self) -> (Vec<GpuBvhNode>, Vec<GpuObject>)
{
// Collect primitives
let mut primitives = self
.objects
.iter()
.map(|(handle, object)| BvhPrimitive {
aabb: object.world_bounding_box(),
handle: *handle,
})
.collect::<Vec<_>>();
let bvh = build_bvh(&mut primitives, 2);
// Build gpu bvh
let gpu_nodes = bvh
.nodes
.iter()
.map(|node| (*node).into())
.collect::<Vec<GpuBvhNode>>();
let gpu_primitives = primitives
.iter()
.map(|primitive| {
GpuObject::new(
*self.slots.get(&primitive.handle).expect("Unallocated slot"),
self.objects
.get(&primitive.handle)
.expect("Object removed")
.transform,
)
})
.collect::<Vec<_>>();
(gpu_nodes, gpu_primitives)
}
/// Marks the CPU BVH as changed. The GPU buffers are rebuilt on the next
/// [`Self::rebuild_if_dirty`] call.
pub fn mark_dirty(&mut self)
{
self.dirty = true;
}
/// Returns true if the GPU buffers no longer match the CPU BVH.
pub fn is_dirty(&self) -> bool
{
self.dirty
}
/// Rebuilds the CPU BVH and uploads it to the GPU.
pub fn rebuild(&mut self, device: &wgpu::Device, queue: &wgpu::Queue)
{
let (nodes, objects) = self.build();
self.upload(device, queue, &nodes, &objects);
}
/// Rebuilds only if the BVH changed since the last upload.
pub fn rebuild_if_dirty(&mut self, device: &wgpu::Device, queue: &wgpu::Queue)
{
if self.dirty
{
self.rebuild(device, queue);
}
}
fn upload(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
nodes: &[GpuBvhNode],
objects: &[GpuObject],
)
{
let node_capacity = grown_capacity(self.node_capacity, nodes.len());
if node_capacity > self.node_capacity
{
self.node_capacity = node_capacity;
self.bvh_nodes = create_bvh_buffer::<GpuBvhNode>(device, node_capacity, "bvh_nodes");
}
let object_capacity = grown_capacity(self.object_capacity, objects.len());
if object_capacity > self.object_capacity
{
self.object_capacity = object_capacity;
self.bvh_objects =
create_bvh_buffer::<GpuObject>(device, object_capacity, "bvh_objects");
}
if !nodes.is_empty()
{
queue.write_buffer(&self.bvh_nodes, 0, bytemuck::cast_slice(nodes));
}
if !objects.is_empty()
{
queue.write_buffer(&self.bvh_objects, 0, bytemuck::cast_slice(objects));
}
self.node_count = nodes.len() as u32;
self.object_count = objects.len() as u32;
// The inner table may have grown (replacing its buffers) since the last
// bind group was created, so always recreate it after an upload.
let raytrace_bind_group = create_bvh_raytrace_bind_group(
device,
&self.raytrace_bind_group_layout,
&self.bvh_nodes,
&self.bvh_objects,
self.structure_table.pointers_buffer(),
self.structure_table.request_pages_buffer(),
);
self.raytrace_bind_group = raytrace_bind_group;
self.dirty = false;
}
pub fn bvh_nodes(&self) -> &wgpu::Buffer
{
&self.bvh_nodes
}
pub fn bvh_objects(&self) -> &wgpu::Buffer
{
&self.bvh_objects
}
pub fn node_count(&self) -> u32
{
self.node_count
}
pub fn object_count(&self) -> u32
{
self.object_count
}
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
{
&self.raytrace_bind_group_layout
}
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
{
&self.raytrace_bind_group
}
}
fn create_bvh_buffer<T>(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer
{
let capacity = capacity.max(1);
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: (capacity * size_of::<T>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
fn grown_capacity(current: usize, required: usize) -> usize
{
if required <= current
{
return current;
}
let mut capacity = current.max(1);
while capacity < required
{
capacity = capacity.saturating_mul(2);
}
capacity
}
fn create_bvh_raytrace_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
let storage = |read_only: bool| wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
};
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("BvhStructureTable::raytrace_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(true),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(true),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(false),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(false),
count: None,
},
],
})
}
fn create_bvh_raytrace_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
nodes: &wgpu::Buffer,
objects: &wgpu::Buffer,
structure_pointers: &wgpu::Buffer,
structure_requests: &wgpu::Buffer,
) -> wgpu::BindGroup
{
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("BvhStructureTable::raytrace_bind_group"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: nodes.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: objects.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: structure_pointers.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: structure_requests.as_entire_binding(),
},
],
})
}
+468
View File
@@ -0,0 +1,468 @@
//! Axis aligned bounding box used by the BVH build.
use glam::Mat4;
use glam::Vec3;
/// An axis aligned bounding box.
///
/// A box is empty when `min` is greater than `max` on any axis. [`Aabb::EMPTY`]
/// uses inverted infinities, which makes it the identity element for
/// [`Aabb::union`] and [`Aabb::union_point`].
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub struct Aabb
{
min: Vec3,
max: Vec3,
}
impl Aabb
{
/// The empty box: it contains no point and is the identity element for
/// union operations.
pub const EMPTY: Self = Self {
min: Vec3::INFINITY,
max: Vec3::NEG_INFINITY,
};
/// The local voxel chunk space is [0,1]^3.
/// This is the box that encompasses that block.
pub const CHUNK: Self = Self {
min: Vec3::ZERO,
max: Vec3::ONE,
};
/// Builds a box from its corners.
///
/// No validation is performed so that [`Aabb::EMPTY`] can be built; use
/// [`Aabb::is_empty`] to check the result.
pub const fn new(min: Vec3, max: Vec3) -> Self
{
Self { min, max }
}
/// Builds a box from a center and the half extents along each axis.
pub fn from_center_half_extents(center: Vec3, half_extents: Vec3) -> Self
{
Self {
min: center - half_extents,
max: center + half_extents,
}
}
/// Builds the tightest box containing every point.
///
/// An empty iterator produces [`Aabb::EMPTY`].
pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Self
{
let mut aabb = Self::EMPTY;
for point in points
{
aabb.union_point(point);
}
aabb
}
pub const fn min(&self) -> Vec3
{
self.min
}
pub const fn max(&self) -> Vec3
{
self.max
}
/// Center of the box. Not meaningful for an empty box.
pub fn center(&self) -> Vec3
{
(self.min + self.max) * 0.5
}
/// Full extent of the box along each axis (`max - min`).
pub fn size(&self) -> Vec3
{
self.max - self.min
}
/// Half extent of the box along each axis.
pub fn half_size(&self) -> Vec3
{
self.size() * 0.5
}
/// Surface area of the box, used by SAH heuristics.
pub fn surface_area(&self) -> f32
{
let size = self.size();
2.0 * (size.x * size.y + size.y * size.z + size.z * size.x)
}
pub fn volume(&self) -> f32
{
self.size().element_product()
}
/// Index of the axis with the largest extent (0 = x, 1 = y, 2 = z).
///
/// Ties are broken in favor of the lower axis.
pub fn longest_axis(&self) -> usize
{
let size = self.size();
if size.x >= size.y && size.x >= size.z
{
0
}
else if size.y >= size.z
{
1
}
else
{
2
}
}
/// Returns `true` when the box contains no point.
pub fn is_empty(&self) -> bool
{
self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
}
/// Returns `true` when both corners are finite.
pub fn is_finite(&self) -> bool
{
self.min.is_finite() && self.max.is_finite()
}
pub fn contains_point(&self, point: Vec3) -> bool
{
point.cmpge(self.min).all() && point.cmple(self.max).all()
}
/// Returns `true` when `other` is fully inside `self`.
///
/// An empty `other` is contained in every box.
pub fn contains(&self, other: &Self) -> bool
{
other.is_empty() || (self.min.cmple(other.min).all() && self.max.cmpge(other.max).all())
}
/// Returns `true` when both boxes share at least one point.
///
/// Boxes touching exactly on a face, edge or corner do intersect.
pub fn intersects(&self, other: &Self) -> bool
{
!self.is_empty()
&& !other.is_empty()
&& self.min.cmple(other.max).all()
&& other.min.cmple(self.max).all()
}
/// Overlap of both boxes.
///
/// The result is empty when the boxes do not intersect.
pub fn intersection(&self, other: &Self) -> Self
{
Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
}
}
/// Grows the box to contain `point`.
pub fn union_point(&mut self, point: Vec3)
{
self.min = self.min.min(point);
self.max = self.max.max(point);
}
/// Grows the box to contain `other`.
pub fn union(&mut self, other: &Self)
{
self.min = self.min.min(other.min);
self.max = self.max.max(other.max);
}
/// Returns a copy of the box grown by `margin` on every side.
pub fn expanded(&self, margin: f32) -> Self
{
let margin = Vec3::splat(margin);
Self {
min: self.min - margin,
max: self.max + margin,
}
}
/// Returns a copy of the box with every axis at least `min_size` long,
/// keeping the center unchanged.
///
/// This avoids degenerate (flat) boxes, which are problematic for SAH
/// splitting. An empty box is returned unchanged.
pub fn padded_to_min_size(&self, min_size: f32) -> Self
{
if self.is_empty()
{
return Self::EMPTY;
}
let half_extents = self.half_size().max(Vec3::splat(min_size * 0.5));
Self::from_center_half_extents(self.center(), half_extents)
}
/// Returns an iterator over all of the corner points of the box
pub fn corner_points(&self) -> impl Iterator<Item = Vec3>
{
(0..=7).map(|i| {
let a = &self.min;
let b = &self.max;
Vec3::new(
if i & 1 == 0 { a.x } else { b.x },
if i & 2 == 0 { a.y } else { b.y },
if i & 4 == 0 { a.z } else { b.z },
)
})
}
/// Returns the Aabb bounding box of the box transformed by `transformed`
pub fn as_transformed_by(&self, transform: &Mat4) -> Self
{
Self::from_points(
self.corner_points()
.map(|point| transform.transform_point3(point)),
)
}
}
impl Default for Aabb
{
fn default() -> Self
{
Self::EMPTY
}
}
#[cfg(test)]
mod tests
{
use super::*;
const EPSILON: f32 = 1e-6;
fn assert_vec3_eq(a: Vec3, b: Vec3)
{
assert!(
(a - b).abs().max_element() <= EPSILON,
"expected {b:?}, got {a:?}"
);
}
#[test]
fn empty_box_contains_nothing()
{
let aabb = Aabb::EMPTY;
assert!(aabb.is_empty());
assert!(!aabb.contains_point(Vec3::ZERO));
assert!(!aabb.intersects(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn empty_is_identity_for_union()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
let mut grown = Aabb::EMPTY;
grown.union(&aabb);
assert_eq!(grown, aabb);
let mut grown = aabb;
grown.union(&Aabb::EMPTY);
assert_eq!(grown, aabb);
}
#[test]
fn from_points_of_empty_iterator_is_empty()
{
assert!(Aabb::from_points(std::iter::empty()).is_empty());
}
#[test]
fn from_points_bounds_all_points()
{
let points = [
Vec3::new(1.0, -2.0, 3.0),
Vec3::new(-4.0, 5.0, -6.0),
Vec3::new(0.0, 0.0, 0.0),
];
let aabb = Aabb::from_points(points);
assert_eq!(aabb.min(), Vec3::new(-4.0, -2.0, -6.0));
assert_eq!(aabb.max(), Vec3::new(1.0, 5.0, 3.0));
for point in points
{
assert!(aabb.contains_point(point));
}
}
#[test]
fn center_and_size()
{
let aabb = Aabb::new(Vec3::new(-1.0, 0.0, 2.0), Vec3::new(3.0, 4.0, 6.0));
assert_vec3_eq(aabb.center(), Vec3::new(1.0, 2.0, 4.0));
assert_vec3_eq(aabb.size(), Vec3::new(4.0, 4.0, 4.0));
assert_vec3_eq(aabb.half_size(), Vec3::new(2.0, 2.0, 2.0));
}
#[test]
fn from_center_half_extents_round_trips()
{
let aabb = Aabb::from_center_half_extents(Vec3::new(1.0, 2.0, 3.0), Vec3::splat(2.0));
assert_eq!(aabb.min(), Vec3::new(-1.0, 0.0, 1.0));
assert_eq!(aabb.max(), Vec3::new(3.0, 4.0, 5.0));
}
#[test]
fn union_grows_to_contain_both_boxes()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::splat(2.0), Vec3::splat(4.0));
let mut union = a;
union.union(&b);
assert_eq!(union.min(), Vec3::ZERO);
assert_eq!(union.max(), Vec3::splat(4.0));
assert!(union.contains(&a));
assert!(union.contains(&b));
}
#[test]
fn contains_point_respects_faces()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
assert!(aabb.contains_point(Vec3::ZERO));
assert!(aabb.contains_point(Vec3::ONE));
assert!(aabb.contains_point(Vec3::splat(0.5)));
assert!(!aabb.contains_point(Vec3::splat(-EPSILON)));
assert!(!aabb.contains_point(Vec3::splat(1.0 + EPSILON)));
}
#[test]
fn contains_box()
{
let outer = Aabb::new(Vec3::ZERO, Vec3::splat(4.0));
let inner = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(outer.contains(&inner));
assert!(!inner.contains(&outer));
assert!(outer.contains(&Aabb::EMPTY));
}
#[test]
fn separated_boxes_do_not_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0));
assert!(!a.intersects(&b));
assert!(!b.intersects(&a));
assert!(a.intersection(&b).is_empty());
}
#[test]
fn touching_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 1.0, 1.0));
assert!(a.intersects(&b));
assert_eq!(a.intersection(&b).size(), Vec3::new(0.0, 1.0, 1.0));
}
#[test]
fn overlapping_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::splat(2.0));
let b = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(a.intersects(&b));
let intersection = a.intersection(&b);
assert_eq!(intersection.min(), Vec3::ONE);
assert_eq!(intersection.max(), Vec3::splat(2.0));
}
#[test]
fn surface_area_and_volume()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0));
assert!((aabb.volume() - 24.0).abs() <= EPSILON);
assert!((aabb.surface_area() - 52.0).abs() <= EPSILON);
}
#[test]
fn longest_axis_picks_largest_extent()
{
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(3.0, 1.0, 2.0)).longest_axis(),
0
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 3.0, 2.0)).longest_axis(),
1
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)).longest_axis(),
2
);
}
#[test]
fn expanded_adds_margin_on_every_side()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE).expanded(0.5);
assert_eq!(aabb.min(), Vec3::splat(-0.5));
assert_eq!(aabb.max(), Vec3::splat(1.5));
assert!(aabb.contains(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn padded_to_min_size_keeps_flat_box_usable()
{
let flat = Aabb::new(Vec3::new(0.0, 0.0, 5.0), Vec3::new(2.0, 2.0, 5.0));
let padded = flat.padded_to_min_size(1.0);
assert!(!padded.is_empty());
assert!((padded.size().z - 1.0).abs() <= EPSILON);
assert_eq!(padded.size().x, 2.0);
assert_eq!(padded.size().y, 2.0);
assert_vec3_eq(padded.center(), flat.center());
assert!(padded.contains(&flat));
}
#[test]
fn padded_empty_box_stays_empty()
{
assert!(Aabb::EMPTY.padded_to_min_size(1.0).is_empty());
}
#[test]
fn default_is_empty()
{
assert_eq!(Aabb::default(), Aabb::EMPTY);
assert!(Aabb::default().is_empty());
}
#[test]
fn layout_is_two_vec3s()
{
assert_eq!(std::mem::size_of::<Aabb>(), 24);
assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24);
}
}
+354
View File
@@ -0,0 +1,354 @@
//! Implementation of fast binary BVH build with binned SAH
//!
use std::num::NonZero;
use egui::emath::OrderedFloat;
use crate::bvh::gpu::GpuBvhNode;
use super::aabb::Aabb;
macro_rules! get_dim {
($v:expr, $d:expr) => {
match $d
{
0 => $v.x,
1 => $v.y,
_ => $v.z,
}
};
}
// Sah heuristic parameters
/// Intersection time
const SAH_INTERSECT: f32 = 1.;
/// Bin count
const SAH_BIN_COUNT: usize = 16;
#[derive(Clone, Copy)]
pub struct BvhNode
{
/// The bounding box of this bvh node
aabb: Aabb,
/// 0 if this is not a leaf
/// n if it is a leaf containing objects
count: u32,
/// If this node is not a leaf, the index in the list of nodes of the left node
/// Otherwise the index in the list of primitive of the first object
first_or_left: u32,
}
impl From<GpuBvhNode> for BvhNode
{
fn from(value: GpuBvhNode) -> Self
{
Self {
aabb: value.aabb.into(),
count: value.count,
first_or_left: value.first_or_left,
}
}
}
impl From<BvhNode> for GpuBvhNode
{
fn from(value: BvhNode) -> Self
{
GpuBvhNode {
aabb: value.aabb.into(),
count: value.count,
first_or_left: value.first_or_left,
}
}
}
impl BvhNode
{
pub fn internal(aabb: Aabb, left: u32) -> BvhNode
{
Self {
aabb,
count: 0,
first_or_left: left,
}
}
pub fn leaf(aabb: Aabb, count: NonZero<u32>, first_index: u32) -> BvhNode
{
Self {
aabb,
count: count.into(),
first_or_left: first_index,
}
}
pub fn is_internal(&self) -> bool
{
self.count == 0
}
pub fn is_leaf(&self) -> bool
{
self.count != 0
}
pub fn first(&self) -> Option<u32>
{
if !self.is_leaf()
{
None
}
else
{
Some(self.first_or_left)
}
}
pub fn count(&self) -> Option<u32>
{
if !self.is_leaf()
{
None
}
else
{
Some(self.count)
}
}
pub fn left(&self) -> Option<u32>
{
if !self.is_internal()
{
None
}
else
{
Some(self.first_or_left)
}
}
pub fn right(&self) -> Option<u32>
{
self.left().map(|x| x + 1)
}
}
pub struct BvhPrimitive<T>
{
pub aabb: Aabb,
pub handle: T,
}
pub struct Bvh
{
/// List of the bvh's nodes
pub nodes: Vec<BvhNode>,
}
pub fn build_bvh<T>(primitives: &mut [BvhPrimitive<T>], leaf_max: usize) -> Bvh
{
let mut nodes = Vec::new();
//let mut prim_indices = Vec::new();
if primitives.is_empty()
{
return Bvh {
nodes,
//prim_indices,
};
}
// Build root node
let mut aabb = Aabb::EMPTY;
primitives.iter().for_each(|p| aabb.union(&p.aabb));
nodes.push(BvhNode::leaf(
aabb,
NonZero::new(primitives.len() as u32).unwrap(),
0,
));
build_node(0, primitives, &mut nodes, leaf_max);
Bvh { nodes }
}
pub fn build_node<T>(
node_index: usize,
primitives: &mut [BvhPrimitive<T>],
nodes: &mut Vec<BvhNode>,
leaf_max: usize,
)
{
// We only extend a leaf if necessary
assert!(nodes[node_index].is_leaf());
let offset = nodes[node_index].first().expect("Node is leaf");
let count = nodes[node_index].count().expect("Node is leaf");
// Primitives owned by this node
let node_primitives = &mut primitives[(offset as usize)..((offset + count) as usize)];
// We must now decide to keep the node as a leaf, or split using the heuristic:
let split = sah_split(node_primitives, leaf_max);
match split
{
Some((split_dimension, split_plane)) =>
{
// Sah says split, do the split
// We sort along the split dimension
node_primitives.sort_unstable_by_key(|primitive| {
OrderedFloat(get_dim!(primitive.aabb.center(), split_dimension))
});
// We now now that the split_plane splits node_primitives into two subslices
let mut left_count = 0u32;
let mut left_aabb = Aabb::EMPTY;
let mut right_aabb = Aabb::EMPTY;
for primitive in node_primitives.iter()
{
if get_dim!(primitive.aabb.center(), split_dimension) < split_plane
{
left_count += 1;
left_aabb.union(&primitive.aabb);
}
else
{
right_aabb.union(&primitive.aabb);
}
}
let right_count = node_primitives.len() as u32 - left_count;
let left_node = BvhNode::leaf(
left_aabb,
NonZero::new(left_count).expect("Empty leaf impossible."),
offset,
);
let right_node = BvhNode::leaf(
right_aabb,
NonZero::new(right_count).expect("Empty leaf impossible."),
offset + left_count, // As the slice is sorted
);
// Allocate spot in the node array
let left_index = nodes.len();
// Left and right are contiguous
nodes.push(left_node);
nodes.push(right_node);
// Change this node to be internal
nodes[node_index] = BvhNode::internal(nodes[node_index].aabb, left_index as u32);
// Build children
build_node(left_index, primitives, nodes, leaf_max);
build_node(left_index + 1, primitives, nodes, leaf_max);
}
None =>
{
// Sah says keep as leaf, do nothing
}
}
}
/// Returns Some if SAH says split, none if it wants a leaf
pub fn sah_split<T>(primitives: &[BvhPrimitive<T>], leaf_max: usize) -> Option<(usize, f32)>
{
// Don't even bother, spliting it does nothing
if primitives.len() <= 2
{
return None;
}
// Cost if this node was a leaf
let leaf_sah = primitives.len() as f32 * SAH_INTERSECT;
// Compute the bounding box contains the centroids of the primitives
let mut centroid_bounds = Aabb::EMPTY;
primitives
.iter()
.for_each(|prim| centroid_bounds.union_point(prim.aabb.center()));
// Evaluate sah per dimension
let mut best_dimension = 0;
let mut minimum_cost = f32::INFINITY;
let mut minimum_split_plane = 0.;
for dimension in 0..3usize
{
let cetroid_min = get_dim!(centroid_bounds.min(), dimension);
// The size of a bin in this dimension
let bin_width = get_dim!(centroid_bounds.size(), dimension) / SAH_BIN_COUNT as f32;
// Indicies of elements per bin
let mut bins: [Aabb; SAH_BIN_COUNT] = Default::default();
let mut bin_counts: [usize; SAH_BIN_COUNT] = Default::default();
// Bin elements
for primitive in primitives.iter()
{
let centroid = get_dim!(primitive.aabb.center(), dimension);
let bin_index =
(((centroid - cetroid_min) / bin_width) as usize).clamp(0, SAH_BIN_COUNT - 1);
// Put it into its bin
bins[bin_index].union(&primitive.aabb);
bin_counts[bin_index] += 1;
}
// Build prefix and suffix bins
let mut prefix: [Aabb; SAH_BIN_COUNT] = bins;
let mut prefix_counts: [usize; SAH_BIN_COUNT] = bin_counts;
let mut suffix: [Aabb; SAH_BIN_COUNT] = bins;
let mut suffix_counts: [usize; SAH_BIN_COUNT] = bin_counts;
// We build prefix and suffix simultaneously
for i in 1..SAH_BIN_COUNT
{
let prefix_previous = prefix[i - 1];
prefix[i].union(&prefix_previous);
prefix_counts[i] += prefix_counts[i - 1];
let suffix_previous = suffix[SAH_BIN_COUNT - i];
suffix[SAH_BIN_COUNT - 1 - i].union(&suffix_previous);
suffix_counts[SAH_BIN_COUNT - 1 - i] += suffix_counts[SAH_BIN_COUNT - i];
}
// Chose a split
// We iterate only up to SAH_BIN_COUNT - 1
// as we dont want to put all primitves on the left or right
for i in 0..(SAH_BIN_COUNT - 1)
{
let left_sah = prefix[i].surface_area() * prefix_counts[i] as f32;
let right_sah = suffix[i + 1].surface_area() * suffix_counts[i + 1] as f32;
let split_sah = left_sah + right_sah;
if split_sah < minimum_cost
{
best_dimension = dimension;
minimum_cost = split_sah;
// Take bin boundary as split point
minimum_split_plane = cetroid_min + (i + 1) as f32 * bin_width;
}
}
}
if leaf_sah < minimum_cost && primitives.len() <= leaf_max
{
// SAH requires leaf
None
}
else
{
// SAH requires split
Some((best_dimension, minimum_split_plane))
}
}
+257
View File
@@ -0,0 +1,257 @@
//! Contains rendering code to display a debug overlay for the BVH.
use glam::Mat4;
// debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync:
// WGSL would otherwise round them up to 16-byte alignment.
const _: () = {
assert!(size_of::<crate::bvh::gpu::GpuBvhNode>() == 40);
assert!(size_of::<crate::bvh::gpu::GpuObject>() == 144);
};
/// Renders a GPU BVH as debug geometry.
///
/// Every node's AABB is drawn as a wireframe box. Leaves additionally draw one
/// filled box per object, using the object's `local_to_world` transform on the
/// local `[0, 1]^3` cube.
///
/// One instance is one `GpuBvhNode`; the shader generates all vertices, so no
/// vertex or index buffer is needed.
pub struct BvhDebugPipeline
{
solid_pipeline: wgpu::RenderPipeline,
line_pipeline: wgpu::RenderPipeline,
bind_group_layout: wgpu::BindGroupLayout,
view_proj_buffer: wgpu::Buffer,
}
impl BvhDebugPipeline
{
/// `color_format` must match the render pass attachment, including its sRGB
/// suffix. `depth_format` must match `depth_view` in [`Self::render`].
pub fn new(
device: &wgpu::Device,
color_format: wgpu::TextureFormat,
depth_format: wgpu::TextureFormat,
) -> Self
{
let shader = device.create_shader_module(wgpu::include_wgsl!("debug.wgsl"));
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("bvh_debug_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(
size_of::<Mat4>() as u64
),
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("bvh_debug_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let view_proj_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("bvh_debug_view_proj_buffer"),
size: size_of::<Mat4>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let create_pipeline =
|label: &str,
vertex_entry: &str,
fragment_entry: &str,
topology: wgpu::PrimitiveTopology,
depth_write_enabled: bool|
-> wgpu::RenderPipeline {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(vertex_entry),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState {
topology,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
// Boxes stay visible even when the camera is inside one.
cull_mode: None,
unclipped_depth: false,
polygon_mode: wgpu::PolygonMode::Fill,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: depth_format,
depth_write_enabled: Some(depth_write_enabled),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(fragment_entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let solid_pipeline = create_pipeline(
"bvh_debug_solid_pipeline",
"vs_solids",
"fs_solids",
wgpu::PrimitiveTopology::TriangleList,
true,
);
let line_pipeline = create_pipeline(
"bvh_debug_line_pipeline",
"vs_lines",
"fs_lines",
wgpu::PrimitiveTopology::LineList,
false,
);
Self {
solid_pipeline,
line_pipeline,
bind_group_layout,
view_proj_buffer,
}
}
/// Records a debug render pass into `encoder`.
///
/// The pass loads the existing color contents, overlays the BVH, and clears
/// the depth buffer before drawing. Record it after the scene has been
/// written to `color_view` and before the UI is drawn.
///
/// `max_objects_per_leaf` is the leaf capacity used when building the BVH
/// (the `leaf_max` argument of `build_bvh`), currently `2`.
#[allow(clippy::too_many_arguments)]
pub fn render(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
color_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
view_proj: Mat4,
node_buffer: &wgpu::Buffer,
object_buffer: &wgpu::Buffer,
node_count: u32,
max_objects_per_leaf: u32,
)
{
if node_count == 0
{
return;
}
queue.write_buffer(
&self.view_proj_buffer,
0,
bytemuck::bytes_of(&view_proj),
);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("bvh_debug_bind_group"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: node_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: object_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.view_proj_buffer.as_entire_binding(),
},
],
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("bvh_debug_render_pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &bind_group, &[]);
// Filled object boxes first so the wireframes can depth-test against
// them.
if max_objects_per_leaf > 0
{
pass.set_pipeline(&self.solid_pipeline);
pass.draw(
0..36 * max_objects_per_leaf,
0..node_count,
);
}
pass.set_pipeline(&self.line_pipeline);
pass.draw(0..24, 0..node_count);
}
}
+202
View File
@@ -0,0 +1,202 @@
//! Debug rendering for the GPU BVH.
//!
//! Every box is generated procedurally from the vertex index, so there is no
//! mesh or vertex buffer. One instance is one `GpuBvhNode`.
struct GpuBvhNode
{
// Kept as scalar fields on purpose. WGSL rounds structs containing vec3/vec4
// up to a 16-byte alignment (48-byte array stride), while the Rust side is
// a 40-byte `#[repr(C)]` struct.
min_x: f32,
min_y: f32,
min_z: f32,
_pad0: f32,
max_x: f32,
max_y: f32,
max_z: f32,
_pad1: u32,
count: u32,
first_or_left: u32,
};
struct GpuObject
{
local_to_world: mat4x4<f32>,
world_to_local: mat4x4<f32>,
table_slot: u32,
_pad0: u32,
_pad1: u32,
_pad2: u32,
};
@group(0) @binding(0) var<storage, read> nodes: array<GpuBvhNode>;
@group(0) @binding(1) var<storage, read> objects: array<GpuObject>;
@group(0) @binding(2) var<uniform> view_proj: mat4x4<f32>;
struct VertexOutput
{
@builtin(position) clip_position: vec4<f32>,
@location(0) color: vec3<f32>,
@location(1) normal: vec3<f32>,
};
const INTERNAL_NODE_COLOR = vec3<f32>(0.15, 0.70, 1.0);
const LEAF_NODE_COLOR = vec3<f32>(1.0, 0.85, 0.20);
const OBJECT_COLOR = vec3<f32>(1.0, 0.45, 0.12);
// Pushed fully outside the clip volume so skipped nodes/objects produce no
// fragments.
const DEGENERATE_POSITION = vec4<f32>(2.0, 2.0, 2.0, 1.0);
const VERTICES_PER_OBJECT: u32 = 36u;
// Corner numbering: bit 0 = x, bit 1 = y, bit 2 = z.
const EDGE_CORNERS = array<u32, 24>(
// -Z face
0u, 1u, 1u, 3u, 3u, 2u, 2u, 0u,
// +Z face
4u, 5u, 5u, 7u, 7u, 6u, 6u, 4u,
// vertical edges
0u, 4u, 1u, 5u, 2u, 6u, 3u, 7u,
);
const TRIANGLE_CORNERS = array<u32, 36>(
// -Z
0u, 2u, 1u, 1u, 2u, 3u,
// +Z
4u, 5u, 6u, 5u, 7u, 6u,
// -Y
0u, 1u, 4u, 1u, 5u, 4u,
// +Y
2u, 6u, 3u, 3u, 6u, 7u,
// -X
0u, 4u, 2u, 2u, 4u, 6u,
// +X
1u, 3u, 5u, 3u, 7u, 5u,
);
const FACE_NORMALS = array<vec3<f32>, 6>(
vec3<f32>(0.0, 0.0, -1.0),
vec3<f32>(0.0, 0.0, 1.0),
vec3<f32>(0.0, -1.0, 0.0),
vec3<f32>(0.0, 1.0, 0.0),
vec3<f32>(-1.0, 0.0, 0.0),
vec3<f32>(1.0, 0.0, 0.0),
);
fn corner_position(min_corner: vec3<f32>, max_corner: vec3<f32>, corner: u32) -> vec3<f32>
{
return vec3<f32>(
select(min_corner.x, max_corner.x, (corner & 1u) != 0u),
select(min_corner.y, max_corner.y, (corner & 2u) != 0u),
select(min_corner.z, max_corner.z, (corner & 4u) != 0u),
);
}
@vertex
fn vs_lines(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput
{
var out: VertexOutput;
out.clip_position = DEGENERATE_POSITION;
out.color = INTERNAL_NODE_COLOR;
out.normal = vec3<f32>(0.0, 0.0, 1.0);
if instance_index >= arrayLength(&nodes)
{
return out;
}
let node = nodes[instance_index];
let min_corner = vec3<f32>(node.min_x, node.min_y, node.min_z);
let max_corner = vec3<f32>(node.max_x, node.max_y, node.max_z);
let world_position = corner_position(
min_corner,
max_corner,
EDGE_CORNERS[vertex_index],
);
out.clip_position = view_proj * vec4<f32>(world_position, 1.0);
if node.count != 0u
{
out.color = LEAF_NODE_COLOR;
}
return out;
}
@vertex
fn vs_solids(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput
{
var out: VertexOutput;
out.clip_position = DEGENERATE_POSITION;
out.color = OBJECT_COLOR;
out.normal = vec3<f32>(0.0, 0.0, 1.0);
if instance_index >= arrayLength(&nodes)
{
return out;
}
let node = nodes[instance_index];
// Only leaves own objects.
if node.count == 0u
{
return out;
}
let object_index = vertex_index / VERTICES_PER_OBJECT;
if object_index >= node.count
{
return out;
}
let object_array_index = node.first_or_left + object_index;
if object_array_index >= arrayLength(&objects)
{
return out;
}
let object = objects[object_array_index];
let local_vertex_index = vertex_index % VERTICES_PER_OBJECT;
let local_position = corner_position(
vec3<f32>(0.0, 0.0, 0.0),
vec3<f32>(1.0, 1.0, 1.0),
TRIANGLE_CORNERS[local_vertex_index],
);
let world_position = object.local_to_world * vec4<f32>(local_position, 1.0);
out.clip_position = view_proj * world_position;
// normals transform with the inverse transpose of local_to_world, which is
// transpose(world_to_local).
let face = local_vertex_index / 6u;
out.normal = normalize(
(transpose(object.world_to_local) * vec4<f32>(FACE_NORMALS[face], 0.0)).xyz,
);
return out;
}
@fragment
fn fs_lines(input: VertexOutput) -> @location(0) vec4<f32>
{
return vec4<f32>(input.color, 1.0);
}
@fragment
fn fs_solids(input: VertexOutput) -> @location(0) vec4<f32>
{
let normal = normalize(input.normal);
let light_direction = normalize(vec3<f32>(0.45, 0.80, 0.55));
let diffuse = max(dot(normal, light_direction), 0.0);
return vec4<f32>(input.color * (0.35 + 0.65 * diffuse), 1.0);
}
+79
View File
@@ -0,0 +1,79 @@
//! GPU ready structures for the BVH representation
use glam::Mat4;
use glam::Vec3;
use crate::bvh::aabb::Aabb;
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuAabb
{
pub min: Vec3,
_pad0: u32, // On the GPU vec3 are aligned to 4 u32
pub max: Vec3,
_pad1: u32,
}
/// Follow the same documentation as [`BvhNode`]
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuBvhNode
{
pub aabb: GpuAabb,
pub count: u32,
pub first_or_left: u32,
}
/// To be a leaf of a GPU BVH
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuObject
{
local_to_world: Mat4, // Tranform
world_to_local: Mat4, // Ray to chunk
table_slot: u32,
_pad0: [u32; 3],
}
impl From<Aabb> for GpuAabb
{
fn from(value: Aabb) -> Self
{
Self::new(value.min(), value.max())
}
}
impl From<GpuAabb> for Aabb
{
fn from(value: GpuAabb) -> Self
{
Aabb::new(value.min, value.max)
}
}
impl GpuObject
{
pub fn new(slot: u32, transform: Mat4) -> Self
{
GpuObject {
local_to_world: transform,
world_to_local: transform.inverse(),
table_slot: slot,
_pad0: Default::default(),
}
}
}
impl GpuAabb
{
pub fn new(min: Vec3, max: Vec3) -> Self
{
Self {
min,
_pad0: Default::default(),
max,
_pad1: Default::default(),
}
}
}
-837
View File
@@ -1,837 +0,0 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use std::hash::Hash;
use std::vec;
use itertools::Itertools;
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Color(pub f32, pub f32, pub f32, pub f32);
pub struct NTree<const N: usize>
{
structure: HashMap<NTreeLocator<N>, NTreeNode<N>>,
depth: u32,
}
#[derive(Clone, Copy)]
struct NTreeNode<const N: usize>
{
color: Color,
subdivided: bool,
}
impl<const N: usize> NTree<N>
where
[(); N * N * N]:,
{
pub fn constant(color: Color, depth: u32) -> Self
{
let mut structure = HashMap::new();
structure.insert(
NTreeLocator::root(),
NTreeNode {
color,
subdivided: false,
},
);
Self { structure, depth }
}
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
{
let mut local_x = x;
let mut local_y = y;
let mut local_z = z;
let mut size = N.pow(self.depth);
assert!(x < size && y < size && z < size);
let mut current_loc = NTreeLocator::<N>::root();
let mut current_node = *self.structure.get(&current_loc).unwrap();
loop
{
if !current_node.subdivided
{
return current_node.color;
}
size /= N;
// Descend
let child_x = local_x / size;
let child_y = local_y / size;
let child_z = local_z / size;
// Node is subdivided, descend
current_loc = current_loc.get_child(child_x, child_y, child_z);
current_node = *self.structure.get(&current_loc).unwrap();
local_x -= child_x * size;
local_y -= child_y * size;
local_z -= child_z * size;
}
}
pub fn from_arrays_old(chunk: &[Color], depth: u32) -> Self
{
let chunk_width = N.pow(depth);
let mut structure = HashMap::with_capacity(chunk_width * chunk_width * chunk_width);
println!("Inserting voxels");
for ((x, y), z) in (0..chunk_width)
.cartesian_product(0..chunk_width)
.cartesian_product(0..chunk_width)
{
structure.insert(
NTreeLocator::<N>::from_depth_coords(x, y, z, depth as usize),
NTreeNode::<N> {
color: chunk[x + y * chunk_width + z * chunk_width * chunk_width],
subdivided: false,
},
);
}
println!("Starting bottom up");
let mut current_size = 1;
for d in (0..depth).rev()
{
println!("depth: {d}");
current_size *= N;
for ((x, y), z) in (0..(chunk_width / current_size))
.cartesian_product(0..(chunk_width / current_size))
.cartesian_product(0..(chunk_width / current_size))
{
let loc = NTreeLocator::<N>::from_depth_coords(x, y, z, d as usize);
let children = (0..N)
.cartesian_product(0..N)
.cartesian_product(0..N)
.map(|((cx, cy), cz)| structure.get(&loc.get_child(cx, cy, cz)).unwrap())
.collect::<Vec<_>>();
let (can_merge, _) = children.iter().fold((true, None), |acc, child| match acc
{
(_, None) => (true, Some(child.color)),
(b, Some(color)) =>
{
(b && !child.subdivided && color == child.color, Some(color))
}
});
let node;
if can_merge
{
node = NTreeNode::<N> {
color: children[0].color,
subdivided: false,
};
//Remove merged childrenn
(0..N)
.cartesian_product(0..N)
.cartesian_product(0..N)
.for_each(|((cx, cy), cz)| {
structure.remove(&loc.get_child(cx, cy, cz)).unwrap();
});
}
else
{
node = NTreeNode::<N> {
color: Color::average(
children
.iter()
.map(|x| x.color)
.collect::<Vec<_>>()
.as_slice(),
),
subdivided: true,
};
}
structure.insert(loc, node);
}
}
Self { structure, depth }
}
pub fn from_arrays(chunk: &[Color], depth: usize) -> Self
{
let width = N.pow(depth as u32);
let mut structure = HashMap::new();
let mut taken = vec![0; chunk.len()]; // Whether or not the current voxel has been added
// Voxel insertion/combination pass
for (y, z) in (0..width).cartesian_product(0..width)
{
let mut x = 0;
while x < width
{
if taken[x + y * width + z * width * width] != 0
{
x += taken[x + y * width + z * width * width];
continue;
}
let max_combination_depth = trailing_zeroes::<N>(x)
.unwrap_or(depth)
.min(trailing_zeroes::<N>(y).unwrap_or(depth))
.min(trailing_zeroes::<N>(z).unwrap_or(depth));
let prev_color = chunk[x + y * width + z * width * width];
let mut locator = NTreeLocator::<N>::from_depth_coords(x, y, z, depth);
//let mut insertion_depth = depth;
let mut block_width = 1;
'depth_loop: for depth in 1..=max_combination_depth
{
let combination_width = N.pow(depth as u32);
for ((sx, sy), sz) in (0..combination_width)
.cartesian_product(0..combination_width)
.cartesian_product(0..combination_width)
{
let voxel_color =
chunk[(x + sx) + (y + sy) * width + (z + sz) * width * width];
let voxel_taken =
taken[(x + sx) + (y + sy) * width + (z + sz) * width * width];
if prev_color != voxel_color || voxel_taken != 0
{
// Cannot merge further
break 'depth_loop;
}
}
// At this point, voxel in combination_width^3 block can be merged
block_width = combination_width;
//insertion_depth -= 1;
locator = locator.get_parent();
}
structure.insert(
locator,
NTreeNode {
color: prev_color,
subdivided: false,
},
);
// Mark as taken
for ((sx, sy), sz) in (0..block_width)
.cartesian_product(0..block_width)
.cartesian_product(0..block_width)
{
taken[(x + sx) + (y + sy) * width + (z + sz) * width * width] = block_width;
}
x += block_width;
}
}
// Increase pass
for d in (0..=(depth - 1)).rev()
{
// Iterate on blocks of depth d
let block_count = N.pow(d as u32); // Number of such blocks along axis
let block_width = width / block_count; // Number of such blocks along axis
for ((bx, by), bz) in (0..(block_count))
.cartesian_product(0..(block_count))
.cartesian_product(0..(block_count))
{
// Get how was the origin voxel merged
let merged_width = taken[(bx * block_width)
+ (by * block_width) * width
+ (bz * block_width) * width * width];
if merged_width >= block_width
{
// Current voxels have been merged in bigger or equal block
continue;
}
let locator = NTreeLocator::<N>::from_depth_coords(bx, by, bz, d);
// Otherwise, merge
// Children CANNOT be merged, Otherwise they would have been already
// Compute average color
let colors = locator
.iter_children()
.map(|loc| structure.get(&loc).unwrap().color)
.collect::<Vec<_>>();
structure.insert(
locator,
NTreeNode::<N> {
color: Color::average(&colors),
subdivided: true,
},
);
}
}
Self {
structure,
depth: depth as u32,
}
}
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
{
let mut local_x = x;
let mut local_y = y;
let mut local_z = z;
let mut size = N.pow(self.depth);
assert!(x < size && y < size && z < size);
let mut current_loc = NTreeLocator::<N>::root();
let mut current_node = *self.structure.get(&current_loc).unwrap();
let mut current_depth = 0;
loop
{
// Subnodes alread with correct color
if current_node.color == color
{
return;
}
if current_depth == self.depth
{
current_node.color = color;
self.structure.get_mut(&current_loc).unwrap().color = color;
break;
}
if !current_node.subdivided
{
// Have to subdivide
let sub_child = NTreeNode::<N> {
color: current_node.color,
subdivided: false,
};
// Set node as subdivided
self.structure.get_mut(&current_loc).unwrap().subdivided = true;
current_node.subdivided = true;
// Insert new children
current_loc.iter_children().for_each(|x| {
self.structure.insert(x, sub_child);
});
}
if current_node.subdivided
{
size /= N;
let child_x = local_x / size;
let child_y = local_y / size;
let child_z = local_z / size;
// Node is subdivided, descend
current_loc = current_loc.get_child(child_x, child_y, child_z);
current_node = *self.structure.get(&current_loc).unwrap();
current_depth += 1;
local_x -= child_x * size;
local_y -= child_y * size;
local_z -= child_z * size;
}
}
// Insertion has been done, travel back up to optimise
loop
{
// Try to simplify, compute average
if current_node.subdivided
{
let (compressable, color) = current_loc
.iter_children()
.map(|x| self.structure.get(&x).unwrap())
.fold((true, None), |state, child| match state
{
(_, None) => (!child.subdivided, Some(child.color)),
(b, Some(c)) => (b && !child.subdivided && c == child.color, Some(c)),
});
if compressable
{
// Compress
*self.structure.get_mut(&current_loc).unwrap() = NTreeNode {
color: color.unwrap(),
subdivided: false,
};
// Remove children
current_loc.iter_children().for_each(|x| {
self.structure.remove(&x).unwrap();
});
}
else
{
// Update average color
let colors = current_loc
.iter_children()
.map(|x| self.structure.get(&x).unwrap().color)
.collect::<Vec<_>>();
self.structure.get_mut(&current_loc).unwrap().color =
Color::average(colors.as_slice());
}
}
// Travel up
if current_depth == 0
{
break; // Finished
}
current_loc = current_loc.get_parent();
current_node = *self.structure.get(&current_loc).unwrap();
current_depth -= 1;
}
}
pub fn to_gpu_rep(&self) -> (Color, Vec<GPUStructureTile<N>>, Vec<[Color; N * N * N]>)
{
// No root + group by child group
let tile_count = (self.structure.len() - 1) / (N * N * N);
if tile_count == 0
{
return (
self.structure
.get(&NTreeLocator::<N>::root())
.unwrap()
.color,
vec![],
vec![],
);
}
let mut structure_tiles = vec![GPUStructureTile::<N>::zero(); tile_count];
let mut color_tiles = vec![[Color(0., 0., 0., 0.); N * N * N]; tile_count];
let mut current_tile = 0usize;
let mut queue = VecDeque::new();
queue.push_back((NTreeLocator::<N>::root(), current_tile));
current_tile += 1;
while !queue.is_empty()
{
let (loc, dest_tile) = queue.pop_front().unwrap();
let children = loc
.iter_children()
.map(|x| (x, self.structure.get(&x).unwrap()))
.collect::<Vec<_>>();
let mut structure_tile = GPUStructureTile::<N>::zero();
let mut color_tile = [Color(0., 0., 0., 0.); N * N * N];
for (i, (child_loc, child)) in children.into_iter().enumerate()
{
structure_tile.children[i] = GPUStructureTileIndex::new(
child.subdivided,
child.subdivided,
current_tile as u32,
);
color_tile[i] = child.color;
if child.subdivided
{
queue.push_back((child_loc, current_tile));
current_tile += 1;
}
}
structure_tiles[dest_tile] = structure_tile;
color_tiles[dest_tile] = color_tile;
}
println!(
"node count: {}, current_tile: {}",
self.structure.len(),
current_tile
);
(
self.structure
.get(&NTreeLocator::<N>::root())
.unwrap()
.color,
structure_tiles,
color_tiles,
)
}
}
#[derive(Clone, Copy)]
pub struct GPUStructureTile<const N: usize>
where
[(); N * N * N]:,
{
children: [GPUStructureTileIndex; N * N * N],
}
impl<const N: usize> GPUStructureTile<N>
where
[(); N * N * N]:,
{
pub fn zero() -> Self
{
GPUStructureTile {
children: [GPUStructureTileIndex::zero(); N * N * N],
}
}
}
#[derive(Clone, Copy)]
pub struct GPUStructureTileIndex(u32);
impl GPUStructureTileIndex
{
pub fn zero() -> Self
{
GPUStructureTileIndex(0)
}
pub fn new(subdivided: bool, leaf: bool, ptr: u32) -> Self
{
assert_eq!((ptr >> 30), 0);
GPUStructureTileIndex(ptr | ((leaf as u32) << 30) | ((subdivided as u32) << 31))
}
pub fn index(&self) -> u32
{
self.0 & 0x3FFFFFFFu32
}
pub fn subdivided(&self) -> bool
{
(self.0 >> 31) == 1
}
pub fn leaf(&self) -> bool
{
((self.0 >> 30) & 1) == 1
}
}
impl Color
{
pub fn average(colors: &[Color]) -> Color
{
let sum = colors
.iter()
.copied()
.reduce(|Color(r_a, g_a, b_a, a_a), Color(r_b, g_b, b_b, a_b)| {
Color(r_a + r_b, g_a + g_b, b_a + b_b, a_a + a_b)
})
.unwrap_or(Color(0., 0., 0., 0.));
//let len = colors.len().max(1) as f32;
let len = colors.iter().map(|x| x.3).sum::<f32>();
Color(sum.0 / len, sum.1 / len, sum.2 / len, sum.3 / len)
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct NTreeLocator<const N: usize>(usize, usize, usize);
impl<const N: usize> NTreeLocator<N>
{
pub fn root() -> Self
{
Self(1, 1, 1)
}
pub fn get_child(&self, child_x: usize, child_y: usize, child_z: usize) -> Self
{
assert!(child_x < N && child_y < N && child_z < N);
let mut new_loc_x = self.0;
let mut new_loc_y = self.1;
let mut new_loc_z = self.2;
// Shift to left three times
new_loc_x *= N;
new_loc_x += child_x;
new_loc_y *= N;
new_loc_y += child_y;
new_loc_z *= N;
new_loc_z += child_z;
Self(new_loc_x, new_loc_y, new_loc_z)
}
pub fn from_depth_coords(x: usize, y: usize, z: usize, depth: usize) -> Self
{
if depth == 0
{
return Self::root();
}
let off = N.pow(depth as u32);
Self(off + x, off + y, off + z)
}
pub fn iter_children(&self) -> impl Iterator<Item = NTreeLocator<N>>
{
(0..N)
.cartesian_product(0..N)
.cartesian_product(0..N)
.map(|((x, y), z)| self.get_child(x, y, z))
}
pub fn get_parent(&self) -> Self
{
if self.0 == 0
{
*self
}
else
{
Self(self.0 / N, self.1 / N, self.2 / N)
}
}
pub fn get_local_location(&self) -> (usize, usize, usize)
{
let mut loc = self.0;
let z = loc % N;
loc /= N;
let y = loc % N;
loc /= N;
let x = loc % N;
(x, y, z)
}
pub fn is_root(&self) -> bool
{
self.0 == 1
}
}
fn trailing_zeroes<const N: usize>(mut n: usize) -> Option<usize>
{
if n == 0
{
return None;
}
let mut i = 0;
while n.is_multiple_of(N)
// n % N == 0
{
i += 1;
n /= N;
}
Some(i)
}
#[cfg(test)]
mod test
{
use crate::voxel::trailing_zeroes;
use itertools::Itertools;
use rand::Rng;
use rand::RngExt;
use crate::voxel::Color;
use crate::voxel::NTree;
use crate::voxel::NTreeLocator;
#[test]
pub fn constant()
{
let color = Color(0.5, 0.3, 0.5, 1.);
let depth = 5;
const N: usize = 3;
let width = N.pow(depth);
let ntree = NTree::<N>::constant(color, depth);
for ((x, y), z) in (0..width)
.cartesian_product(0..width)
.cartesian_product(0..width)
{
assert_eq!(ntree.get(x, y, z), color);
}
}
#[test]
pub fn full_insert()
{
const DEPTH: u32 = 4;
const N: usize = 3;
const WIDTH: usize = N.pow(DEPTH);
let mut ntree = NTree::<N>::constant(Color(1., 0., 0., 0.), DEPTH);
let mut rng = rand::rng();
let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH];
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = Color(rng.random(), rng.random(), rng.random(), rng.random());
storage[x][y][z] = color;
ntree.set(x, y, z, color);
}
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = ntree.get(x, y, z);
assert_eq!(storage[x][y][z], color);
}
println!("Total nodes {}", ntree.structure.len());
}
#[test]
pub fn full_insert_bottom_up()
{
const DEPTH: u32 = 4;
const N: usize = 3;
const WIDTH: usize = N.pow(DEPTH);
let mut rng = rand::rng();
let mut storage = vec![Color(0., 0., 0., 0.); WIDTH * WIDTH * WIDTH];
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = Color(rng.random(), rng.random(), rng.random(), rng.random());
storage[x + WIDTH * y + WIDTH * WIDTH * z] = color;
}
let ntree = NTree::<N>::from_arrays(&storage, DEPTH as usize);
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = ntree.get(x, y, z);
assert_eq!(storage[x + WIDTH * y + WIDTH * WIDTH * z], color);
}
println!("Total nodes {}", ntree.structure.len());
}
#[test]
pub fn full_insert_const()
{
const DEPTH: u32 = 4;
const N: usize = 3;
const WIDTH: usize = N.pow(DEPTH);
const NEW_COLOR: Color = Color(0., 1., 0., 1.);
let mut ntree = NTree::<N>::constant(Color(1., 0., 1., 0.), DEPTH);
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
ntree.set(x, y, z, NEW_COLOR);
}
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = ntree.get(x, y, z);
assert_eq!(NEW_COLOR, color);
}
println!("Total nodes {}", ntree.structure.len());
}
#[test]
pub fn full_insert_quantized()
{
const DEPTH: u32 = 4;
const N: usize = 3;
const WIDTH: usize = N.pow(DEPTH);
let mut ntree = NTree::<N>::constant(Color(0., 0., 0., 0.), DEPTH);
let mut rng = rand::rng();
let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH];
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let nbr = rng.random::<f32>();
let mut color = Color(0., 1., 0., 0.);
// Only 1 percent of different color
if nbr > 0.01
{
color = Color(1., 0., 0., 0.);
}
storage[x][y][z] = color;
ntree.set(x, y, z, color);
}
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let color = ntree.get(x, y, z);
assert_eq!(storage[x][y][z], color);
}
println!("Total nodes {}", ntree.structure.len());
}
#[test]
pub fn gpu_rep_quantized()
{
const DEPTH: u32 = 4;
const N: usize = 3;
const WIDTH: usize = N.pow(DEPTH);
let mut ntree = NTree::<N>::constant(Color(0., 0., 0., 0.), DEPTH);
let mut rng = rand::rng();
let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH];
for ((x, y), z) in (0..WIDTH)
.cartesian_product(0..WIDTH)
.cartesian_product(0..WIDTH)
{
let nbr = rng.random::<f32>();
let mut color = Color(0., 1., 0., 0.);
// Only 1 percent of different color
if nbr > 0.01
{
color = Color(1., 0., 0., 0.);
}
storage[x][y][z] = color;
ntree.set(x, y, z, color);
}
let (_color, _a, _b) = ntree.to_gpu_rep();
drop(_a);
drop(_b);
}
#[test]
pub fn tree_locator_from_depth_coords()
{
const N: usize = 4;
assert_eq!(
NTreeLocator::<N>::root(),
NTreeLocator::<N>::from_depth_coords(1, 2, 3, 0)
);
assert_eq!(
NTreeLocator::<N>::root().get_child(1, 2, 3),
NTreeLocator::<N>::from_depth_coords(1, 2, 3, 1)
);
assert_eq!(
NTreeLocator::<N>::root()
.get_child(1, 1, 1)
.get_child(1, 2, 3),
NTreeLocator::<N>::from_depth_coords(4 + 1, 4 + 2, 4 + 3, 2)
);
}
#[test]
fn trailing_zeroes_base10()
{
let n = 2139800000;
assert_eq!(trailing_zeroes::<10>(n), Some(5));
assert_eq!(trailing_zeroes::<10>(0), None);
}
}