Skip to main content

crcbl_phys/
broadphase.rs

1//! Broadphase spatial queries: bounding volume hierarchy (BVH).
2//!
3//! The [`Bvh`] is a *dynamic* axis-aligned bounding volume hierarchy that
4//! accelerates ray, segment, and overlap queries. It can be built in bulk from
5//! a collection of (AABB, element_id) pairs and then churned in place:
6//! [`Bvh::insert`] and [`Bvh::remove`] each touch one root-to-leaf path
7//! instead of rebuilding, and [`Bvh::update_aabb`] refits one in place.
8//!
9//! # Build strategy
10//!
11//! Bulk construction uses recursive spatial median splitting on the longest
12//! axis of each node's bounding box. The tree is stored as a flat array; the
13//! root is not necessarily index 0, because churn frees and
14//! recycles node slots.
15//!
16//! # Churn strategy
17//!
18//! [`Bvh::insert`] picks the sibling to pair a new leaf with by the surface
19//! area heuristic (SAH): it descends from the root, at each node comparing the
20//! cost of stopping here against the cost of pushing the leaf into either
21//! child, and stops when descending cannot pay for itself. [`Bvh::remove`]
22//! deletes the leaf and its parent and promotes the leaf's sibling into the
23//! parent's place. Both then walk back to the root, refitting bounds so every
24//! query sees bounds tight for the elements actually present, and rotating
25//! (AVL single rotation) so no node's two subtrees ever differ by more
26//! than one in height.
27//!
28//! The rotation is what makes tree quality a property rather than a hope: the
29//! surface area heuristic alone degenerates when elements pile into the same
30//! region, because then every candidate site costs the same. [`Bvh::depth`] is
31//! the observable, and `crates/crcbl-phys/tests/broadphase_churn.rs` bounds it across
32//! thousands of operations including that degenerate input.
33//!
34//! # Layers
35//!
36//! Every element carries a `u32` of layer bits ([`Bvh::insert_layered`],
37//! [`Bvh::build_layered`], [`Bvh::set_layers`]; the unlayered forms put it on
38//! every bit), and every internal node the union of its subtree's. The masked
39//! traversals ([`Bvh::traverse_aabb_masked_into`],
40//! [`Bvh::traverse_ray_masked_into`]) skip any subtree whose union shares no
41//! bit with the query's mask, which is what lets a query that looks at a few
42//! static colliders walk past a crowd of characters on other layers without
43//! descending to each of them. A leaf is reported only if an unmasked
44//! traversal would report it *and* its own bits meet the mask, in the same
45//! order, because every ancestor of such a leaf carries its bits too.
46
47use crate::collider::Aabb;
48use glam::DVec3;
49
50// ---------------------------------------------------------------------------
51// Primitive queries
52// ---------------------------------------------------------------------------
53
54/// A ray defined by an origin and a direction (not normalised).
55///
56/// The direction may have any non-zero length; the traversal code normalises
57/// internally. `t_min` / `t_max` bound how far along the ray intersections are
58/// accepted, in units of the ray's direction length.
59#[derive(Debug, Clone, Copy, PartialEq)]
60pub struct Ray {
61    /// Origin in simulation space.
62    pub origin: DVec3,
63    /// Direction vector (not necessarily unit length).
64    pub dir: DVec3,
65    /// Minimum parametric distance to accept.
66    pub t_min: f64,
67    /// Maximum parametric distance to accept.
68    pub t_max: f64,
69}
70
71impl Ray {
72    /// Create a ray from origin and direction, with default bounds `(0, +inf)`.
73    #[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    /// Set the parametric bounds.
85    #[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/// A finite segment (ray clamped between origin and endpoint).
95///
96/// Equivalent to a ray with `t_max` set to the segment length.
97#[derive(Debug, Clone, Copy, PartialEq)]
98pub struct Segment {
99    /// Start point.
100    pub start: DVec3,
101    /// End point.
102    pub end: DVec3,
103}
104
105impl Segment {
106    /// Create a segment from start to end.
107    #[inline]
108    #[must_use]
109    pub fn new(start: DVec3, end: DVec3) -> Self {
110        Self { start, end }
111    }
112
113    /// Direction vector (end - start).
114    #[inline]
115    #[must_use]
116    pub fn dir(&self) -> DVec3 {
117        self.end - self.start
118    }
119
120    /// Length of the segment.
121    #[inline]
122    #[must_use]
123    pub fn length(&self) -> f64 {
124        self.dir().length()
125    }
126}
127
128/// A hit returned by BVH traversal.
129#[derive(Debug, Clone, Copy, PartialEq)]
130pub struct BvhHit {
131    /// The element_id supplied at build time.
132    pub element_id: u32,
133    /// Parametric distance along the ray at the leaf AABB's entry point.
134    /// This is a broadphase distance — refine it with an exact shape test.
135    pub t: f64,
136}
137
138// ---------------------------------------------------------------------------
139// BVH
140// ---------------------------------------------------------------------------
141
142/// Sentinel for "no node" — an absent parent, or an empty tree's root.
143const NIL: u32 = u32::MAX;
144
145/// The layer bits an element gets from the unlayered [`Bvh::build`] and
146/// [`Bvh::insert`]: every one.
147const ALL_BITS: u32 = u32::MAX;
148
149/// One element on its way into [`Bvh::build_layered`]: its position in the
150/// input travels with it so the centroid sort cannot lose it.
151#[derive(Debug, Clone, Copy)]
152struct BuildItem {
153    aabb: Aabb,
154    element_id: u32,
155    build_index: u32,
156    layers: u32,
157}
158
159/// A flat node in the BVH tree.
160///
161/// Nodes are stored in a flat array.  Bulk construction lays them out in
162/// pre-order ([`Bvh::build_rec`] reserves a node's slot before recursing, so a
163/// parent precedes its subtree), but [`Bvh::insert`] and [`Bvh::remove`]
164/// recycle freed slots, so position carries no meaning once a tree has been
165/// churned — follow `child_left` / `child_right` / `parent`, never `index ± 1`.
166///
167/// An internal node has `leaf_count == 0` and stores left/right child indices.
168/// A leaf node has `leaf_count == 1` and stores its *element index* at
169/// `child_left` (`child_right` is unused).  That element index addresses both
170/// `element_indices` and `element_node`, and is the handle
171/// [`Bvh::update_aabb`] and [`Bvh::remove`] take.
172///
173/// Every node except the root has a valid `parent` index.  The root's parent
174/// is [`NIL`].
175#[derive(Debug, Clone, Copy)]
176struct Node {
177    aabb: Aabb,
178    /// Internal: left child index. Leaf: this leaf's element index.
179    child_left: u32,
180    /// Internal: right child index. Leaf: unused (0).
181    child_right: u32,
182    /// Parent node index, or [`NIL`] for the root.
183    parent: u32,
184    /// 0 = internal node, 1 = leaf node.
185    leaf_count: u32,
186    /// Longest path from here to a leaf below, in edges: a leaf is `0`, its
187    /// parent `1`. Maintained by every structural change so
188    /// [`Bvh::balance`] can compare two subtrees in `O(1)`.
189    height: u32,
190    /// Leaf: its element's layer bits. Internal: the union of its two
191    /// children's, so a subtree with no bit in a query's mask holds no leaf
192    /// that has one. Maintained by every structural change and by
193    /// [`Bvh::set_layers`]; [`Bvh::update_aabb`] moves no node and leaves it.
194    layers: u32,
195}
196
197/// A dynamic bounding volume hierarchy for spatial queries.
198///
199/// Build in bulk via [`Bvh::build`], then query with [`Bvh::traverse_ray`],
200/// [`Bvh::traverse_segment`] or [`Bvh::traverse_aabb`].
201///
202/// The element set is not frozen by construction:
203///
204/// * [`Bvh::insert`] adds one element, returning the element index that names
205///   it from then on.
206/// * [`Bvh::remove`] takes one back out.
207/// * [`Bvh::update_aabb`] moves one that stays.
208///
209/// Each is one root-to-leaf walk plus a refit of that path, which is what lets
210/// a caller that spawns and kills elements every tick — bullets, debris —
211/// avoid paying `O(n log n)` for a rebuild each time.
212#[derive(Debug, Clone)]
213pub struct Bvh {
214    nodes: Vec<Node>,
215    /// For each element index, the caller-supplied `element_id` reported by
216    /// queries.  Slots of removed elements are stale and are never read,
217    /// because `element_node` marks them [`NIL`] and no leaf points at them.
218    element_indices: Vec<u32>,
219    /// For each element index, the leaf node that owns it, or [`NIL`] if that
220    /// element index is free.  Bulk construction reorders elements by
221    /// centroid, so leaf order and *build* order differ; this is indexed by
222    /// build order because that is the handle callers hold on to.
223    element_node: Vec<u32>,
224    /// Element indices freed by [`Bvh::remove`], available for reuse.
225    free_elements: Vec<u32>,
226    /// Node slots freed by [`Bvh::remove`], available for reuse.
227    free_nodes: Vec<u32>,
228    /// Number of live elements (leaves).
229    live_elements: usize,
230    /// Root node index, or [`NIL`] when the tree is empty.  Not necessarily 0:
231    /// removing the root's subtree promotes a sibling into its place.
232    root: u32,
233}
234
235impl Bvh {
236    /// Build a BVH from (AABB, element_id) pairs.
237    ///
238    /// The element_id is opaque to the BVH — it is returned as-is in hit
239    /// results so the caller can look up the actual collider or entity.
240    ///
241    /// An empty iterator produces an empty BVH (no root node).
242    #[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    /// [`Bvh::build`] from (AABB, element_id, layers) triples, each element on
252    /// the layer bits given rather than on every one.
253    #[must_use]
254    pub fn build_layered(elements: impl IntoIterator<Item = (Aabb, u32, u32)>) -> Self {
255        // Each item carries its position in the input array so the centroid
256        // sort below cannot detach `element_node` from the build order that
257        // `update_aabb` is indexed by.
258        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    /// Recursive build using spatial median split on the longest axis.
307    ///
308    /// Leaves record their node and their element id against
309    /// [`BuildItem::build_index`], never against the leaf's own position, so
310    /// that a leaf's `child_left` is the same element index that
311    /// [`Bvh::update_aabb`] and [`Bvh::remove`] take.
312    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        // Compute union AABB of this range.
324        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            // Leaf node: the element index *is* the build index, so one number
331            // addresses the leaf, `element_indices` and `element_node` alike.
332            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        // Internal node: split by spatial median on the longest axis.
350        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        // `total_cmp`, not `partial_cmp().unwrap_or(Equal)`. The old form
360        // neither panicked nor broke `sort_by`'s contract, but a `NaN` centroid
361        // made the comparator non-transitive — `NaN` compares Equal to
362        // everything while the finite keys still order among themselves — and a
363        // non-transitive comparator turns this spatial median split into an
364        // arbitrary partition. `total_cmp` is a total order over every `f64`
365        // including `NaN`, so the split degrades to "the NaN sorts to one end"
366        // rather than to nothing. `crcbl_render::shadow` and
367        // `crcbl_scene::simplify` already choose it for the same reason.
368        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        // Reserve the node slot so children's back-references are valid.
377        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    /// Walk the BVH and return all element ids whose AABB intersects the
417    /// query AABB. The BVH itself tests AABB↔AABB, so this is a broadphase
418    /// overlap query — the caller must refine with exact shape tests.
419    ///
420    /// Results are unsorted (tree order).
421    #[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    /// [`traverse_aabb`](Self::traverse_aabb) writing into buffers the caller
429    /// owns, for a consumer that runs one query per body per tick.
430    ///
431    /// Both `out` and the descent `stack` are **cleared** and then filled, so a
432    /// caller hoists one of each out of its loop and the whole pass allocates
433    /// nothing in the steady state. The owned form allocates two `Vec`s per
434    /// call, which at a crowd sample's ten thousand agents is 1.2 million
435    /// allocations a second doing nothing.
436    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    /// [`traverse_aabb_into`](Self::traverse_aabb_into) reporting only the
441    /// elements whose layer bits share at least one bit with `mask`, and never
442    /// descending into a subtree that holds none.
443    ///
444    /// `out` is exactly what the unmasked form writes with every element whose
445    /// layers miss `mask` taken out, in the same order — the pruning only ever
446    /// skips subtrees whose leaves would all have been taken out. A mask of `0`
447    /// reports nothing.
448    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    /// The one AABB descent, pruning on `mask` when `MASKED`. A const
459    /// parameter rather than a mask of every bit for the unmasked form,
460    /// because an element on no layer at all is still reported by that one.
461    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    /// Walk the BVH with a ray, returning all intersected element ids and
493    /// hit positions.
494    ///
495    /// Results are unsorted (tree order). Duplicate element ids are possible
496    /// if the same element was inserted twice.
497    #[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    /// [`traverse_ray`](Self::traverse_ray) writing into buffers the caller
505    /// owns, for the same reason
506    /// [`traverse_aabb_into`](Self::traverse_aabb_into) exists — and
507    /// additionally because [`crate::world::OverlapQueries`] holds only a
508    /// shared borrow of the world and so cannot reach the world's own buffers.
509    ///
510    /// Both `out` and the descent `stack` are **cleared** and then filled, so
511    /// what they held before never reaches an answer.
512    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    /// [`traverse_ray_into`](Self::traverse_ray_into) reporting only the
517    /// elements whose layer bits share at least one bit with `mask`, and never
518    /// descending into a subtree that holds none — the ray counterpart of
519    /// [`traverse_aabb_masked_into`](Self::traverse_aabb_masked_into), with the
520    /// same guarantee: the unmasked answer with the other elements taken out,
521    /// in the same order, at the same `t`.
522    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    /// The one ray descent, pruning on `mask` when `MASKED`, as
533    /// [`aabb_walk`](Self::aabb_walk) does.
534    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                // Leaf: report each element at the AABB entry point.
565                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                // Internal: push right then left (left will be popped first).
582                stack.push(node.child_right);
583                stack.push(node.child_left);
584            }
585        }
586    }
587
588    /// Walk the BVH with a segment, returning all intersected element ids.
589    ///
590    /// This is a convenience wrapper around [`Bvh::traverse_ray`] that converts
591    /// the segment to a ray first.
592    #[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    /// Update the AABB of a single element and refit the tree upwards.
609    ///
610    /// `element_index` is the handle [`Bvh::insert`] returned, or — for
611    /// elements that came from [`Bvh::build`] — the position in the array that
612    /// was built from. Returns `true` if the element is live and the tree was
613    /// refit, `false` if the index names no element (never inserted, or
614    /// removed since).
615    ///
616    /// This is O(depth) — much cheaper than a full rebuild after each move.
617    /// The caller must ensure the new AABB *contains* the shape it represents;
618    /// the BVH only sees AABBs.
619    ///
620    /// This does **not** re-pick the element's place in the tree. An element
621    /// that moves far from where it was inserted stays where it was, growing
622    /// its ancestors' bounds; that is the cost of a refit, and it is why
623    /// callers whose elements travel — rather than jitter — should remove and
624    /// re-insert instead.
625    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        // Update leaf, then walk up to the root refitting.
631        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    /// Put one element on the layer bits `layers`, replacing what it was on,
637    /// and bring every ancestor's union up to date. Returns `false` if the
638    /// index names no element, as [`Bvh::update_aabb`] does.
639    ///
640    /// O(depth) at most, and it stops at the first ancestor whose union comes
641    /// out unchanged, since every one above that is unchanged too.
642    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    /// Put every node on every layer bit, so the masked walks prune nothing:
662    /// the unpruned reference the query world's layer tests compare against.
663    #[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    // ── Churn: insert / remove ─────────────────────────────────────────
671
672    /// Insert one element, returning the element index that names it.
673    ///
674    /// The returned index is the handle for [`Bvh::update_aabb`],
675    /// [`Bvh::set_layers`] and [`Bvh::remove`], and it is in the same space as
676    /// the build-order indices
677    /// [`Bvh::build`] hands out. Indices of removed elements are recycled, so
678    /// an index is only meaningful until the element it names is removed.
679    ///
680    /// The new leaf is paired with the sibling chosen by
681    /// the surface area heuristic; a fresh internal
682    /// node takes the sibling's place and adopts both, and the path back to the
683    /// root is refit and rebalanced. Cost is one root-to-leaf descent plus one
684    /// walk back up.
685    pub fn insert(&mut self, aabb: Aabb, element_id: u32) -> usize {
686        self.insert_layered(aabb, element_id, ALL_BITS)
687    }
688
689    /// [`Bvh::insert`] with the element on the layer bits `layers` rather than
690    /// on every one. The returned index is the same handle, for
691    /// [`Bvh::update_aabb`], [`Bvh::set_layers`] and [`Bvh::remove`].
692    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        // First element: it is the whole tree.
707        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    /// Remove the element named by `element_index`.
736    ///
737    /// Returns `false` if the index names no live element — the same answer a
738    /// double remove gets, which is what makes it safe for a caller sweeping
739    /// deferred destructions to ask twice.
740    ///
741    /// The leaf and its parent both go; the leaf's sibling is promoted into the
742    /// parent's slot, so the tree keeps its "every internal node has two
743    /// children" shape and never accumulates single-child chains. The freed
744    /// node slots are recycled by later inserts.
745    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        // Sole element: the tree becomes empty.
754        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    // ── Observables ────────────────────────────────────────────────────
783
784    /// Number of live elements.
785    #[must_use]
786    pub fn len(&self) -> usize {
787        self.live_elements
788    }
789
790    /// Whether the tree holds no elements.
791    #[must_use]
792    pub fn is_empty(&self) -> bool {
793        self.live_elements == 0
794    }
795
796    /// Allocated node slots, including those a [`Bvh::remove`] recycled.
797    ///
798    /// A balanced binary tree over `n` leaves holds about `2n − 1` nodes; the
799    /// number drifting up past that is the memory footprint of churn, which is
800    /// what [`PhysicsWorld::broadphase_stats`](crate::world::PhysicsWorld::broadphase_stats)
801    /// reports it for.
802    #[must_use]
803    pub fn node_count(&self) -> usize {
804        self.nodes.len()
805    }
806
807    /// The longest root-to-leaf path, counted in nodes (a one-element tree has
808    /// depth 1, an empty one 0).
809    ///
810    /// This is the tree-quality observable: query cost is bounded by how far a
811    /// traversal can descend, so a depth that grows past `O(log n)` under churn
812    /// is the shape of degradation, and this is what
813    /// `crates/crcbl-phys/tests/broadphase_churn.rs` asserts a bound on. It walks the
814    /// whole tree — `O(n)` — so it is for tests and diagnostics, not for a
815    /// per-frame check.
816    #[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    /// Sum of the half-surface areas of every live internal node.
836    ///
837    /// A refit keeps every box tight around its children but does not move a
838    /// leaf back beside its new neighbours. The resulting overlap makes this
839    /// sum grow even while [`depth`](Self::depth) and the node count stay
840    /// unchanged, so this is the diagnostic that distinguishes a balanced but
841    /// spatially loose tree from a freshly partitioned one.
842    ///
843    /// Only nodes reachable from the root are counted. Removed nodes leave
844    /// recycled slots in `nodes`, and folding those stale boxes in would make
845    /// churn look like query work that traversal cannot reach.
846    ///
847    /// This walks the tree in `O(n)` and allocates a traversal stack. It is for
848    /// diagnostics and policy measurements, not for each query.
849    #[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    /// Internal-node surface-area cost relative to the root's surface area.
868    ///
869    /// The quotient is unchanged when the whole world scales uniformly, so a
870    /// quality policy does not mistake a larger but equally partitioned world
871    /// for a looser tree. A point-sized tree has no traversal surface and
872    /// therefore no degradation signal.
873    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    // ── Internal helpers ───────────────────────────────────────────────
886
887    /// The leaf node owning `element_index`, or `None` if that index names no
888    /// live element.
889    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    /// Take a free element index, or grow the element arrays by one.
897    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    /// Take a free node slot, or grow the node array by one.
910    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    /// Point `parent`'s child link at `new_child` wherever it pointed at
922    /// `old_child`.
923    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    /// Re-union the bounds of `start` and every ancestor above it.
933    ///
934    /// For structural changes use [`Bvh::refit_and_balance_from`]; this one is
935    /// for [`Bvh::update_aabb`], which moves a leaf's bounds without moving any
936    /// node, and therefore leaves every `height` already correct.
937    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    /// Walk from `start` to the root, rebalancing each node on the way and
949    /// recomputing its bounds and height.
950    ///
951    /// Insertion picks where a leaf goes by bounds alone, which says nothing
952    /// about shape: elements that pile into the same region give the surface
953    /// area heuristic nothing to separate them by, every candidate costs the
954    /// same, and the tie sends every one of them down the same side. Measured
955    /// on 1024 coincident boxes under 20k insert/remove pairs, that reached
956    /// depth 623 against an ideal of 11 — a "tree" that is very nearly a linked
957    /// list, and queries that scan it. Rebalancing on the way back up is what
958    /// makes the ideal hold regardless of where elements sit.
959    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    /// Rotate `index`'s taller grandchild up if its two subtrees differ in
974    /// height by more than one, returning whichever node now sits in `index`'s
975    /// place.
976    ///
977    /// This is the AVL single rotation, chosen over the alternatives — a
978    /// periodic full rebuild, or tree rotations picked by SAH cost — because it
979    /// is the one that makes a *statement*: no node's subtrees ever differ by
980    /// more than one in height, so depth is `O(log n)` by construction rather
981    /// than by hoping the inputs are well spread. A rebuild policy would only
982    /// bound the damage between rebuilds, and would put an `O(n log n)` spike
983    /// in a frame that was trying to spawn a bullet.
984    ///
985    /// The rotated node's bounds and height are fixed up here; its new parent's
986    /// are fixed by the caller, which is mid-walk up to the root.
987    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    /// Pull `child` (a child of `index`) above `index`, leaving `index` holding
1007    /// `keep` and whichever of `child`'s own children is shorter.
1008    ///
1009    /// Returns `child`, which now occupies the slot `index` did.
1010    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        // `child` takes `index`'s place under the grandparent.
1023        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        // `child` keeps its taller subtree and adopts `index`; `index` keeps
1033        // `keep` and adopts the shorter one.  Which side each lands on is the
1034        // side it came from, so a left-heavy rotation stays left-heavy.
1035        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        // `index` is now below `child`, so it is refit first.
1044        self.recompute(index);
1045        self.recompute(child);
1046        child
1047    }
1048
1049    /// Point `parent` at exactly these two children, preserving the order they
1050    /// are given in.
1051    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    /// Recompute one internal node's bounds, height and layers from its
1058    /// children.
1059    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    /// Pick the node a new leaf with bounds `aabb` should become a sibling of.
1069    ///
1070    /// Descends from the root. At each internal node it compares the cost of
1071    /// stopping — pairing with this whole subtree, which prices at the area of
1072    /// the box that would have to enclose both — against the cost of pushing
1073    /// the leaf into either child, which is that child's area growth plus the
1074    /// area every node on the path above would inherit. It stops as soon as
1075    /// descending cannot pay for itself, so the walk is bounded by the depth.
1076    ///
1077    /// Costs are compared, never accumulated across calls, so the dropped
1078    /// factor of two in [`Aabb::half_surface_area`] is invisible here.
1079    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            // Stop here: a new parent enclosing this subtree and the new leaf.
1087            let stop_cost = 2.0 * combined_area;
1088            // Every ancestor of the descent point grows by this much.
1089            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// ---------------------------------------------------------------------------
1117// Tests
1118// ---------------------------------------------------------------------------
1119
1120#[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        // Ray that would hit at t=5, but bounds say t_max=3.
1257        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        // Origin is inside the AABB.
1288        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        // AABB spans x in [4.5, 5.5], ray from origin along x hits at t=4.5.
1300        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    // ── AABB traversal ─────────────────────────────────────────────────
1309
1310    #[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    // ── BVH refit ───────────────────────────────────────────────────────
1347
1348    #[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        // Element 0 hits at x=5.
1363        let hits = bvh.traverse_ray(&Ray::new(DVec3::ZERO, DVec3::X));
1364        assert_eq!(hits.len(), 2);
1365
1366        // Move element 0 far away.
1367        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        // Ray going +X should miss it now, only hit element 1.
1371        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        // Build a larger tree to exercise deeper refit paths.
1379        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        // Update element 10.
1389        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        // The BVH should still find it.
1393        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        // Elements are supplied in *descending* centroid order, so the
1400        // centroid sort in `build_rec` reverses them.  `update_aabb(0)` must
1401        // still move the element that was passed first.
1402        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        // Move build-order element 0 (the one at x=20) behind the ray origin.
1416        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    // ── Churn: structural invariants ────────────────────────────────────
1431
1432    /// Check every invariant the tree's own code relies on and no query can
1433    /// reveal on its own.
1434    ///
1435    /// A query only ever descends, so it cannot notice a wrong `parent`, a
1436    /// stale `height` or a subtree that has become lopsided — but `remove` and
1437    /// `balance` walk *up* and read exactly those, so a tree that is wrong
1438    /// here answers correctly today and corrupts itself later. Checking them
1439    /// from inside the module is the point: they are private, and a test that
1440    /// could only see the public surface would be checking the queries again.
1441    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        // And it comes back to life.
1558        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        // Insert-heavy, then remove-heavy, then alternating: each phase drives
1578        // a different rotation case, and the invariants are checked after
1579        // every single operation rather than at the end, so a violation is
1580        // reported at the operation that caused it.
1581        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        // Remove from the front, which is the oldest and deepest-buried.
1600        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        // The point of incremental churn is that steady-state spawning and
1620        // killing does not keep allocating. One removal frees two node slots
1621        // (the leaf and its parent) and one insertion claims them back, so a
1622        // balanced sequence must leave the array exactly the size it was.
1623        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    /// The layers, in the 4 bits the masked tests deal them from: few enough
1647    /// that subtrees with no bit of a mask are common, so pruning happens.
1648    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    /// The masked walks against the unmasked ones filtered by hand, for every
1661    /// mask of the dealt bits, and the number of answers the masked walk kept,
1662    /// so a caller can tell the comparison was not over empty lists.
1663    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    /// Pruning on the layer unions changes no answer, through a bulk build
1691    /// and then through every kind of churn: inserts, removals, refits and
1692    /// layer changes, with the invariants — the unions among them — checked
1693    /// after each.
1694    #[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        // `layers_of[element_id]`, element ids being the order they were made.
1700        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        // (element index, element id) of each live element.
1705        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    /// A subtree whose union holds no bit of the mask is skipped, and one
1736    /// element moved onto that bit after the build is found again: the
1737    /// union it lives under picked the bit up.
1738    #[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        // And off it again: the bit leaves every union it was the only
1758        // reason for.
1759        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    /// The node as it was before it carried a layer union.
1766    #[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    /// Where `f64` is 8-aligned — 64-bit targets and wasm32 — the layer union
1777    /// rides in what was the node's padding, and the node is the size it was
1778    /// before. Where `f64` is 4-aligned (i686) there was no padding, and the
1779    /// node grows by the one `u32`.
1780    #[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        // Ray starts on +Y face of element with zero Y dir component.
1794        // Exercises intersect_ray_entry NaN fix.
1795        let centre = DVec3::new(5.0, 0.0, 0.0);
1796        let bvh = Bvh::build([unit_box_at(centre)]);
1797        // AABB spans: min = (4.5, -0.5, -0.5), max = (5.5, 0.5, 0.5).
1798        // Ray origin on +Y face, dir = +X (zero Y component).
1799        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}