1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use super::bvh_tree::{BvhNodeIndex, BvhNodeVec, BvhNodeWide};
use super::{Bvh, BvhNode, BvhWorkspace};
use crate::utils::VecMap;
use alloc::vec::Vec;
impl Bvh {
/// Updates the BVH's internal node AABBs after leaf changes.
///
/// Refitting ensures that every internal node's AABB tightly encloses the AABBs of its
/// children. This operation is essential after updating leaf positions with
/// [`insert_or_update_partially`] and is much faster than rebuilding the entire tree.
///
/// In addition to updating AABBs, this method:
/// - Reorders nodes in depth-first order for better cache locality during queries
/// - Ensures leaf counts on each node are correct
/// - Propagates change flags from leaves to ancestors (for change detection)
///
/// # When to Use
///
/// Call `refit` after:
/// - Bulk updates with [`insert_or_update_partially`]
/// - Any operation that modifies leaf AABBs without updating ancestor nodes
/// - When you want to optimize tree layout for better query performance
///
/// **Don't call `refit` after**:
/// - Regular [`insert`] calls (they already update ancestors)
/// - [`remove`] calls (they already maintain tree validity)
///
/// # Arguments
///
/// * `workspace` - A reusable workspace to avoid allocations. Can be shared across
/// multiple BVH operations for better performance.
///
/// # Performance
///
/// - **Time**: O(n) where n is the number of nodes
/// - **Space**: O(n) temporary storage in workspace
/// - Much faster than rebuilding the tree from scratch
/// - Essential for maintaining good query performance in dynamic scenes
///
/// # Examples
///
/// ## After bulk updates
///
/// ```
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::partitioning::{Bvh, BvhWorkspace};
/// use parry3d::bounding_volume::Aabb;
/// use parry3d::math::Vector;
///
/// let mut bvh = Bvh::new();
/// let mut workspace = BvhWorkspace::default();
///
/// // Insert initial objects
/// for i in 0..100 {
/// let aabb = Aabb::new(
/// Vector::new(i as f32, 0.0, 0.0),
/// Vector::new(i as f32 + 1.0, 1.0, 1.0)
/// );
/// bvh.insert(aabb, i);
/// }
///
/// // Update all objects without tree propagation (faster)
/// for i in 0..100 {
/// let offset = 0.1;
/// let aabb = Aabb::new(
/// Vector::new(i as f32 + offset, 0.0, 0.0),
/// Vector::new(i as f32 + 1.0 + offset, 1.0, 1.0)
/// );
/// bvh.insert_or_update_partially(aabb, i, 0.0);
/// }
///
/// // Now update the tree in one efficient pass
/// bvh.refit(&mut workspace);
/// # }
/// ```
///
/// ## In a game loop
///
/// ```
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::partitioning::{Bvh, BvhWorkspace};
/// use parry3d::bounding_volume::Aabb;
/// use parry3d::math::Vector;
///
/// let mut bvh = Bvh::new();
/// let mut workspace = BvhWorkspace::default();
///
/// // Game initialization - add objects
/// for i in 0..1000 {
/// let aabb = Aabb::new(
/// Vector::new(i as f32, 0.0, 0.0),
/// Vector::new(i as f32 + 1.0, 1.0, 1.0)
/// );
/// bvh.insert(aabb, i);
/// }
///
/// // Game loop - update objects each frame
/// for frame in 0..100 {
/// // Update physics, AI, etc.
/// for i in 0..1000 {
/// let time = frame as f32 * 0.016; // ~60 FPS
/// let pos = time.sin() * 10.0;
/// let aabb = Aabb::new(
/// Vector::new(i as f32 + pos, 0.0, 0.0),
/// Vector::new(i as f32 + pos + 1.0, 1.0, 1.0)
/// );
/// bvh.insert_or_update_partially(aabb, i, 0.0);
/// }
///
/// // Refit once per frame for all updates
/// bvh.refit(&mut workspace);
///
/// // Now perform collision detection queries...
/// }
/// # }
/// ```
///
/// ## With change detection margin
///
/// ```
/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
/// use parry3d::partitioning::{Bvh, BvhWorkspace};
/// use parry3d::bounding_volume::Aabb;
/// use parry3d::math::Vector;
///
/// let mut bvh = Bvh::new();
/// let mut workspace = BvhWorkspace::default();
///
/// // Add an object
/// let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0));
/// bvh.insert(aabb, 0);
///
/// // Update with a margin - tree won't update if movement is small
/// let margin = 0.5;
/// let new_aabb = Aabb::new(Vector::new(0.1, 0.0, 0.0), Vector::new(1.1, 1.0, 1.0));
/// bvh.insert_or_update_partially(new_aabb, 0, margin);
///
/// // Refit propagates the change detection flags
/// bvh.refit(&mut workspace);
/// # }
/// ```
///
/// # Comparison with `refit_without_opt`
///
/// This method reorganizes the tree in memory for better cache performance.
/// If you only need to update AABBs without reordering, use [`refit_without_opt`](Self::refit_without_opt)
/// which is faster but doesn't improve memory layout.
///
/// # Notes
///
/// - Reuses the provided `workspace` to avoid allocations
/// - Safe to call even if no leaves were modified (just reorganizes tree)
/// - Does not change the tree's topology, only AABBs and layout
/// - Call this before [`optimize_incremental`] for best results
///
/// # See Also
///
/// - [`insert_or_update_partially`](Bvh::insert_or_update_partially) - Update leaves
/// without propagation
/// - [`refit_without_opt`](Self::refit_without_opt) - Faster refit without memory
/// reorganization
/// - [`optimize_incremental`](Bvh::optimize_incremental) - Improve tree quality
/// - [`BvhWorkspace`] - Reusable workspace for operations
///
/// [`insert_or_update_partially`]: Bvh::insert_or_update_partially
/// [`insert`]: Bvh::insert
/// [`remove`]: Bvh::remove
/// [`optimize_incremental`]: Bvh::optimize_incremental
pub fn refit(&mut self, workspace: &mut BvhWorkspace) {
Self::refit_buffers(
&mut self.nodes,
&mut workspace.refit_tmp,
&mut self.leaf_node_indices,
&mut self.parents,
);
// Swap the old nodes with the refitted ones.
core::mem::swap(&mut self.nodes, &mut workspace.refit_tmp);
}
pub(super) fn refit_buffers(
source: &mut BvhNodeVec,
target: &mut BvhNodeVec,
leaf_data: &mut VecMap<BvhNodeIndex>,
parents: &mut Vec<BvhNodeIndex>,
) {
if source.is_empty() {
target.clear();
parents.clear();
} else if source[0].leaf_count() <= 2 {
// No actual refit to apply, just copy the root wide node.
target.clear();
parents.clear();
target.push(source[0]);
target[0].left.data.resolve_pending_change();
if target[0].right.leaf_count() > 0 {
target[0].right.data.resolve_pending_change();
}
parents.push(BvhNodeIndex::default());
} else if !source.is_empty() && source[0].leaf_count() > 2 {
target.resize(
source.len(),
BvhNodeWide {
left: BvhNode::zeros(),
right: BvhNode::zeros(),
},
);
let mut len = 1;
// Start with a special case for the root then recurse.
let left_child_id = source[0].left.children;
let right_child_id = source[0].right.children;
if !source[0].left.is_leaf() {
Self::refit_recurse(
source,
target,
leaf_data,
parents,
left_child_id,
&mut len,
BvhNodeIndex::left(0),
);
} else {
target[0].left = source[0].left;
target[0].left.data.resolve_pending_change();
// NOTE: updating the leaf_data shouldn’t be needed here since the root
// is always at 0.
// *self.leaf_data.get_mut_unknown_gen(left_child_id).unwrap() = BvhNodeIndex::left(0);
}
if !source[0].right.is_leaf() {
Self::refit_recurse(
source,
target,
leaf_data,
parents,
right_child_id,
&mut len,
BvhNodeIndex::right(0),
);
} else {
target[0].right = source[0].right;
target[0].right.data.resolve_pending_change();
// NOTE: updating the leaf_data shouldn’t be needed here since the root
// is always at 0.
// *self.leaf_data.get_mut_unknown_gen(right_child_id).unwrap() = BvhNodeIndex::right(0);
}
source.truncate(len as usize);
target.truncate(len as usize);
parents.truncate(len as usize);
}
}
fn refit_recurse(
source: &BvhNodeVec,
target: &mut BvhNodeVec,
leaf_data: &mut VecMap<BvhNodeIndex>,
parents: &mut [BvhNodeIndex],
source_id: u32,
target_id_mut: &mut u32,
parent: BvhNodeIndex,
) {
let target_id = *target_id_mut;
*target_id_mut += 1;
let node = &source[source_id as usize];
let left_is_leaf = node.left.is_leaf();
let right_is_leaf = node.right.is_leaf();
let left_source_id = node.left.children;
let right_source_id = node.right.children;
if !left_is_leaf {
Self::refit_recurse(
source,
target,
leaf_data,
parents,
left_source_id,
target_id_mut,
BvhNodeIndex::left(target_id),
);
} else {
let node = &source[source_id as usize];
target[target_id as usize].left = node.left;
target[target_id as usize]
.left
.data
.resolve_pending_change();
leaf_data[node.left.children as usize] = BvhNodeIndex::left(target_id);
}
if !right_is_leaf {
Self::refit_recurse(
source,
target,
leaf_data,
parents,
right_source_id,
target_id_mut,
BvhNodeIndex::right(target_id),
);
} else {
let node = &source[source_id as usize];
target[target_id as usize].right = node.right;
target[target_id as usize]
.right
.data
.resolve_pending_change();
leaf_data[node.right.children as usize] = BvhNodeIndex::right(target_id);
}
let node = &target[target_id as usize];
target[parent] = node.left.merged(&node.right, target_id);
parents[target_id as usize] = parent;
}
/// Similar to [`Self::refit`] but without any optimization of the internal node storage layout.
///
/// This can be faster than [`Self::refit`] but doesn’t reorder node to be more cache-efficient
/// on tree traversals.
pub fn refit_without_opt(&mut self) {
if self.leaf_count() > 2 {
let root = &self.nodes[0];
let left = root.left.children;
let right = root.right.children;
let left_is_leaf = root.left.is_leaf();
let right_is_leaf = root.right.is_leaf();
if !left_is_leaf {
self.recurse_refit_without_opt(left, BvhNodeIndex::left(0));
}
if !right_is_leaf {
self.recurse_refit_without_opt(right, BvhNodeIndex::right(0));
}
}
}
fn recurse_refit_without_opt(&mut self, node_id: u32, parent: BvhNodeIndex) {
let node = &self.nodes[node_id as usize];
let left = &node.left;
let right = &node.right;
let left_is_leaf = left.is_leaf();
let right_is_leaf = right.is_leaf();
let left_children = left.children;
let right_children = right.children;
if !left_is_leaf {
self.recurse_refit_without_opt(left_children, BvhNodeIndex::left(node_id));
} else {
self.nodes[node_id as usize]
.left
.data
.resolve_pending_change();
}
if !right_is_leaf {
self.recurse_refit_without_opt(right_children, BvhNodeIndex::right(node_id));
} else {
self.nodes[node_id as usize]
.right
.data
.resolve_pending_change();
}
let node = &self.nodes[node_id as usize];
let left = &node.left;
let right = &node.right;
let merged = left.merged(right, node_id);
self.nodes[parent] = merged;
}
}