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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// AABB query, closest query, ray cast, and box cast from dynamic_tree.c.
//
// The C callbacks take a `void* context`; the Rust versions take closures,
// which capture their context directly.
//
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
use super::{category_bits_match, BoxCastInput, DynamicTree, TreeStats, TREE_STACK_SIZE};
use crate::core::NULL_INDEX;
use crate::geometry::RayCastInput;
use crate::math_functions::{
aabb_center, aabb_extents, aabb_overlaps, add, clamp, distance_squared, dot, max, min, mul_add,
mul_sv, sub, test_bounds_ray_overlap, Aabb, Vec3,
};
/// Squared distance from a point to a node AABB. (static b3DistanceToNodeSqr)
fn distance_to_node_sqr(point: Vec3, node_aabb: Aabb) -> f32 {
let r = sub(
point,
clamp(point, node_aabb.lower_bound, node_aabb.upper_bound),
);
dot(r, r)
}
#[derive(Clone, Copy)]
struct QueryClosestItem {
node_index: i32,
distance_to_node_sqr: f32,
}
impl DynamicTree {
/// Query an AABB for overlapping proxies. The callback is called for each
/// proxy that overlaps the supplied AABB and passes the mask-bits filter;
/// return false from the callback to stop. (b3DynamicTree_Query)
pub fn query(
&self,
aabb: Aabb,
mask_bits: u64,
require_all_bits: bool,
mut callback: impl FnMut(i32, u64) -> bool,
) -> TreeStats {
let mut result = TreeStats::default();
if self.node_count == 0 {
return result;
}
let mut stack = [0i32; TREE_STACK_SIZE];
let mut stack_count = 0usize;
stack[stack_count] = self.root;
stack_count += 1;
while stack_count > 0 {
stack_count -= 1;
let node_id = stack[stack_count];
if node_id == NULL_INDEX {
debug_assert!(false);
continue;
}
let node = &self.nodes[node_id as usize];
result.node_visits += 1;
if category_bits_match(node.category_bits, mask_bits, require_all_bits)
&& aabb_overlaps(node.aabb, aabb)
{
if node.is_leaf() {
// callback to user code with proxy id
let proceed = callback(node_id, node.user_data);
result.leaf_visits += 1;
if !proceed {
return result;
}
} else {
debug_assert!(stack_count < TREE_STACK_SIZE - 1);
if stack_count < TREE_STACK_SIZE - 1 {
stack[stack_count] = node.child1;
stack_count += 1;
stack[stack_count] = node.child2;
stack_count += 1;
}
}
}
}
result
}
/// Query for the closest proxy to a point. The callback receives the current
/// minimum squared distance and returns an updated distance for that proxy.
/// (b3DynamicTree_QueryClosest)
pub fn query_closest(
&self,
point: Vec3,
mask_bits: u64,
require_all_bits: bool,
mut callback: impl FnMut(f32, i32, u64) -> f32,
min_distance_sqr: &mut f32,
) -> TreeStats {
let mut result = TreeStats::default();
if self.node_count == 0 {
return result;
}
let mut min_sqr = *min_distance_sqr;
let mut stack = [QueryClosestItem {
node_index: 0,
distance_to_node_sqr: 0.0,
}; TREE_STACK_SIZE];
let mut stack_count = 0usize;
let root_distance_sqr = distance_to_node_sqr(point, self.nodes[self.root as usize].aabb);
stack[stack_count] = QueryClosestItem {
node_index: self.root,
distance_to_node_sqr: root_distance_sqr,
};
stack_count += 1;
while stack_count > 0 {
stack_count -= 1;
let item = stack[stack_count];
let node = &self.nodes[item.node_index as usize];
result.node_visits += 1;
if category_bits_match(node.category_bits, mask_bits, require_all_bits)
&& item.distance_to_node_sqr < min_sqr
{
if node.is_leaf() {
let dd = callback(min_sqr, item.node_index, node.user_data);
if dd < min_sqr {
min_sqr = dd;
}
result.leaf_visits += 1;
} else {
debug_assert!(stack_count < TREE_STACK_SIZE - 1);
if stack_count < TREE_STACK_SIZE - 1 {
let child1 = node.child1;
let child2 = node.child2;
let item1 = QueryClosestItem {
node_index: child1,
distance_to_node_sqr: distance_to_node_sqr(
point,
self.nodes[child1 as usize].aabb,
),
};
let item2 = QueryClosestItem {
node_index: child2,
distance_to_node_sqr: distance_to_node_sqr(
point,
self.nodes[child2 as usize].aabb,
),
};
// Ensure we iterate the closest child first as we pop
if item2.distance_to_node_sqr < item1.distance_to_node_sqr {
stack[stack_count] = item1;
stack_count += 1;
stack[stack_count] = item2;
stack_count += 1;
} else {
stack[stack_count] = item2;
stack_count += 1;
stack[stack_count] = item1;
stack_count += 1;
}
}
}
}
}
*min_distance_sqr = min_sqr;
result
}
/// Ray cast against the proxies in the tree. The callback performs an
/// exact ray cast when the proxy contains a shape, and returns the new
/// ray fraction:
/// - return 0 to terminate the ray cast
/// - return a value less than the input max_fraction to clip the ray
/// - return the input max_fraction to continue without clipping
///
/// (b3DynamicTree_RayCast)
pub fn ray_cast(
&self,
input: &RayCastInput,
mask_bits: u64,
require_all_bits: bool,
mut callback: impl FnMut(&RayCastInput, i32, u64) -> f32,
) -> TreeStats {
let mut result = TreeStats::default();
if self.node_count == 0 {
return result;
}
let p1 = input.origin;
let d = input.translation;
let mut max_fraction = input.max_fraction;
let mut p2 = mul_add(p1, max_fraction, d);
// Build a bounding box for the segment.
let mut segment_aabb = Aabb {
lower_bound: min(p1, p2),
upper_bound: max(p1, p2),
};
let mut stack = [0i32; TREE_STACK_SIZE];
let mut stack_count = 0usize;
stack[stack_count] = self.root;
stack_count += 1;
let mut sub_input = *input;
while stack_count > 0 {
stack_count -= 1;
let node_id = stack[stack_count];
if node_id == NULL_INDEX {
debug_assert!(false);
continue;
}
let node = &self.nodes[node_id as usize];
result.node_visits += 1;
let node_aabb = node.aabb;
if !category_bits_match(node.category_bits, mask_bits, require_all_bits)
|| !aabb_overlaps(node_aabb, segment_aabb)
{
continue;
}
if !test_bounds_ray_overlap(node_aabb.lower_bound, node_aabb.upper_bound, p1, d) {
continue;
}
if node.is_leaf() {
sub_input.max_fraction = max_fraction;
let value = callback(&sub_input, node_id, node.user_data);
result.leaf_visits += 1;
// The user may return -1 to indicate this shape should be skipped
if value == 0.0 {
// The client has terminated the ray cast.
return result;
}
if 0.0 < value && value <= max_fraction {
// Update segment bounding box.
max_fraction = value;
p2 = mul_add(p1, max_fraction, d);
segment_aabb.lower_bound = min(p1, p2);
segment_aabb.upper_bound = max(p1, p2);
}
} else {
debug_assert!(stack_count < TREE_STACK_SIZE - 1);
if stack_count < TREE_STACK_SIZE - 1 {
let c1 = aabb_center(self.nodes[node.child1 as usize].aabb);
let c2 = aabb_center(self.nodes[node.child2 as usize].aabb);
if distance_squared(c1, p1) < distance_squared(c2, p1) {
stack[stack_count] = node.child2;
stack_count += 1;
stack[stack_count] = node.child1;
stack_count += 1;
} else {
stack[stack_count] = node.child1;
stack_count += 1;
stack[stack_count] = node.child2;
stack_count += 1;
}
}
}
}
result
}
/// Cast a swept AABB through the tree. The callback returns the new cast
/// fraction, with the same semantics as [`DynamicTree::ray_cast`].
/// (b3DynamicTree_BoxCast)
pub fn box_cast(
&self,
input: &BoxCastInput,
mask_bits: u64,
require_all_bits: bool,
mut callback: impl FnMut(&BoxCastInput, i32, u64) -> f32,
) -> TreeStats {
let mut stats = TreeStats::default();
if self.node_count == 0 {
return stats;
}
// The caller folds the shape radius and the world origin into the box
let origin_aabb = input.box_;
let p1 = aabb_center(origin_aabb);
let extension = aabb_extents(origin_aabb);
let d = input.translation;
let mut max_fraction = input.max_fraction;
// Build total box for the cast
let mut t = mul_sv(max_fraction, input.translation);
let mut total_aabb = Aabb {
lower_bound: min(origin_aabb.lower_bound, add(origin_aabb.lower_bound, t)),
upper_bound: max(origin_aabb.upper_bound, add(origin_aabb.upper_bound, t)),
};
let mut sub_input = *input;
let mut stack = [0i32; TREE_STACK_SIZE];
let mut stack_count = 0usize;
stack[stack_count] = self.root;
stack_count += 1;
while stack_count > 0 {
stack_count -= 1;
let node_id = stack[stack_count];
if node_id == NULL_INDEX {
debug_assert!(false);
continue;
}
let node = &self.nodes[node_id as usize];
stats.node_visits += 1;
if !category_bits_match(node.category_bits, mask_bits, require_all_bits)
|| !aabb_overlaps(node.aabb, total_aabb)
{
continue;
}
// radius extension is added to the node in this case
let lower = sub(node.aabb.lower_bound, extension);
let upper = add(node.aabb.upper_bound, extension);
if !test_bounds_ray_overlap(lower, upper, p1, d) {
continue;
}
if node.is_leaf() {
sub_input.max_fraction = max_fraction;
let value = callback(&sub_input, node_id, node.user_data);
stats.leaf_visits += 1;
if value == 0.0 {
// The client has terminated the cast.
return stats;
}
if 0.0 < value && value < max_fraction {
max_fraction = value;
t = mul_sv(max_fraction, input.translation);
total_aabb.lower_bound =
min(origin_aabb.lower_bound, add(origin_aabb.lower_bound, t));
total_aabb.upper_bound =
max(origin_aabb.upper_bound, add(origin_aabb.upper_bound, t));
}
} else {
debug_assert!(stack_count < TREE_STACK_SIZE - 1);
if stack_count < TREE_STACK_SIZE - 1 {
let c1 = aabb_center(self.nodes[node.child1 as usize].aabb);
let c2 = aabb_center(self.nodes[node.child2 as usize].aabb);
if distance_squared(c1, p1) < distance_squared(c2, p1) {
stack[stack_count] = node.child2;
stack_count += 1;
stack[stack_count] = node.child1;
stack_count += 1;
} else {
stack[stack_count] = node.child1;
stack_count += 1;
stack[stack_count] = node.child2;
stack_count += 1;
}
}
}
}
stats
}
}