382 lines
9.5 KiB
Rust
382 lines
9.5 KiB
Rust
//! 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 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))
|
|
}
|
|
}
|