refactor: Splitting into crates

This commit is contained in:
2026-11-15 20:36:43 +01:00
parent c13a04c8e2
commit 828806fbc8
68 changed files with 929 additions and 330 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vxls-bvh"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
egui.workspace = true
glam.workspace = true
wgpu.workspace = true
vxls-profiler = { path = "../vxls-profiler" }
vxls-production = { path = "../vxls-production" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
+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);
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Implementation of fast binary BVH build with binned SAH
//!
use std::num::NonZero;
use egui::emath::OrderedFloat;
use crate::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,
_pad2: [0; 2],
}
}
}
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 depth: usize,
}
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,
depth: 1,
//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,
));
let mut max_depth = 0usize;
build_node(0, primitives, &mut nodes, leaf_max, 0, &mut max_depth);
println!("Max depth {}", max_depth);
Bvh {
nodes,
depth: max_depth,
}
}
pub fn build_node<T>(
node_index: usize,
primitives: &mut [BvhPrimitive<T>],
nodes: &mut Vec<BvhNode>,
leaf_max: usize,
depth: usize,
max_depth: &mut 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,
depth + 1,
max_depth,
);
build_node(
left_index + 1,
primitives,
nodes,
leaf_max,
depth + 1,
max_depth,
);
}
None =>
{
// Sah says keep as leaf, do nothing
if depth > *max_depth
{
*max_depth = depth;
}
}
}
}
/// 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))
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Contains rendering code to display a debug overlay for the BVH.
use glam::Mat4;
use wgpu::BlendState;
// debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync:
// WGSL rounds structs containing vec3 up to a 16-byte alignment, so a node's
// 40 bytes of data become a 48-byte array stride.
const _: () = {
assert!(size_of::<crate::gpu::GpuBvhNode>() == 48);
assert!(size_of::<crate::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: Some(wgpu::BlendState {
color: wgpu::BlendComponent::OVER,
alpha: wgpu::BlendComponent::OVER,
}),
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);
}
}
+198
View File
@@ -0,0 +1,198 @@
//! 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
{
// vec3 members align to 16 bytes, so this struct has a 48-byte array
// stride. The Rust `GpuBvhNode` is padded to the same size.
min: vec3<f32>,
_pad0: u32,
max: vec3<f32>,
_pad1: u32,
count: u32,
first_or_left: u32,
_pad2: vec2<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: vec4<f32>,
@location(1) normal: vec3<f32>,
};
const INTERNAL_NODE_COLOR = vec4<f32>(0.15, 0.70, 1.0, 1.0);
const LEAF_NODE_COLOR = vec4<f32>(1.0, 0.85, 0.20, 1.0);
const OBJECT_COLOR = vec4<f32>(1.0, 0.45, 0.12, 0.5);
// 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 = node.min;
let max_corner = node.max;
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 input.color;
}
@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));
}
+84
View File
@@ -0,0 +1,84 @@
//! GPU ready structures for the BVH representation
use glam::Mat4;
use glam::Vec3;
use crate::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`]
///
/// The trailing padding keeps the array stride at 48 bytes. On the GPU a struct
/// containing `vec3` has a 16-byte alignment, so the shader rounds the 40 bytes
/// of data up to a 48-byte stride.
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuBvhNode
{
pub aabb: GpuAabb,
pub count: u32,
pub first_or_left: u32,
pub(crate) _pad2: [u32; 2],
}
/// 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(),
}
}
}
+476
View File
@@ -0,0 +1,476 @@
#![feature(generic_const_exprs)]
//! 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::aabb::Aabb;
use crate::build::BvhPrimitive;
use crate::build::build_bvh;
use crate::gpu::GpuBvhNode;
use crate::gpu::GpuObject;
use vxls_profiler::ScopeEncoder;
use vxls_production::ProducerId;
use vxls_production::StructureAnchor;
use vxls_voxel_cache::CacheInvalidable;
use vxls_voxel_cache::eviction::CacheEvictor;
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::requests::CacheRequestBuffer;
use vxls_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
}
/// Gathers the root requests emitted by the inner structure table into
/// `request_buffer`.
pub fn gather_requests(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
request_buffer: &CacheRequestBuffer,
)
{
self.structure_table
.gather_requests(device, encoder, request_buffer);
}
/// Writes the cache page pointers produced by an external insertion into
/// the inner structure table.
pub fn insert<const N: usize>(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
) where
[(); N * N * N]:,
{
self.structure_table.insert(device, encoder, insertion);
}
pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject>
{
self.objects.get(handle)
}
pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject>
{
self.objects.get_mut(handle)
}
}
impl<const N: usize> CacheInvalidable<N> for BvhStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
)
{
self.structure_table
.validate_insertion(device, encoder, insertion);
}
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
)
{
self.structure_table
.invalidate(encoder, cache_evictor, invalid_timestamp);
}
}
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(),
},
],
})
}