crcbl_phys/compound.rs
1//! Rigid compounds: a set of boxes fixed in one body's local space, queried
2//! at a pose.
3//!
4//! A game item or a body built from several meshes is bounded tighter by one
5//! box per part than by a single box around the lot, and those parts turn with
6//! the body. [`AabbCompound`] holds the parts as axis-aligned boxes in the
7//! body's own frame and answers queries at whatever [`Transform`] the body has
8//! this frame: each query moves its input into local space, runs the existing
9//! single-box primitive ([`ray_vs_aabb`], [`Aabb::closest_point`]) against
10//! every part, and moves the answer back out. Rotation preserves length, so a
11//! distance measured in local space is the world-space distance.
12//!
13//! What a game does with the answer — reach limits, line of sight, ranking one
14//! target against another — is the game's, not this module's.
15
16use crate::broadphase::Ray;
17use crate::collider::Aabb;
18use crate::components::Transform;
19use crate::query::{ShapeHit, ray_vs_aabb};
20use glam::DVec3;
21use std::fmt;
22
23/// Why [`AabbCompound::new`] or [`crate::CompoundShape::new`] refused a set
24/// of parts. The query compound refuses only the first two;
25/// the rest are the collision shape's, which must also be a body.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum CompoundError {
28 /// A corner of the part at `index` holds a `NaN` or an infinity. A
29 /// poisoned part would turn every query that reaches it into a `NaN`, and
30 /// an infinite one bounds nothing a body can be.
31 NonFinitePart {
32 /// The part's index in the slice given to [`AabbCompound::new`].
33 index: usize,
34 },
35 /// The part at `index` has `min` past `max` on an axis, so it is empty
36 /// ([`Aabb::is_empty`]) and not a part of anything. A flat box, with `min`
37 /// equal to `max` on an axis, is accepted.
38 InvertedPart {
39 /// The part's index in the slice given to [`AabbCompound::new`].
40 index: usize,
41 },
42 /// A collision shape with no parts: nothing to collide or weigh.
43 NoParts,
44 /// A collision shape with more than [`crate::CompoundShape::MAX_PARTS`]
45 /// parts.
46 TooManyParts {
47 /// How many parts it was given.
48 count: usize,
49 },
50 /// The part at `index` of a collision shape has a rotation that is not a
51 /// unit quaternion, which would scale the box as it turned it.
52 NonUnitRotation {
53 /// The part's index in the parts given.
54 index: usize,
55 },
56 /// Every part of a collision shape is flat, so a density weighs nothing.
57 NoVolume,
58 /// A collision shape's parts are so large or so small that their mass
59 /// properties overflow or underflow an `f64`: no rigid body can carry
60 /// them, and [`crate::RigidBody::with_inertia`] would refuse the tensor.
61 UnweighableMass,
62}
63
64impl fmt::Display for CompoundError {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 Self::NonFinitePart { index } => {
68 write!(f, "compound part {index} has a non-finite corner")
69 }
70 Self::InvertedPart { index } => {
71 write!(f, "compound part {index} has min past max on an axis")
72 }
73 Self::NoParts => write!(f, "a compound shape needs at least one part"),
74 Self::TooManyParts { count } => write!(
75 f,
76 "a compound shape has at most {} parts, not {count}",
77 crate::CompoundShape::MAX_PARTS
78 ),
79 Self::NonUnitRotation { index } => {
80 write!(
81 f,
82 "compound part {index} has a rotation of other than unit length"
83 )
84 }
85 Self::NoVolume => write!(f, "every part of a compound shape is flat"),
86 Self::UnweighableMass => write!(
87 f,
88 "a compound shape's mass properties are out of an f64's range"
89 ),
90 }
91 }
92}
93
94impl std::error::Error for CompoundError {}
95
96/// A ray's nearest hit on an [`AabbCompound`], in world space.
97#[derive(Debug, Clone, Copy, PartialEq)]
98pub struct CompoundHit {
99 /// Index of the part struck, in the slice the compound was built from.
100 pub part: usize,
101 /// The hit itself: `t` along the world ray, the world point
102 /// `ray.origin + ray.dir * t`, and the part's outward face normal turned
103 /// into world space. `started_inside` means the ray began inside this part
104 /// and the hit is its exit face, as [`ray_vs_aabb`] reports.
105 pub hit: ShapeHit,
106}
107
108/// The point of one part of an [`AabbCompound`] nearest a query point.
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct CompoundPoint {
111 /// Index of the part, in the slice the compound was built from.
112 pub part: usize,
113 /// The nearest world-space point on or in that part. When the query point
114 /// is inside the part this is the query point itself, bit for bit.
115 pub point: DVec3,
116 /// World-space distance from the query point to [`point`](Self::point);
117 /// exactly `0.0` inside the part.
118 pub distance: f64,
119}
120
121/// Axis-aligned boxes fixed in one rigid body's local frame.
122///
123/// Borrows its parts, so a game keeps them in whatever storage it already has
124/// and builds this view per query at the cost of one validation pass. Every
125/// part is finite and non-inverted by construction; an empty set of parts is
126/// allowed, and every query on it answers `None` (or nothing).
127///
128/// Queries take the body's pose as a [`Transform`] and refuse — answer `None`
129/// — a pose whose position is not finite or whose rotation is not a finite
130/// unit quaternion, and a query point or ray that is not finite. None of them
131/// skips a `NaN` silently: a poisoned input is never read as a miss that some
132/// other part then wins.
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct AabbCompound<'a> {
135 parts: &'a [Aabb],
136}
137
138impl<'a> AabbCompound<'a> {
139 /// A compound of `parts`, each an axis-aligned box in the body's local
140 /// frame. Part indices in every answer are indices into `parts`.
141 ///
142 /// # Errors
143 ///
144 /// [`CompoundError::NonFinitePart`] for a part with a `NaN` or infinite
145 /// corner, [`CompoundError::InvertedPart`] for one with `min` past `max`,
146 /// each naming the first such part.
147 pub fn new(parts: &'a [Aabb]) -> Result<Self, CompoundError> {
148 for (index, part) in parts.iter().enumerate() {
149 if !part.min.is_finite() || !part.max.is_finite() {
150 return Err(CompoundError::NonFinitePart { index });
151 }
152 if part.is_empty() {
153 return Err(CompoundError::InvertedPart { index });
154 }
155 }
156 Ok(Self { parts })
157 }
158
159 /// The parts, in the order given to [`new`](Self::new).
160 #[inline]
161 #[must_use]
162 pub fn parts(&self) -> &'a [Aabb] {
163 self.parts
164 }
165
166 /// The nearest part `ray` strikes with the body at `pose`, or `None` for a
167 /// miss, an empty compound, or a refused input.
168 ///
169 /// `t` is in units of `ray.dir`'s length, as for [`ray_vs_aabb`], and is
170 /// the same in world and local space because rotation preserves length;
171 /// `ray.t_min`/`t_max` bound it in those units. A ray that starts inside a
172 /// part reports that part's exit face with
173 /// [`started_inside`](ShapeHit::started_inside) set — the rule
174 /// [`ray_vs_aabb`] follows — so a part the ray enters before that exit
175 /// wins. Two parts struck at the same `t` resolve to the lower index.
176 ///
177 /// Refused, besides a bad `pose`: a ray whose origin or direction is not
178 /// finite, whose direction is zero, whose `t_min` is not finite, or whose
179 /// `t_max` is `NaN`, or whose origin overflows once taken relative to the
180 /// pose. A zero direction has no hit to report, and an unbounded `t_min`
181 /// would put the hit at infinity.
182 #[must_use]
183 pub fn ray_cast(&self, pose: &Transform, ray: &Ray) -> Option<CompoundHit> {
184 if !valid_pose(pose)
185 || !ray.origin.is_finite()
186 || !ray.dir.is_finite()
187 || ray.dir == DVec3::ZERO
188 || !ray.t_min.is_finite()
189 || ray.t_max.is_nan()
190 {
191 return None;
192 }
193 let to_local = pose.rotation.inverse();
194 let local = Ray {
195 origin: to_local * (ray.origin - pose.position),
196 dir: to_local * ray.dir,
197 ..*ray
198 };
199 // Finite inputs can still overflow on the way in (an origin and a
200 // position at opposite ends of `f64`), and a `NaN` from that would
201 // miss every part silently rather than be refused.
202 if !local.origin.is_finite() || !local.dir.is_finite() {
203 return None;
204 }
205 let (part, local_hit) = self
206 .parts
207 .iter()
208 .enumerate()
209 .filter_map(|(part, aabb)| ray_vs_aabb(&local, aabb).map(|hit| (part, hit)))
210 .min_by(|(_, a), (_, b)| a.t.total_cmp(&b.t))?;
211 Some(CompoundHit {
212 part,
213 hit: ShapeHit {
214 // Rebuilt from the world ray rather than rotated back, so the
215 // point lies on the ray the caller cast.
216 point: ray.origin + ray.dir * local_hit.t,
217 normal: pose.rotation * local_hit.normal,
218 ..local_hit
219 },
220 })
221 }
222
223 /// The nearest point of each part to `point`, with the body at `pose`, in
224 /// part order; `None` for a refused input (a bad `pose`, or a `point` that
225 /// is not finite or overflows once taken relative to the pose). An empty
226 /// compound yields nothing.
227 ///
228 /// For a caller that filters parts before choosing — by reach or line of
229 /// sight — and so needs every candidate rather than only the nearest; see
230 /// [`closest_point`](Self::closest_point) for that.
231 #[must_use]
232 pub fn closest_points(
233 &self,
234 pose: &Transform,
235 point: DVec3,
236 ) -> Option<impl Iterator<Item = CompoundPoint> + use<'a>> {
237 if !valid_pose(pose) || !point.is_finite() {
238 return None;
239 }
240 let pose = *pose;
241 let local = pose.rotation.inverse() * (point - pose.position);
242 // Overflow on the way in, refused for the reason `ray_cast` gives.
243 if !local.is_finite() {
244 return None;
245 }
246 Some(self.parts.iter().enumerate().map(move |(part, aabb)| {
247 let nearest = aabb
248 .closest_point(local)
249 .expect("parts are finite and non-inverted by construction, the point finite");
250 if nearest == local {
251 // Inside: the query point is its own answer. Rotating the local
252 // copy back out would return it off by a rounding.
253 CompoundPoint {
254 part,
255 point,
256 distance: 0.0,
257 }
258 } else {
259 CompoundPoint {
260 part,
261 point: pose.position + pose.rotation * nearest,
262 distance: local.distance(nearest),
263 }
264 }
265 }))
266 }
267
268 /// The nearest point on any part to `point`, with the body at `pose`, or
269 /// `None` for an empty compound or a refused input (see
270 /// [`closest_points`](Self::closest_points)). Two parts at the same
271 /// distance resolve to the lower index.
272 #[must_use]
273 pub fn closest_point(&self, pose: &Transform, point: DVec3) -> Option<CompoundPoint> {
274 self.closest_points(pose, point)?
275 .min_by(|a, b| a.distance.total_cmp(&b.distance))
276 }
277}
278
279/// Whether `pose` can place a body: a finite position and a finite unit
280/// rotation. A rotation that is not unit length scales as it turns, so the
281/// local-space answers would not map back to world space.
282fn valid_pose(pose: &Transform) -> bool {
283 pose.position.is_finite() && pose.rotation.is_finite() && pose.rotation.is_normalized()
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289 use core::f64::consts::FRAC_1_SQRT_2;
290 use glam::DQuat;
291
292 const EPS: f64 = 1e-12;
293
294 /// A quarter turn about `+Z`: local `+X` is world `+Y`, local `+Y` is
295 /// world `-X`. Written out rather than built with
296 /// `DQuat::from_rotation_z`, which this crate's determinism lint refuses.
297 fn quarter_turn_z() -> DQuat {
298 DQuat::from_xyzw(0.0, 0.0, FRAC_1_SQRT_2, FRAC_1_SQRT_2)
299 }
300
301 fn pose() -> Transform {
302 Transform::new(DVec3::new(10.0, 20.0, 30.0), quarter_turn_z())
303 }
304
305 /// EW's fixture: a unit cube at the origin and one two metres along `+X`,
306 /// listed far one first so the nearest is not simply the first.
307 fn ew_parts() -> [Aabb; 2] {
308 [
309 Aabb::new(DVec3::new(2.0, 0.0, 0.0), DVec3::new(3.0, 1.0, 1.0)),
310 Aabb::new(DVec3::ZERO, DVec3::ONE),
311 ]
312 }
313
314 fn assert_near(actual: DVec3, expected: DVec3) {
315 assert!(
316 actual.distance(expected) < EPS,
317 "got {actual:?}, expected {expected:?}"
318 );
319 }
320
321 // -- ray cast ------------------------------------------------------------
322
323 /// EW's `interaction_ray_hit_returns_the_nearest_rigid_compound_part`.
324 ///
325 /// The ray starts at world `(9.5, 17, 30.5)` heading `+Y`. Relative to the
326 /// pose that is `(-0.5, -3, 0.5)`, which the inverse quarter turn takes to
327 /// local `(-3, 0.5, 0.5)` heading local `+X`. It enters the cube at the
328 /// origin (part 1) at local `x = 0`, `t = 3`, before the far cube (part 0)
329 /// at `t = 5`: world point `(9.5, 20, 30.5)`, and the struck face's local
330 /// normal `-X` is world `-Y`.
331 #[test]
332 fn a_ray_hits_the_nearest_part_of_a_rotated_compound() {
333 let parts = ew_parts();
334 let compound = AabbCompound::new(&parts).unwrap();
335 let ray = Ray::new(DVec3::new(9.5, 17.0, 30.5), DVec3::Y);
336 let hit = compound.ray_cast(&pose(), &ray).expect("the ray hits");
337 assert_eq!(hit.part, 1);
338 assert!((hit.hit.t - 3.0).abs() < EPS, "t = {}", hit.hit.t);
339 assert_near(hit.hit.point, DVec3::new(9.5, 20.0, 30.5));
340 assert_near(hit.hit.normal, DVec3::NEG_Y);
341 assert!(!hit.hit.started_inside);
342 }
343
344 /// `t` is in units of the direction's length, as for `ray_vs_aabb`: the
345 /// same ray with a direction twice as long reaches the same point at half
346 /// the `t`.
347 #[test]
348 fn a_ray_cast_measures_t_in_units_of_its_direction() {
349 let parts = ew_parts();
350 let compound = AabbCompound::new(&parts).unwrap();
351 let ray = Ray::new(DVec3::new(9.5, 17.0, 30.5), DVec3::Y * 2.0);
352 let hit = compound.ray_cast(&pose(), &ray).expect("the ray hits");
353 assert!((hit.hit.t - 1.5).abs() < EPS, "t = {}", hit.hit.t);
354 assert_near(hit.hit.point, DVec3::new(9.5, 20.0, 30.5));
355 }
356
357 /// Aimed back the way it came, beside the body, or cut short of it: none
358 /// of these touch a part.
359 #[test]
360 fn a_ray_that_misses_every_part_is_none() {
361 let parts = ew_parts();
362 let compound = AabbCompound::new(&parts).unwrap();
363 let origin = DVec3::new(9.5, 17.0, 30.5);
364 assert_eq!(
365 compound.ray_cast(&pose(), &Ray::new(origin, DVec3::NEG_Y)),
366 None
367 );
368 // Local y = 0.5 + 3 is above every part.
369 assert_eq!(
370 compound.ray_cast(&pose(), &Ray::new(origin - DVec3::X * 3.0, DVec3::Y)),
371 None
372 );
373 assert_eq!(
374 compound.ray_cast(&pose(), &Ray::new(origin, DVec3::Y).with_bounds(0.0, 2.5)),
375 None
376 );
377 }
378
379 /// Starting at local `(0.5, 0.5, 0.5)`, the centre of part 1, heading
380 /// local `+X` (world `+Y`): part 1's exit face is at `t = 0.5`, nearer
381 /// than part 0's entry at `t = 1.5`, so part 1 is reported, flagged as
382 /// started inside, with the exit face's normal (local `+X`, world `+Y`).
383 #[test]
384 fn a_ray_starting_inside_a_part_reports_its_exit_face() {
385 let parts = ew_parts();
386 let compound = AabbCompound::new(&parts).unwrap();
387 let origin = DVec3::new(9.5, 20.5, 30.5);
388 let hit = compound
389 .ray_cast(&pose(), &Ray::new(origin, DVec3::Y))
390 .expect("a ray from inside hits its exit face");
391 assert_eq!(hit.part, 1);
392 assert!(hit.hit.started_inside);
393 assert!((hit.hit.t - 0.5).abs() < EPS, "t = {}", hit.hit.t);
394 assert_near(hit.hit.point, DVec3::new(9.5, 21.0, 30.5));
395 assert_near(hit.hit.normal, DVec3::Y);
396 }
397
398 /// EW's refusals, a zero direction and a rotation that is not unit length,
399 /// plus every `NaN` input.
400 #[test]
401 fn a_ray_cast_refuses_non_finite_or_degenerate_input() {
402 let parts = ew_parts();
403 let compound = AabbCompound::new(&parts).unwrap();
404 let good = Ray::new(DVec3::new(9.5, 17.0, 30.5), DVec3::Y);
405 assert!(compound.ray_cast(&pose(), &good).is_some());
406
407 let nan = f64::NAN;
408 let bad_rays = [
409 Ray::new(DVec3::ZERO, DVec3::ZERO),
410 Ray::new(DVec3::new(nan, 17.0, 30.5), DVec3::Y),
411 Ray::new(good.origin, DVec3::new(0.0, nan, 0.0)),
412 Ray::new(good.origin, DVec3::new(0.0, f64::INFINITY, 0.0)),
413 good.with_bounds(nan, f64::INFINITY),
414 good.with_bounds(f64::NEG_INFINITY, f64::INFINITY),
415 good.with_bounds(0.0, nan),
416 ];
417 for ray in bad_rays {
418 assert_eq!(compound.ray_cast(&pose(), &ray), None, "{ray:?}");
419 }
420
421 let bad_poses = [
422 Transform::new(DVec3::new(10.0, nan, 30.0), quarter_turn_z()),
423 Transform::new(pose().position, DQuat::from_xyzw(0.0, 0.0, nan, 1.0)),
424 ];
425 for bad in bad_poses {
426 assert_eq!(compound.ray_cast(&bad, &good), None, "{bad:?}");
427 }
428
429 // EW's non-unit rotation case. The ray lines up with part 1 whether
430 // or not the rotation scales it, so only the refusal makes it `None`.
431 let position = pose().position;
432 let ray = Ray::new(position + DVec3::new(-3.0, 0.125, 0.125), DVec3::X);
433 let unit = Transform::from_position(position);
434 assert!(compound.ray_cast(&unit, &ray).is_some());
435 let scaling = Transform::new(position, DQuat::from_xyzw(0.0, 0.0, 0.0, 2.0));
436 assert_eq!(compound.ray_cast(&scaling, &ray), None);
437
438 // Every input finite, but the origin relative to the pose overflows.
439 let far = Transform::new(DVec3::new(-f64::MAX, 20.0, 30.0), quarter_turn_z());
440 let ray = Ray::new(DVec3::new(f64::MAX, 20.0, 30.0), DVec3::Y);
441 assert_eq!(compound.ray_cast(&far, &ray), None);
442 }
443
444 // -- closest point -------------------------------------------------------
445
446 /// Local query `(3, -1, 0.5)` against the unit cube clamps to
447 /// `(1, 0, 0.5)`, a corner edge `√5` away. At the pose the query is world
448 /// `(10 + 1, 20 + 3, 30.5)` and the answer world `(10, 21, 30.5)`.
449 #[test]
450 fn the_closest_point_outside_a_rotated_part_is_on_its_surface() {
451 let parts = [Aabb::new(DVec3::ZERO, DVec3::ONE)];
452 let compound = AabbCompound::new(&parts).unwrap();
453 let nearest = compound
454 .closest_point(&pose(), DVec3::new(11.0, 23.0, 30.5))
455 .unwrap();
456 assert_eq!(nearest.part, 0);
457 assert_near(nearest.point, DVec3::new(10.0, 21.0, 30.5));
458 assert!(
459 (nearest.distance - 5.0_f64.sqrt()).abs() < EPS,
460 "distance {}",
461 nearest.distance
462 );
463 }
464
465 /// A point placed at local `(0.1, 0.1, 0.3)`, inside the unit cube: the
466 /// answer is the query point itself, bit for bit, at distance zero.
467 ///
468 /// The body sits at the origin because a translation of tens of metres
469 /// absorbs the last-bit error of a round trip through local space, and
470 /// the quarter turn's `FRAC_1_SQRT_2` components are not exactly unit
471 /// length, so rotating this point out and back again lands its `z` off in
472 /// the last bits — which is what an answer rotated back out would return.
473 #[test]
474 fn the_closest_point_to_a_point_inside_a_part_is_that_point() {
475 let parts = [Aabb::new(DVec3::ZERO, DVec3::ONE)];
476 let compound = AabbCompound::new(&parts).unwrap();
477 let at_origin = Transform::new(DVec3::ZERO, quarter_turn_z());
478 let inside = at_origin.rotation * DVec3::new(0.1, 0.1, 0.3);
479 let nearest = compound.closest_point(&at_origin, inside).unwrap();
480 assert_eq!(nearest.part, 0);
481 assert_eq!(nearest.point, inside);
482 assert_eq!(nearest.distance, 0.0);
483 }
484
485 /// Local query `(1.75, 0.5, 0.5)` is `0.75` from the unit cube (part 1),
486 /// `0.25` from the cube at `x = 2` (part 2) and `5.75` from the one at
487 /// `x = -5` (part 0). Part 2 wins, at local `(2, 0.5, 0.5)`, world
488 /// `(9.5, 22, 30.5)`; `closest_points` reports all three in part order.
489 #[test]
490 fn the_closest_point_is_chosen_from_the_nearest_of_several_parts() {
491 let parts = [
492 Aabb::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(-4.0, 1.0, 1.0)),
493 Aabb::new(DVec3::ZERO, DVec3::ONE),
494 Aabb::new(DVec3::new(2.0, 0.0, 0.0), DVec3::new(3.0, 1.0, 1.0)),
495 ];
496 let compound = AabbCompound::new(&parts).unwrap();
497 let query = DVec3::new(9.5, 21.75, 30.5);
498
499 let nearest = compound.closest_point(&pose(), query).unwrap();
500 assert_eq!(nearest.part, 2);
501 assert_near(nearest.point, DVec3::new(9.5, 22.0, 30.5));
502 assert!((nearest.distance - 0.25).abs() < EPS);
503
504 let every: Vec<_> = compound.closest_points(&pose(), query).unwrap().collect();
505 let found: Vec<_> = every.iter().map(|p| (p.part, p.distance)).collect();
506 assert_eq!(found.len(), 3);
507 for ((part, distance), (want_part, want)) in
508 found.into_iter().zip([(0, 5.75), (1, 0.75), (2, 0.25)])
509 {
510 assert_eq!(part, want_part);
511 assert!((distance - want).abs() < EPS, "part {part}: {distance}");
512 }
513 }
514
515 #[test]
516 fn a_closest_point_query_refuses_non_finite_input() {
517 let parts = [Aabb::new(DVec3::ZERO, DVec3::ONE)];
518 let compound = AabbCompound::new(&parts).unwrap();
519 let query = DVec3::new(11.0, 23.0, 30.5);
520 assert!(compound.closest_point(&pose(), query).is_some());
521
522 let nan = f64::NAN;
523 for bad in [
524 DVec3::new(nan, 23.0, 30.5),
525 DVec3::new(11.0, f64::INFINITY, 30.5),
526 ] {
527 assert_eq!(compound.closest_point(&pose(), bad), None, "{bad:?}");
528 assert!(compound.closest_points(&pose(), bad).is_none(), "{bad:?}");
529 }
530 for bad in [
531 Transform::new(DVec3::new(nan, 20.0, 30.0), quarter_turn_z()),
532 Transform::new(pose().position, DQuat::from_xyzw(nan, 0.0, 0.0, 1.0)),
533 Transform::new(pose().position, DQuat::from_xyzw(0.0, 0.0, 0.0, 2.0)),
534 ] {
535 assert_eq!(compound.closest_point(&bad, query), None, "{bad:?}");
536 assert!(compound.closest_points(&bad, query).is_none(), "{bad:?}");
537 }
538
539 // Every input finite, but the point relative to the pose overflows.
540 let far = Transform::new(DVec3::new(-f64::MAX, 20.0, 30.0), quarter_turn_z());
541 let point = DVec3::new(f64::MAX, 20.0, 30.0);
542 assert_eq!(compound.closest_point(&far, point), None);
543 }
544
545 // -- construction --------------------------------------------------------
546
547 #[test]
548 fn an_empty_compound_answers_none() {
549 let compound = AabbCompound::new(&[]).unwrap();
550 let ray = Ray::new(DVec3::new(9.5, 17.0, 30.5), DVec3::Y);
551 assert_eq!(compound.ray_cast(&pose(), &ray), None);
552 assert_eq!(compound.closest_point(&pose(), DVec3::ZERO), None);
553 assert_eq!(
554 compound
555 .closest_points(&pose(), DVec3::ZERO)
556 .map(Iterator::count),
557 Some(0)
558 );
559 }
560
561 #[test]
562 fn a_compound_refuses_a_non_finite_or_inverted_part() {
563 let unit = Aabb::new(DVec3::ZERO, DVec3::ONE);
564 let nan = Aabb::new(DVec3::new(0.0, f64::NAN, 0.0), DVec3::ONE);
565 let infinite = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 1.0, f64::INFINITY));
566 let inverted = Aabb::new(DVec3::ONE, DVec3::new(2.0, 0.5, 2.0));
567 let flat = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 0.0, 1.0));
568
569 assert_eq!(
570 AabbCompound::new(&[unit, nan]),
571 Err(CompoundError::NonFinitePart { index: 1 })
572 );
573 assert_eq!(
574 AabbCompound::new(&[infinite, unit]),
575 Err(CompoundError::NonFinitePart { index: 0 })
576 );
577 assert_eq!(
578 AabbCompound::new(&[unit, unit, inverted]),
579 Err(CompoundError::InvertedPart { index: 2 })
580 );
581 assert_eq!(
582 AabbCompound::new(&[Aabb::EMPTY]),
583 Err(CompoundError::NonFinitePart { index: 0 }),
584 "Aabb::EMPTY's corners are infinite"
585 );
586 assert!(AabbCompound::new(&[unit, flat]).is_ok());
587 }
588}