1use crate::collider::Aabb;
48use glam::DVec3;
49
50#[derive(Debug, Clone, Copy, PartialEq)]
60pub struct Ray {
61 pub origin: DVec3,
63 pub dir: DVec3,
65 pub t_min: f64,
67 pub t_max: f64,
69}
70
71impl Ray {
72 #[inline]
74 #[must_use]
75 pub fn new(origin: DVec3, dir: DVec3) -> Self {
76 Self {
77 origin,
78 dir,
79 t_min: 0.0,
80 t_max: f64::INFINITY,
81 }
82 }
83
84 #[inline]
86 #[must_use]
87 pub fn with_bounds(mut self, t_min: f64, t_max: f64) -> Self {
88 self.t_min = t_min;
89 self.t_max = t_max;
90 self
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
98pub struct Segment {
99 pub start: DVec3,
101 pub end: DVec3,
103}
104
105impl Segment {
106 #[inline]
108 #[must_use]
109 pub fn new(start: DVec3, end: DVec3) -> Self {
110 Self { start, end }
111 }
112
113 #[inline]
115 #[must_use]
116 pub fn dir(&self) -> DVec3 {
117 self.end - self.start
118 }
119
120 #[inline]
122 #[must_use]
123 pub fn length(&self) -> f64 {
124 self.dir().length()
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq)]
130pub struct BvhHit {
131 pub element_id: u32,
133 pub t: f64,
136}
137
138const NIL: u32 = u32::MAX;
144
145const ALL_BITS: u32 = u32::MAX;
148
149#[derive(Debug, Clone, Copy)]
152struct BuildItem {
153 aabb: Aabb,
154 element_id: u32,
155 build_index: u32,
156 layers: u32,
157}
158
159#[derive(Debug, Clone, Copy)]
176struct Node {
177 aabb: Aabb,
178 child_left: u32,
180 child_right: u32,
182 parent: u32,
184 leaf_count: u32,
186 height: u32,
190 layers: u32,
195}
196
197#[derive(Debug, Clone)]
213pub struct Bvh {
214 nodes: Vec<Node>,
215 element_indices: Vec<u32>,
219 element_node: Vec<u32>,
224 free_elements: Vec<u32>,
226 free_nodes: Vec<u32>,
228 live_elements: usize,
230 root: u32,
233}
234
235impl Bvh {
236 #[must_use]
243 pub fn build(elements: impl IntoIterator<Item = (Aabb, u32)>) -> Self {
244 Self::build_layered(
245 elements
246 .into_iter()
247 .map(|(aabb, element_id)| (aabb, element_id, ALL_BITS)),
248 )
249 }
250
251 #[must_use]
254 pub fn build_layered(elements: impl IntoIterator<Item = (Aabb, u32, u32)>) -> Self {
255 let mut items: Vec<BuildItem> = elements
259 .into_iter()
260 .enumerate()
261 .map(|(build_index, (aabb, element_id, layers))| BuildItem {
262 aabb,
263 element_id,
264 build_index: build_index as u32,
265 layers,
266 })
267 .collect();
268 if items.is_empty() {
269 return Self {
270 nodes: Vec::new(),
271 element_indices: Vec::new(),
272 element_node: Vec::new(),
273 free_elements: Vec::new(),
274 free_nodes: Vec::new(),
275 live_elements: 0,
276 root: NIL,
277 };
278 }
279
280 let mut nodes = Vec::with_capacity(2 * items.len());
281 let mut element_indices = vec![0u32; items.len()];
282 let mut element_node = vec![NIL; items.len()];
283
284 let count = items.len();
285 let root = Self::build_rec(
286 &mut items,
287 &mut nodes,
288 &mut element_indices,
289 &mut element_node,
290 0,
291 count,
292 NIL,
293 );
294
295 Self {
296 nodes,
297 element_indices,
298 element_node,
299 free_elements: Vec::new(),
300 free_nodes: Vec::new(),
301 live_elements: count,
302 root,
303 }
304 }
305
306 fn build_rec(
313 items: &mut [BuildItem],
314 nodes: &mut Vec<Node>,
315 element_indices: &mut [u32],
316 element_node: &mut [u32],
317 range_start: usize,
318 range_end: usize,
319 parent: u32,
320 ) -> u32 {
321 let count = range_end - range_start;
322
323 let mut aabb = Aabb::EMPTY;
325 for item in &items[range_start..range_end] {
326 aabb = aabb.union(item.aabb);
327 }
328
329 if count == 1 {
330 let item = items[range_start];
333 let elem_idx = item.build_index;
334 element_indices[elem_idx as usize] = item.element_id;
335 let node_idx = nodes.len() as u32;
336 element_node[elem_idx as usize] = node_idx;
337 nodes.push(Node {
338 aabb,
339 child_left: elem_idx,
340 child_right: 0,
341 parent,
342 leaf_count: 1,
343 height: 0,
344 layers: item.layers,
345 });
346 return node_idx;
347 }
348
349 let extents = aabb.extents();
351 let axis = if extents.x >= extents.y && extents.x >= extents.z {
352 0usize
353 } else if extents.y >= extents.z {
354 1
355 } else {
356 2
357 };
358
359 items[range_start..range_end].sort_by(|a, b| {
369 let ka = a.aabb.centre().to_array()[axis];
370 let kb = b.aabb.centre().to_array()[axis];
371 ka.total_cmp(&kb)
372 });
373
374 let mid = range_start + count / 2;
375 let node_idx = nodes.len() as u32;
376 nodes.push(Node {
378 aabb,
379 child_left: 0,
380 child_right: 0,
381 parent,
382 leaf_count: 0,
383 height: 0,
384 layers: 0,
385 });
386
387 let left = Self::build_rec(
388 items,
389 nodes,
390 element_indices,
391 element_node,
392 range_start,
393 mid,
394 node_idx,
395 );
396 let right = Self::build_rec(
397 items,
398 nodes,
399 element_indices,
400 element_node,
401 mid,
402 range_end,
403 node_idx,
404 );
405
406 nodes[node_idx as usize].child_left = left;
407 nodes[node_idx as usize].child_right = right;
408 nodes[node_idx as usize].height = 1 + nodes[left as usize]
409 .height
410 .max(nodes[right as usize].height);
411 nodes[node_idx as usize].layers =
412 nodes[left as usize].layers | nodes[right as usize].layers;
413 node_idx
414 }
415
416 #[must_use]
422 pub fn traverse_aabb(&self, query: &Aabb) -> Vec<u32> {
423 let mut out = Vec::new();
424 self.traverse_aabb_into(query, &mut Vec::with_capacity(64), &mut out);
425 out
426 }
427
428 pub fn traverse_aabb_into(&self, query: &Aabb, stack: &mut Vec<u32>, out: &mut Vec<u32>) {
437 self.aabb_walk::<false>(query, ALL_BITS, stack, out);
438 }
439
440 pub fn traverse_aabb_masked_into(
449 &self,
450 query: &Aabb,
451 mask: u32,
452 stack: &mut Vec<u32>,
453 out: &mut Vec<u32>,
454 ) {
455 self.aabb_walk::<true>(query, mask, stack, out);
456 }
457
458 fn aabb_walk<const MASKED: bool>(
462 &self,
463 query: &Aabb,
464 mask: u32,
465 stack: &mut Vec<u32>,
466 out: &mut Vec<u32>,
467 ) {
468 out.clear();
469 stack.clear();
470 if self.root == NIL {
471 return;
472 }
473 stack.push(self.root);
474
475 while let Some(node_idx) = stack.pop() {
476 let node = &self.nodes[node_idx as usize];
477 if (MASKED && node.layers & mask == 0) || !node.aabb.intersects(query) {
478 continue;
479 }
480 if node.leaf_count > 0 {
481 let end = (node.child_left + node.leaf_count) as usize;
482 for i in node.child_left as usize..end {
483 out.push(self.element_indices[i]);
484 }
485 } else {
486 stack.push(node.child_right);
487 stack.push(node.child_left);
488 }
489 }
490 }
491
492 #[must_use]
498 pub fn traverse_ray(&self, ray: &Ray) -> Vec<BvhHit> {
499 let mut hits = Vec::new();
500 self.traverse_ray_into(ray, &mut Vec::with_capacity(64), &mut hits);
501 hits
502 }
503
504 pub fn traverse_ray_into(&self, ray: &Ray, stack: &mut Vec<u32>, out: &mut Vec<BvhHit>) {
513 self.ray_walk::<false>(ray, ALL_BITS, stack, out);
514 }
515
516 pub fn traverse_ray_masked_into(
523 &self,
524 ray: &Ray,
525 mask: u32,
526 stack: &mut Vec<u32>,
527 out: &mut Vec<BvhHit>,
528 ) {
529 self.ray_walk::<true>(ray, mask, stack, out);
530 }
531
532 fn ray_walk<const MASKED: bool>(
535 &self,
536 ray: &Ray,
537 mask: u32,
538 stack: &mut Vec<u32>,
539 out: &mut Vec<BvhHit>,
540 ) {
541 out.clear();
542 stack.clear();
543 if self.root == NIL {
544 return;
545 }
546
547 let inv_dir = ray.dir.recip();
548 let dir_is_neg = [ray.dir.x < 0.0, ray.dir.y < 0.0, ray.dir.z < 0.0];
549 let t_min = ray.t_min;
550 let t_max = ray.t_max;
551
552 stack.push(self.root);
553
554 while let Some(node_idx) = stack.pop() {
555 let node = &self.nodes[node_idx as usize];
556 if (MASKED && node.layers & mask == 0)
557 || !node
558 .aabb
559 .intersect_ray(ray.origin, inv_dir, dir_is_neg, t_min, t_max)
560 {
561 continue;
562 }
563 if node.leaf_count > 0 {
564 let t_entry = node
566 .aabb
567 .ray_slab(ray.origin, inv_dir, dir_is_neg)
568 .map_or(f64::INFINITY, |(t_near, _)| t_near);
569 if t_entry > t_max {
570 continue;
571 }
572 let t = t_entry.max(t_min);
573 let end = (node.child_left + node.leaf_count) as usize;
574 for i in node.child_left as usize..end {
575 out.push(BvhHit {
576 element_id: self.element_indices[i],
577 t,
578 });
579 }
580 } else {
581 stack.push(node.child_right);
583 stack.push(node.child_left);
584 }
585 }
586 }
587
588 #[must_use]
593 pub fn traverse_segment(&self, segment: &Segment) -> Vec<BvhHit> {
594 let dir = segment.end - segment.start;
595 let length = dir.length();
596 if length <= 0.0 {
597 return Vec::new();
598 }
599 let ray = Ray {
600 origin: segment.start,
601 dir,
602 t_min: 0.0,
603 t_max: 1.0,
604 };
605 self.traverse_ray(&ray)
606 }
607
608 pub fn update_aabb(&mut self, element_index: usize, new_aabb: Aabb) -> bool {
626 let Some(leaf_node) = self.leaf_of(element_index) else {
627 return false;
628 };
629
630 self.nodes[leaf_node as usize].aabb = new_aabb;
632 self.refit_from(self.nodes[leaf_node as usize].parent);
633 true
634 }
635
636 pub fn set_layers(&mut self, element_index: usize, layers: u32) -> bool {
643 let Some(leaf_node) = self.leaf_of(element_index) else {
644 return false;
645 };
646 self.nodes[leaf_node as usize].layers = layers;
647 let mut current = self.nodes[leaf_node as usize].parent;
648 while current != NIL {
649 let node = self.nodes[current as usize];
650 let union = self.nodes[node.child_left as usize].layers
651 | self.nodes[node.child_right as usize].layers;
652 if union == node.layers {
653 break;
654 }
655 self.nodes[current as usize].layers = union;
656 current = node.parent;
657 }
658 true
659 }
660
661 #[cfg(test)]
664 pub(crate) fn saturate_layers(&mut self) {
665 for node in &mut self.nodes {
666 node.layers = ALL_BITS;
667 }
668 }
669
670 pub fn insert(&mut self, aabb: Aabb, element_id: u32) -> usize {
686 self.insert_layered(aabb, element_id, ALL_BITS)
687 }
688
689 pub fn insert_layered(&mut self, aabb: Aabb, element_id: u32, layers: u32) -> usize {
693 let element_index = self.alloc_element(element_id);
694 let leaf = self.alloc_node(Node {
695 aabb,
696 child_left: element_index,
697 child_right: 0,
698 parent: NIL,
699 leaf_count: 1,
700 height: 0,
701 layers,
702 });
703 self.element_node[element_index as usize] = leaf;
704 self.live_elements += 1;
705
706 if self.root == NIL {
708 self.root = leaf;
709 return element_index as usize;
710 }
711
712 let sibling = self.find_best_sibling(aabb);
713 let old_parent = self.nodes[sibling as usize].parent;
714 let new_parent = self.alloc_node(Node {
715 aabb: aabb.union(self.nodes[sibling as usize].aabb),
716 child_left: sibling,
717 child_right: leaf,
718 parent: old_parent,
719 leaf_count: 0,
720 height: 1 + self.nodes[sibling as usize].height,
721 layers: layers | self.nodes[sibling as usize].layers,
722 });
723 self.nodes[sibling as usize].parent = new_parent;
724 self.nodes[leaf as usize].parent = new_parent;
725
726 if old_parent == NIL {
727 self.root = new_parent;
728 } else {
729 self.replace_child(old_parent, sibling, new_parent);
730 }
731 self.refit_and_balance_from(new_parent);
732 element_index as usize
733 }
734
735 pub fn remove(&mut self, element_index: usize) -> bool {
746 let Some(leaf) = self.leaf_of(element_index) else {
747 return false;
748 };
749 self.element_node[element_index] = NIL;
750 self.free_elements.push(element_index as u32);
751 self.live_elements -= 1;
752
753 if leaf == self.root {
755 self.root = NIL;
756 self.free_nodes.push(leaf);
757 return true;
758 }
759
760 let parent = self.nodes[leaf as usize].parent;
761 let parent_node = self.nodes[parent as usize];
762 let sibling = if parent_node.child_left == leaf {
763 parent_node.child_right
764 } else {
765 parent_node.child_left
766 };
767 let grandparent = parent_node.parent;
768
769 self.nodes[sibling as usize].parent = grandparent;
770 if grandparent == NIL {
771 self.root = sibling;
772 } else {
773 self.replace_child(grandparent, parent, sibling);
774 self.refit_and_balance_from(grandparent);
775 }
776
777 self.free_nodes.push(parent);
778 self.free_nodes.push(leaf);
779 true
780 }
781
782 #[must_use]
786 pub fn len(&self) -> usize {
787 self.live_elements
788 }
789
790 #[must_use]
792 pub fn is_empty(&self) -> bool {
793 self.live_elements == 0
794 }
795
796 #[must_use]
803 pub fn node_count(&self) -> usize {
804 self.nodes.len()
805 }
806
807 #[must_use]
817 pub fn depth(&self) -> usize {
818 if self.root == NIL {
819 return 0;
820 }
821 let mut deepest = 0;
822 let mut stack = vec![(self.root, 1usize)];
823 while let Some((node_idx, depth)) = stack.pop() {
824 let node = &self.nodes[node_idx as usize];
825 if node.leaf_count > 0 {
826 deepest = deepest.max(depth);
827 } else {
828 stack.push((node.child_left, depth + 1));
829 stack.push((node.child_right, depth + 1));
830 }
831 }
832 deepest
833 }
834
835 #[must_use]
850 pub fn surface_area_cost(&self) -> f64 {
851 if self.root == NIL {
852 return 0.0;
853 }
854 let mut cost = 0.0;
855 let mut stack = vec![self.root];
856 while let Some(index) = stack.pop() {
857 let node = self.nodes[index as usize];
858 if node.leaf_count == 0 {
859 cost += node.aabb.half_surface_area();
860 stack.push(node.child_right);
861 stack.push(node.child_left);
862 }
863 }
864 cost
865 }
866
867 pub(crate) fn normalized_surface_area_cost(&self) -> f64 {
874 if self.root == NIL {
875 return 0.0;
876 }
877 let root_area = self.nodes[self.root as usize].aabb.half_surface_area();
878 if root_area == 0.0 {
879 0.0
880 } else {
881 self.surface_area_cost() / root_area
882 }
883 }
884
885 fn leaf_of(&self, element_index: usize) -> Option<u32> {
890 match self.element_node.get(element_index).copied() {
891 Some(leaf) if leaf != NIL => Some(leaf),
892 _ => None,
893 }
894 }
895
896 fn alloc_element(&mut self, element_id: u32) -> u32 {
898 if let Some(index) = self.free_elements.pop() {
899 self.element_indices[index as usize] = element_id;
900 index
901 } else {
902 let index = self.element_indices.len() as u32;
903 self.element_indices.push(element_id);
904 self.element_node.push(NIL);
905 index
906 }
907 }
908
909 fn alloc_node(&mut self, node: Node) -> u32 {
911 if let Some(index) = self.free_nodes.pop() {
912 self.nodes[index as usize] = node;
913 index
914 } else {
915 let index = self.nodes.len() as u32;
916 self.nodes.push(node);
917 index
918 }
919 }
920
921 fn replace_child(&mut self, parent: u32, old_child: u32, new_child: u32) {
924 let node = &mut self.nodes[parent as usize];
925 if node.child_left == old_child {
926 node.child_left = new_child;
927 } else {
928 node.child_right = new_child;
929 }
930 }
931
932 fn refit_from(&mut self, start: u32) {
938 let mut current = start;
939 while current != NIL {
940 let node = self.nodes[current as usize];
941 let left = self.nodes[node.child_left as usize].aabb;
942 let right = self.nodes[node.child_right as usize].aabb;
943 self.nodes[current as usize].aabb = left.union(right);
944 current = node.parent;
945 }
946 }
947
948 fn refit_and_balance_from(&mut self, start: u32) {
960 let mut current = start;
961 while current != NIL {
962 current = self.balance(current);
963 let node = self.nodes[current as usize];
964 let left = self.nodes[node.child_left as usize];
965 let right = self.nodes[node.child_right as usize];
966 self.nodes[current as usize].aabb = left.aabb.union(right.aabb);
967 self.nodes[current as usize].height = 1 + left.height.max(right.height);
968 self.nodes[current as usize].layers = left.layers | right.layers;
969 current = self.nodes[current as usize].parent;
970 }
971 }
972
973 fn balance(&mut self, index: u32) -> u32 {
988 let node = self.nodes[index as usize];
989 if node.leaf_count > 0 || node.height < 2 {
990 return index;
991 }
992
993 let left = node.child_left;
994 let right = node.child_right;
995 let skew =
996 self.nodes[right as usize].height as i64 - self.nodes[left as usize].height as i64;
997 if skew > 1 {
998 self.rotate_up(index, right, left)
999 } else if skew < -1 {
1000 self.rotate_up(index, left, right)
1001 } else {
1002 index
1003 }
1004 }
1005
1006 fn rotate_up(&mut self, index: u32, child: u32, keep: u32) -> u32 {
1011 let child_node = self.nodes[child as usize];
1012 let (tall, short) = {
1013 let a = child_node.child_left;
1014 let b = child_node.child_right;
1015 if self.nodes[a as usize].height > self.nodes[b as usize].height {
1016 (a, b)
1017 } else {
1018 (b, a)
1019 }
1020 };
1021
1022 let grandparent = self.nodes[index as usize].parent;
1024 self.nodes[child as usize].parent = grandparent;
1025 self.nodes[index as usize].parent = child;
1026 if grandparent == NIL {
1027 self.root = child;
1028 } else {
1029 self.replace_child(grandparent, index, child);
1030 }
1031
1032 self.set_children(child, index, tall);
1036 if self.nodes[index as usize].child_left == keep {
1037 self.set_children(index, keep, short);
1038 } else {
1039 self.set_children(index, short, keep);
1040 }
1041 self.nodes[short as usize].parent = index;
1042
1043 self.recompute(index);
1045 self.recompute(child);
1046 child
1047 }
1048
1049 fn set_children(&mut self, parent: u32, left: u32, right: u32) {
1052 let node = &mut self.nodes[parent as usize];
1053 node.child_left = left;
1054 node.child_right = right;
1055 }
1056
1057 fn recompute(&mut self, index: u32) {
1060 let node = self.nodes[index as usize];
1061 let left = self.nodes[node.child_left as usize];
1062 let right = self.nodes[node.child_right as usize];
1063 self.nodes[index as usize].aabb = left.aabb.union(right.aabb);
1064 self.nodes[index as usize].height = 1 + left.height.max(right.height);
1065 self.nodes[index as usize].layers = left.layers | right.layers;
1066 }
1067
1068 fn find_best_sibling(&self, aabb: Aabb) -> u32 {
1080 let mut index = self.root;
1081 while self.nodes[index as usize].leaf_count == 0 {
1082 let node = self.nodes[index as usize];
1083 let area = node.aabb.half_surface_area();
1084 let combined_area = node.aabb.union(aabb).half_surface_area();
1085
1086 let stop_cost = 2.0 * combined_area;
1088 let inheritance_cost = 2.0 * (combined_area - area);
1090
1091 let descend_cost = |child: u32| {
1092 let child = self.nodes[child as usize];
1093 let grown = child.aabb.union(aabb).half_surface_area();
1094 if child.leaf_count > 0 {
1095 grown + inheritance_cost
1096 } else {
1097 grown - child.aabb.half_surface_area() + inheritance_cost
1098 }
1099 };
1100 let left_cost = descend_cost(node.child_left);
1101 let right_cost = descend_cost(node.child_right);
1102
1103 if stop_cost < left_cost && stop_cost < right_cost {
1104 break;
1105 }
1106 index = if left_cost < right_cost {
1107 node.child_left
1108 } else {
1109 node.child_right
1110 };
1111 }
1112 index
1113 }
1114}
1115
1116#[cfg(test)]
1121mod tests {
1122 use super::*;
1123 use crcbl_core::rand::hash_unit;
1124
1125 fn unit_box_at(centre: DVec3) -> (Aabb, u32) {
1126 (Aabb::from_centre_half(centre, DVec3::splat(0.5)), 0)
1127 }
1128
1129 #[test]
1130 fn empty_bvh_returns_no_hits() {
1131 let bvh = Bvh::build([]);
1132 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1133 assert!(hits.is_empty());
1134 }
1135
1136 #[test]
1137 fn bvh_hits_single_element() {
1138 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1139 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1140 assert_eq!(hits.len(), 1);
1141 assert_eq!(hits[0].element_id, 0);
1142 }
1143
1144 #[test]
1145 fn surface_area_cost_sums_the_internal_boxes() {
1146 let bvh = Bvh::build([
1147 unit_box_at(DVec3::ZERO),
1148 unit_box_at(DVec3::new(2.0, 0.0, 0.0)),
1149 ]);
1150 assert_eq!(bvh.surface_area_cost(), 7.0);
1151 }
1152
1153 #[test]
1154 fn normalized_surface_area_cost_is_scale_invariant() {
1155 let build = |scale: f64| {
1156 Bvh::build([
1157 (
1158 Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(0.5 * scale)),
1159 0,
1160 ),
1161 (
1162 Aabb::from_centre_half(
1163 DVec3::new(2.0 * scale, 0.0, 0.0),
1164 DVec3::splat(0.5 * scale),
1165 ),
1166 1,
1167 ),
1168 ])
1169 };
1170 assert_eq!(
1171 build(1.0).normalized_surface_area_cost(),
1172 build(10.0).normalized_surface_area_cost()
1173 );
1174 }
1175
1176 #[test]
1177 fn bvh_hits_multiple_elements() {
1178 let elements = [
1179 unit_box_at(DVec3::new(5.0, 0.0, 0.0)),
1180 (
1181 Aabb::from_centre_half(DVec3::new(10.0, 0.0, 0.0), DVec3::splat(0.5)),
1182 1,
1183 ),
1184 ];
1185 let bvh = Bvh::build(elements);
1186 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1187 assert_eq!(hits.len(), 2);
1188 }
1189
1190 #[test]
1191 fn bvh_misses_when_ray_goes_other_way() {
1192 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1193 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::NEG_X));
1194 assert!(hits.is_empty());
1195 }
1196
1197 #[test]
1198 fn a_segment_crossing_a_leaf_reports_that_leaf_as_a_hit() {
1199 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1200 let seg = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
1201 let hits = bvh.traverse_segment(&seg);
1202 assert_eq!(hits.len(), 1);
1203 }
1204
1205 #[test]
1206 fn segment_that_misses_returns_nothing() {
1207 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1208 let seg = Segment::new(DVec3::ZERO, DVec3::new(0.0, 5.0, 0.0));
1209 let hits = bvh.traverse_segment(&seg);
1210 assert!(hits.is_empty());
1211 }
1212
1213 #[test]
1214 fn zero_length_segment_is_safe() {
1215 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1216 let seg = Segment::new(DVec3::ZERO, DVec3::ZERO);
1217 let hits = bvh.traverse_segment(&seg);
1218 assert!(hits.is_empty());
1219 }
1220
1221 #[test]
1222 fn many_elements_bvh_builds_and_queries() {
1223 let mut elements = Vec::new();
1224 for i in 0..100u32 {
1225 let x = (i as f64) * 2.0 + 1.0;
1226 elements.push((
1227 Aabb::from_centre_half(DVec3::new(x, 0.0, 0.0), DVec3::splat(0.4)),
1228 i,
1229 ));
1230 }
1231 let bvh = Bvh::build(elements);
1232 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1233 assert_eq!(hits.len(), 100);
1234 }
1235
1236 #[test]
1237 fn bvh_handles_negative_direction_ray() {
1238 let elements = [
1239 (
1240 Aabb::from_centre_half(DVec3::new(-5.0, 0.0, 0.0), DVec3::splat(0.5)),
1241 0,
1242 ),
1243 (
1244 Aabb::from_centre_half(DVec3::new(-10.0, 0.0, 0.0), DVec3::splat(0.5)),
1245 1,
1246 ),
1247 ];
1248 let bvh = Bvh::build(elements);
1249 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::NEG_X));
1250 assert_eq!(hits.len(), 2);
1251 }
1252
1253 #[test]
1254 fn ray_outside_t_bounds_returns_nothing() {
1255 let bvh = Bvh::build([unit_box_at(DVec3::new(5.0, 0.0, 0.0))]);
1256 let ray = Ray::new(DVec3::ZERO, DVec3::X).with_bounds(0.0, 3.0);
1258 let hits = bvh.traverse_ray(&ray);
1259 assert!(hits.is_empty());
1260 }
1261
1262 #[test]
1263 fn element_ids_are_preserved() {
1264 let elements = [
1265 (
1266 Aabb::from_centre_half(DVec3::new(3.0, 0.0, 0.0), DVec3::splat(0.5)),
1267 42u32,
1268 ),
1269 (
1270 Aabb::from_centre_half(DVec3::new(7.0, 0.0, 0.0), DVec3::splat(0.5)),
1271 99u32,
1272 ),
1273 ];
1274 let bvh = Bvh::build(elements);
1275 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1276 let mut ids: Vec<_> = hits.iter().map(|h| h.element_id).collect();
1277 ids.sort();
1278 assert_eq!(ids, vec![42, 99]);
1279 }
1280
1281 #[test]
1282 fn ray_origin_inside_bvh_still_reports_hits() {
1283 let bvh = Bvh::build([(
1284 Aabb::from_centre_half(DVec3::new(0.0, 0.0, 0.0), DVec3::splat(1.0)),
1285 42,
1286 )]);
1287 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1289 assert_eq!(hits.len(), 1);
1290 assert_eq!(hits[0].element_id, 42);
1291 }
1292
1293 #[test]
1294 fn t_values_are_correct() {
1295 let bvh = Bvh::build([(
1296 Aabb::from_centre_half(DVec3::new(5.0, 0.0, 0.0), DVec3::splat(0.5)),
1297 1,
1298 )]);
1299 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1301 assert!(
1302 (hits[0].t - 4.5).abs() < 0.001,
1303 "expected ~4.5, got {}",
1304 hits[0].t
1305 );
1306 }
1307
1308 #[test]
1311 fn traverse_aabb_finds_overlapping() {
1312 let elements = [
1313 (
1314 Aabb::from_centre_half(DVec3::new(3.0, 0.0, 0.0), DVec3::splat(1.0)),
1315 10,
1316 ),
1317 (
1318 Aabb::from_centre_half(DVec3::new(10.0, 0.0, 0.0), DVec3::splat(1.0)),
1319 20,
1320 ),
1321 ];
1322 let bvh = Bvh::build(elements);
1323 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(5.0));
1324 let ids = bvh.traverse_aabb(&query);
1325 assert_eq!(ids.len(), 1);
1326 assert_eq!(ids[0], 10);
1327 }
1328
1329 #[test]
1330 fn traverse_aabb_empty_bvh() {
1331 let bvh = Bvh::build([]);
1332 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0));
1333 assert!(bvh.traverse_aabb(&query).is_empty());
1334 }
1335
1336 #[test]
1337 fn traverse_aabb_misses_all() {
1338 let bvh = Bvh::build([(
1339 Aabb::from_centre_half(DVec3::new(100.0, 0.0, 0.0), DVec3::splat(1.0)),
1340 1,
1341 )]);
1342 let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(5.0));
1343 assert!(bvh.traverse_aabb(&query).is_empty());
1344 }
1345
1346 #[test]
1349 fn update_aabb_moves_element_in_ray_query() {
1350 let elements = vec![
1351 (
1352 Aabb::from_centre_half(DVec3::new(5.0, 0.0, 0.0), DVec3::splat(1.0)),
1353 100,
1354 ),
1355 (
1356 Aabb::from_centre_half(DVec3::new(100.0, 0.0, 0.0), DVec3::splat(1.0)),
1357 200,
1358 ),
1359 ];
1360 let mut bvh = Bvh::build(elements);
1361
1362 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1364 assert_eq!(hits.len(), 2);
1365
1366 let new_aabb = Aabb::from_centre_half(DVec3::new(-50.0, 0.0, 0.0), DVec3::splat(1.0));
1368 assert!(bvh.update_aabb(0, new_aabb));
1369
1370 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1372 assert_eq!(hits.len(), 1);
1373 assert_eq!(hits[0].element_id, 200);
1374 }
1375
1376 #[test]
1377 fn update_aabb_refit_keeps_tree_consistent() {
1378 let mut elements = Vec::new();
1380 for i in 0..20u32 {
1381 elements.push((
1382 Aabb::from_centre_half(DVec3::new(i as f64 * 2.0, 0.0, 0.0), DVec3::splat(0.5)),
1383 i,
1384 ));
1385 }
1386 let mut bvh = Bvh::build(elements);
1387
1388 let new_aabb = Aabb::from_centre_half(DVec3::new(10.0 * 2.0, 0.0, 0.0), DVec3::splat(1.0));
1390 assert!(bvh.update_aabb(10, new_aabb));
1391
1392 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1394 assert_eq!(hits.len(), 20);
1395 }
1396
1397 #[test]
1398 fn update_aabb_indexes_build_order_not_leaf_order() {
1399 let elements = vec![
1403 (
1404 Aabb::from_centre_half(DVec3::new(20.0, 0.0, 0.0), DVec3::splat(1.0)),
1405 100,
1406 ),
1407 (
1408 Aabb::from_centre_half(DVec3::new(5.0, 0.0, 0.0), DVec3::splat(1.0)),
1409 200,
1410 ),
1411 ];
1412 let mut bvh = Bvh::build(elements);
1413 assert_eq!(bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X)).len(), 2);
1414
1415 let new_aabb = Aabb::from_centre_half(DVec3::new(-50.0, 0.0, 0.0), DVec3::splat(1.0));
1417 assert!(bvh.update_aabb(0, new_aabb));
1418
1419 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1420 assert_eq!(hits.len(), 1, "only the untouched element remains ahead");
1421 assert_eq!(hits[0].element_id, 200);
1422 }
1423
1424 #[test]
1425 fn update_aabb_invalid_index_returns_false() {
1426 let mut bvh = Bvh::build([unit_box_at(DVec3::ZERO)]);
1427 assert!(!bvh.update_aabb(999, Aabb::EMPTY));
1428 }
1429
1430 fn assert_invariants(bvh: &Bvh) {
1442 if bvh.root == NIL {
1443 assert_eq!(bvh.live_elements, 0, "empty tree claims live elements");
1444 return;
1445 }
1446 assert_eq!(
1447 bvh.nodes[bvh.root as usize].parent, NIL,
1448 "the root has a parent"
1449 );
1450
1451 let mut leaves = 0usize;
1452 let mut stack = vec![bvh.root];
1453 while let Some(index) = stack.pop() {
1454 let node = bvh.nodes[index as usize];
1455 if node.leaf_count > 0 {
1456 leaves += 1;
1457 assert_eq!(node.height, 0, "leaf {index} has non-zero height");
1458 assert_eq!(
1459 bvh.element_node[node.child_left as usize], index,
1460 "leaf {index} and its element disagree about who owns whom"
1461 );
1462 continue;
1463 }
1464
1465 let (left, right) = (node.child_left, node.child_right);
1466 assert_ne!(left, right, "node {index} has the same child twice");
1467 for child in [left, right] {
1468 assert_eq!(
1469 bvh.nodes[child as usize].parent, index,
1470 "child {child} of {index} points at a different parent"
1471 );
1472 }
1473
1474 let (lh, rh) = (
1475 bvh.nodes[left as usize].height,
1476 bvh.nodes[right as usize].height,
1477 );
1478 assert_eq!(
1479 node.height,
1480 1 + lh.max(rh),
1481 "node {index} has a stale height"
1482 );
1483 assert!(
1484 lh.abs_diff(rh) <= 1,
1485 "node {index} is unbalanced: heights {lh} and {rh}"
1486 );
1487 assert_eq!(
1488 node.aabb,
1489 bvh.nodes[left as usize]
1490 .aabb
1491 .union(bvh.nodes[right as usize].aabb),
1492 "node {index} has stale bounds"
1493 );
1494 assert_eq!(
1495 node.layers,
1496 bvh.nodes[left as usize].layers | bvh.nodes[right as usize].layers,
1497 "node {index} has a stale layer union"
1498 );
1499
1500 stack.push(left);
1501 stack.push(right);
1502 }
1503
1504 assert_eq!(leaves, bvh.live_elements, "leaf count disagrees with len()");
1505 }
1506
1507 #[test]
1508 fn bulk_build_satisfies_the_invariants() {
1509 for count in [1usize, 2, 3, 5, 8, 33, 64] {
1510 let bvh = Bvh::build((0..count).map(|i| {
1511 (
1512 Aabb::from_centre_half(
1513 DVec3::new(i as f64 * 3.0, (i % 7) as f64, (i % 3) as f64),
1514 DVec3::splat(0.5),
1515 ),
1516 i as u32,
1517 )
1518 }));
1519 assert_eq!(bvh.len(), count);
1520 assert_invariants(&bvh);
1521 }
1522 }
1523
1524 #[test]
1525 fn insert_into_empty_tree_makes_a_one_leaf_tree() {
1526 let mut bvh = Bvh::build([]);
1527 assert!(bvh.is_empty());
1528 assert_eq!(bvh.depth(), 0);
1529
1530 let index = bvh.insert(unit_box_at(DVec3::new(5.0, 0.0, 0.0)).0, 7);
1531 assert_eq!(index, 0);
1532 assert_eq!(bvh.len(), 1);
1533 assert_eq!(bvh.depth(), 1);
1534 assert_invariants(&bvh);
1535
1536 let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1537 assert_eq!(hits.len(), 1);
1538 assert_eq!(hits[0].element_id, 7);
1539 }
1540
1541 #[test]
1542 fn removing_the_last_element_empties_the_tree() {
1543 let mut bvh = Bvh::build([unit_box_at(DVec3::ZERO)]);
1544 assert!(bvh.remove(0));
1545 assert!(bvh.is_empty());
1546 assert_eq!(bvh.depth(), 0);
1547 assert!(
1548 bvh.traverse_aabb(&Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(100.0)))
1549 .is_empty()
1550 );
1551 assert!(
1552 bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X))
1553 .is_empty()
1554 );
1555 assert_invariants(&bvh);
1556
1557 let index = bvh.insert(unit_box_at(DVec3::ZERO).0, 5);
1559 assert_eq!(bvh.len(), 1);
1560 assert_invariants(&bvh);
1561 assert!(bvh.update_aabb(index, unit_box_at(DVec3::new(9.0, 0.0, 0.0)).0));
1562 }
1563
1564 #[test]
1565 fn remove_reports_false_for_indices_that_name_nothing() {
1566 let mut bvh = Bvh::build([unit_box_at(DVec3::ZERO), unit_box_at(DVec3::X * 10.0)]);
1567 assert!(!bvh.remove(99), "index past the end");
1568 assert!(bvh.remove(1));
1569 assert!(!bvh.remove(1), "already removed");
1570 assert!(!bvh.update_aabb(1, Aabb::EMPTY), "refit of a dead element");
1571 assert_eq!(bvh.len(), 1);
1572 assert_invariants(&bvh);
1573 }
1574
1575 #[test]
1576 fn churn_preserves_the_invariants() {
1577 let mut bvh = Bvh::build([]);
1582 let mut live: Vec<usize> = Vec::new();
1583 let mut counter = 0u32;
1584
1585 let spawn = |bvh: &mut Bvh, live: &mut Vec<usize>, counter: &mut u32| {
1586 let n = *counter as f64;
1587 let aabb = Aabb::from_centre_half(
1588 DVec3::new((n * 7.3) % 50.0, (n * 3.1) % 30.0, (n * 1.7) % 20.0),
1589 DVec3::splat(0.75),
1590 );
1591 live.push(bvh.insert(aabb, *counter));
1592 *counter += 1;
1593 };
1594
1595 for _ in 0..40 {
1596 spawn(&mut bvh, &mut live, &mut counter);
1597 assert_invariants(&bvh);
1598 }
1599 for _ in 0..20 {
1601 let index = live.remove(0);
1602 assert!(bvh.remove(index));
1603 assert_invariants(&bvh);
1604 }
1605 for step in 0..40 {
1606 if step % 2 == 0 {
1607 spawn(&mut bvh, &mut live, &mut counter);
1608 } else {
1609 let index = live.swap_remove(step % live.len());
1610 assert!(bvh.remove(index));
1611 }
1612 assert_invariants(&bvh);
1613 }
1614 assert_eq!(bvh.len(), live.len());
1615 }
1616
1617 #[test]
1618 fn insert_and_remove_do_not_rebuild_the_node_array() {
1619 let mut bvh =
1624 Bvh::build((0..32).map(|i| (unit_box_at(DVec3::new(i as f64 * 2.0, 0.0, 0.0)).0, i)));
1625 let nodes_after_build = bvh.nodes.len();
1626 let mut live: Vec<usize> = (0..32).collect();
1627
1628 for i in 0..200u32 {
1629 let index = live.swap_remove((i as usize * 7) % live.len());
1630 assert!(bvh.remove(index));
1631 live.push(bvh.insert(
1632 unit_box_at(DVec3::new((i % 40) as f64 * 2.0, 1.0, 0.0)).0,
1633 1000 + i,
1634 ));
1635 }
1636
1637 assert_eq!(
1638 bvh.nodes.len(),
1639 nodes_after_build,
1640 "churn grew the node array instead of recycling slots"
1641 );
1642 assert_eq!(bvh.element_indices.len(), 32, "element slots leaked");
1643 assert_invariants(&bvh);
1644 }
1645
1646 fn dealt_layers(seed: u64, index: u64) -> u32 {
1649 (hash_unit(seed, index) * 16.0) as u32
1650 }
1651
1652 fn dealt_box(seed: u64, index: u64) -> Aabb {
1653 let at = |axis: u64| hash_unit(seed, 4 * index + axis) * 40.0;
1654 Aabb::from_centre_half(
1655 DVec3::new(at(0), at(1), at(2)),
1656 DVec3::splat(0.25 + hash_unit(seed, 4 * index + 3)),
1657 )
1658 }
1659
1660 fn assert_masked_walks_filter_the_unmasked(bvh: &Bvh, layers_of: &[u32], probe: u64) -> usize {
1664 let mut stack = Vec::new();
1665 let (mut all, mut masked) = (Vec::new(), Vec::new());
1666 let (mut all_hits, mut masked_hits) = (Vec::new(), Vec::new());
1667 let query = dealt_box(probe, 0).inflated(6.0);
1668 let centre = query.centre();
1669 let ray = Ray::new(
1670 centre - DVec3::new(30.0, 7.0, 3.0),
1671 DVec3::new(30.0, 7.0, 3.0),
1672 );
1673 let mut kept = 0;
1674 for mask in 0..16u32 {
1675 bvh.traverse_aabb_into(&query, &mut stack, &mut all);
1676 bvh.traverse_aabb_masked_into(&query, mask, &mut stack, &mut masked);
1677 all.retain(|&id| layers_of[id as usize] & mask != 0);
1678 assert_eq!(masked, all, "aabb walk under mask {mask:#b}");
1679 kept += masked.len();
1680
1681 bvh.traverse_ray_into(&ray, &mut stack, &mut all_hits);
1682 bvh.traverse_ray_masked_into(&ray, mask, &mut stack, &mut masked_hits);
1683 all_hits.retain(|hit| layers_of[hit.element_id as usize] & mask != 0);
1684 assert_eq!(masked_hits, all_hits, "ray walk under mask {mask:#b}");
1685 kept += masked_hits.len();
1686 }
1687 kept
1688 }
1689
1690 #[test]
1695 fn masked_walks_are_the_unmasked_walks_filtered_through_churn() {
1696 const SEED: u64 = 0x001a_7e25;
1697 const START: u64 = 64;
1698 const STEPS: u64 = 400;
1699 let mut layers_of: Vec<u32> = (0..START).map(|i| dealt_layers(SEED, i)).collect();
1701 let mut bvh = Bvh::build_layered(
1702 (0..START).map(|i| (dealt_box(SEED, i), i as u32, layers_of[i as usize])),
1703 );
1704 let mut live: Vec<(usize, u32)> = (0..START as usize).map(|i| (i, i as u32)).collect();
1706 assert_invariants(&bvh);
1707 let mut kept = assert_masked_walks_filter_the_unmasked(&bvh, &layers_of, SEED);
1708
1709 for step in 0..STEPS {
1710 let roll = hash_unit(SEED ^ 0xc0de, step);
1711 let pick = (hash_unit(SEED ^ 0xfeed, step) * live.len() as f64) as usize;
1712 if roll < 0.3 || live.is_empty() {
1713 let id = layers_of.len() as u32;
1714 layers_of.push(dealt_layers(SEED ^ 0xabc, step));
1715 let index =
1716 bvh.insert_layered(dealt_box(SEED ^ 0xabc, step), id, layers_of[id as usize]);
1717 live.push((index, id));
1718 } else if roll < 0.5 {
1719 let (index, _) = live.swap_remove(pick);
1720 assert!(bvh.remove(index));
1721 } else if roll < 0.75 {
1722 let (index, _) = live[pick];
1723 assert!(bvh.update_aabb(index, dealt_box(SEED ^ 0x5e7, step)));
1724 } else {
1725 let (index, id) = live[pick];
1726 layers_of[id as usize] = dealt_layers(SEED ^ 0x1a7, step);
1727 assert!(bvh.set_layers(index, layers_of[id as usize]));
1728 }
1729 assert_invariants(&bvh);
1730 kept += assert_masked_walks_filter_the_unmasked(&bvh, &layers_of, SEED ^ step);
1731 }
1732 assert!(kept > 1000, "the walks compared almost nothing: {kept}");
1733 }
1734
1735 #[test]
1739 fn set_layers_brings_the_unions_above_it_up_to_date() {
1740 let mut bvh = Bvh::build_layered((0..16).map(|i| {
1741 (
1742 unit_box_at(DVec3::new(f64::from(i) * 2.0, 0.0, 0.0)).0,
1743 i,
1744 0b01,
1745 )
1746 }));
1747 let everything = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(100.0));
1748 let (mut stack, mut out) = (Vec::new(), Vec::new());
1749 bvh.traverse_aabb_masked_into(&everything, 0b10, &mut stack, &mut out);
1750 assert!(out.is_empty(), "nothing is on the second bit yet: {out:?}");
1751
1752 assert!(bvh.set_layers(11, 0b10));
1753 assert_invariants(&bvh);
1754 bvh.traverse_aabb_masked_into(&everything, 0b10, &mut stack, &mut out);
1755 assert_eq!(out, [11]);
1756
1757 assert!(bvh.set_layers(11, 0b01));
1760 assert_invariants(&bvh);
1761 assert_eq!(bvh.nodes[bvh.root as usize].layers, 0b01);
1762 assert!(!bvh.set_layers(99, 0b10), "no such element");
1763 }
1764
1765 #[allow(dead_code, reason = "only its layout is measured")]
1767 struct NodeWithoutLayers {
1768 aabb: Aabb,
1769 child_left: u32,
1770 child_right: u32,
1771 parent: u32,
1772 leaf_count: u32,
1773 height: u32,
1774 }
1775
1776 #[test]
1781 fn the_layer_union_costs_no_node_memory_where_f64_is_8_aligned() {
1782 let before = std::mem::size_of::<NodeWithoutLayers>();
1783 let after = std::mem::size_of::<Node>();
1784 if std::mem::align_of::<f64>() == 8 {
1785 assert_eq!(after, before);
1786 } else {
1787 assert_eq!(after, before + std::mem::size_of::<u32>());
1788 }
1789 }
1790
1791 #[test]
1792 fn ray_on_face_with_zero_dir_through_bvh_hits() {
1793 let centre = DVec3::new(5.0, 0.0, 0.0);
1796 let bvh = Bvh::build([unit_box_at(centre)]);
1797 let ray = Ray::new(DVec3::new(0.0, 0.5, 0.0), DVec3::X);
1800 let hits = bvh.traverse_ray(&ray);
1801 assert_eq!(hits.len(), 1);
1802 assert_eq!(hits[0].element_id, 0);
1803 }
1804}