crcbl_phys/compound_shape.rs
1//! Compound collision shapes: several boxes fixed in one body's frame that the
2//! contact pipeline collides as one rigid body.
3//!
4//! [`AabbCompound`] is the query half of a body made of parts; this is the
5//! dynamic half. A [`CompoundShape`] is carried by
6//! [`ColliderComponent::Compound`], and in a system
7//! [`with_contacts`](crate::PhysicsSystem::with_contacts) each of its parts is
8//! a box of its own to the broadphase and the narrow phase, turning with the
9//! body — see [`crate::contact`]'s "Compounds" section for why each part is
10//! its own proxy.
11//!
12//! # Mass: parts summed, overlaps counted twice
13//!
14//! [`CompoundShape::mass_properties`] gives each part the mass of its own
15//! volume at one density and sums the parts with the parallel-axis theorem,
16//! through [`MassProperties::combine`]. Where two parts overlap, the overlap is
17//! counted once for each: a padded receiver box inside a stock box weighs
18//! twice. That is what Box2D, Rapier and Jolt do with a compound's children,
19//! and it is chosen here for the same reasons: it is exact for parts that do
20//! not overlap, it holds for turned parts where an exact union would need
21//! polyhedral clipping, and a game that does not author mass — EW's items —
22//! gets a distribution that follows its silhouette, which is what makes a
23//! rifle tumble like a rifle. A game that needs a true mass passes it to
24//! [`MassProperties::of_collider`]; the centre of mass and the inertia's shape
25//! are the part that matters, and a doubled overlap moves them towards where
26//! the parts crowd, which is where the solid is.
27
28use std::sync::Arc;
29
30use glam::{DMat3, DQuat, DVec3};
31
32use crate::collider::{Aabb, BoxCollider};
33use crate::components::{ColliderComponent, RigidBody, Transform, is_positive_definite};
34use crate::compound::{AabbCompound, CompoundError};
35use crate::contact::shape::ContactShape;
36use crate::mass::MassProperties;
37
38/// One box of a [`CompoundShape`], fixed in the body's frame.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct CompoundPart {
41 /// Its centre, in the shape's frame.
42 pub centre: DVec3,
43 /// Its orientation in the shape's frame: identity for a box whose faces
44 /// are the body's own axes, as every part [`CompoundPart::from_aabb`]
45 /// makes is.
46 pub rotation: DQuat,
47 /// Its half-extents along its own axes, in metres.
48 pub half_extents: DVec3,
49}
50
51impl CompoundPart {
52 /// A part centred at `centre`, turned by `rotation` and `half_extents`
53 /// across. [`CompoundShape::new`] checks it.
54 #[inline]
55 #[must_use]
56 pub const fn new(centre: DVec3, rotation: DQuat, half_extents: DVec3) -> Self {
57 Self {
58 centre,
59 rotation,
60 half_extents,
61 }
62 }
63
64 /// The box `aabb` as a part, unturned.
65 #[inline]
66 #[must_use]
67 pub fn from_aabb(aabb: &Aabb) -> Self {
68 Self {
69 centre: aabb.centre(),
70 rotation: DQuat::IDENTITY,
71 half_extents: aabb.extents() * 0.5,
72 }
73 }
74
75 /// Its volume, in cubic metres: zero for a flat part.
76 #[inline]
77 #[must_use]
78 pub fn volume(&self) -> f64 {
79 let h = self.half_extents;
80 8.0 * h.x * h.y * h.z
81 }
82
83 /// This part with its shape `offset` from a body at `transform`: the
84 /// offset and the part's centre and faces all turned by the body. The
85 /// contact pipeline ([`ContactShape::compound_part`]) and the query world
86 /// both place a part by it.
87 #[must_use]
88 pub(crate) fn placed(&self, offset: DVec3, transform: &Transform) -> BoxCollider {
89 BoxCollider::new(
90 transform.position + transform.rotation * (offset + self.centre),
91 self.half_extents,
92 )
93 .with_rotation(transform.rotation * self.rotation)
94 }
95
96 /// Its mass properties as a solid of `density`: [`MassProperties::cuboid`]
97 /// turned into the shape's frame, `R I Rᵀ`.
98 fn mass_properties(&self, density: f64) -> MassProperties {
99 let mass = density * self.volume();
100 let own = MassProperties::cuboid(mass, self.half_extents, self.centre);
101 let i = own.inertia;
102 MassProperties {
103 inertia: turned_inertia(
104 DMat3::from_quat(self.rotation),
105 DVec3::new(i.x_axis.x, i.y_axis.y, i.z_axis.z),
106 ),
107 ..own
108 }
109 }
110}
111
112/// `R diag(d) Rᵀ`, with each entry below the diagonal copied from the one
113/// above it, so the tensor is symmetric to the bit: each off-diagonal entry
114/// summed in two orders would round two ways, and
115/// [`RigidBody::with_inertia`] refuses a tensor that is not symmetric.
116fn turned_inertia(r: DMat3, d: DVec3) -> DMat3 {
117 let row = |i: usize| DVec3::new(r.col(0)[i], r.col(1)[i], r.col(2)[i]);
118 let rows = [row(0), row(1), row(2)];
119 let mut m = [[0.0; 3]; 3];
120 for i in 0..3 {
121 for j in i..3 {
122 let value = (rows[i] * d).dot(rows[j]);
123 m[i][j] = value;
124 m[j][i] = value;
125 }
126 }
127 DMat3::from_cols_array_2d(&m)
128}
129
130/// Boxes fixed in one rigid body's frame, validated once: the collision shape
131/// [`ColliderComponent::Compound`] carries.
132///
133/// The parts are shared behind an [`Arc`], so cloning a shape — which
134/// [`crate::PhysicsSystem::set_collider`] does to keep its component — copies
135/// a pointer. Every part is finite, has no negative half-extent and a unit
136/// rotation; there is at least one part, at most [`CompoundShape::MAX_PARTS`],
137/// and some volume among them.
138#[derive(Debug, Clone, PartialEq)]
139pub struct CompoundShape {
140 parts: Arc<[CompoundPart]>,
141}
142
143/// A dynamic body built from a [`CompoundShape`] by
144/// [`CompoundShape::dynamic_body`]: what [`crate::PhysicsSystem::set_body`] and
145/// [`crate::PhysicsSystem::set_collider`] take, and where the body's origin
146/// sits in the shape's frame.
147#[derive(Debug, Clone, PartialEq)]
148pub struct CompoundBody {
149 /// The body: the parts' mass, and their inertia about their centre of mass.
150 pub body: RigidBody,
151 /// The collider, offset so the centre of mass is the body's origin.
152 pub collider: ColliderComponent,
153 /// The centre of mass, in the shape's frame. A game whose own origin is
154 /// the shape's places the body at `origin + rotation * centre_of_mass`,
155 /// and reads its origin back as `position - rotation * centre_of_mass`.
156 pub centre_of_mass: DVec3,
157}
158
159impl CompoundShape {
160 /// The most parts a shape may have.
161 ///
162 /// Each part is a broadphase proxy and each touching pair of parts a
163 /// manifold of up to [`crate::contact::manifold::MAX_POINTS`] points, so
164 /// this is what bounds the proxies a compound body costs and, with the
165 /// other body's parts, the points a pair of bodies can put in the solver.
166 /// It leaves room above what an item boxed one part per mesh primitive
167 /// has: the model of EW's break-action shotgun has thirteen primitives.
168 pub const MAX_PARTS: usize = 32;
169
170 /// A density for a body whose mass nobody authored: water's, in kg/m³.
171 /// It sets a scale, not a measurement: boxes overstate a model's volume
172 /// by their empty corners and by their overlaps, so a game that knows an
173 /// item's real mass weighs it with [`MassProperties::of_collider`], which
174 /// shares that mass among the parts. The centre of mass and the inertia's
175 /// shape, which are what make it tumble, are the same either way.
176 pub const DEFAULT_DENSITY: f64 = 1000.0;
177
178 /// A shape of `parts`, each in the shape's frame. Part indices in a
179 /// [`crate::ContactReport`] are indices into `parts`.
180 ///
181 /// A rotation within glam's unit tolerance is kept normalised.
182 ///
183 /// # Errors
184 ///
185 /// Naming the first offending part where there is one:
186 /// [`CompoundError::NoParts`], [`CompoundError::TooManyParts`],
187 /// [`CompoundError::NonFinitePart`] for a `NaN` or infinity anywhere in a
188 /// part, [`CompoundError::InvertedPart`] for a negative half-extent,
189 /// [`CompoundError::NonUnitRotation`], [`CompoundError::NoVolume`] when
190 /// every part is flat, which leaves nothing for a density to weigh, and
191 /// [`CompoundError::UnweighableMass`] when the parts weighed at unit
192 /// density give an inertia tensor [`RigidBody::with_inertia`] would
193 /// refuse: one overflowed or underflowed out of an `f64`'s range.
194 pub fn new(parts: impl Into<Arc<[CompoundPart]>>) -> Result<Self, CompoundError> {
195 let parts: Arc<[CompoundPart]> = parts.into();
196 if parts.is_empty() {
197 return Err(CompoundError::NoParts);
198 }
199 if parts.len() > Self::MAX_PARTS {
200 return Err(CompoundError::TooManyParts { count: parts.len() });
201 }
202 for (index, part) in parts.iter().enumerate() {
203 if !part.centre.is_finite()
204 || !part.half_extents.is_finite()
205 || !part.rotation.is_finite()
206 {
207 return Err(CompoundError::NonFinitePart { index });
208 }
209 if part.half_extents.min_element() < 0.0 {
210 return Err(CompoundError::InvertedPart { index });
211 }
212 if !part.rotation.is_normalized() {
213 return Err(CompoundError::NonUnitRotation { index });
214 }
215 }
216 if parts.iter().all(|part| part.volume() == 0.0) {
217 return Err(CompoundError::NoVolume);
218 }
219 // A flat part's volume is `inf * 0` once its other extents overflow,
220 // and `combine` refuses the `NaN` mass that would sum to.
221 if parts.iter().any(|part| !part.volume().is_finite()) {
222 return Err(CompoundError::UnweighableMass);
223 }
224 let parts = parts
225 .iter()
226 .map(|part| CompoundPart {
227 rotation: part.rotation.normalize(),
228 ..*part
229 })
230 .collect();
231 let shape = Self { parts };
232 // Checked on the tensor alone: parts whose centre of mass is out of
233 // range reach it through the parallel-axis shift.
234 if !is_positive_definite(shape.mass_properties(1.0).inertia) {
235 return Err(CompoundError::UnweighableMass);
236 }
237 Ok(shape)
238 }
239
240 /// A shape of axis-aligned boxes in the body's frame — what
241 /// [`AabbCompound`] takes, and what EW's `ItemMotion` keeps.
242 ///
243 /// # Errors
244 ///
245 /// [`AabbCompound::new`]'s refusals of a part, then
246 /// [`new`](Self::new)'s of the whole.
247 pub fn from_aabbs(parts: &[Aabb]) -> Result<Self, CompoundError> {
248 let parts = AabbCompound::new(parts)?.parts();
249 Self::new(
250 parts
251 .iter()
252 .map(CompoundPart::from_aabb)
253 .collect::<Vec<_>>(),
254 )
255 }
256
257 /// The parts, in the order given.
258 #[inline]
259 #[must_use]
260 pub fn parts(&self) -> &[CompoundPart] {
261 &self.parts
262 }
263
264 /// The parts' volumes summed, overlaps counted once for each part they
265 /// are in.
266 #[must_use]
267 pub fn volume(&self) -> f64 {
268 self.parts.iter().map(CompoundPart::volume).sum()
269 }
270
271 /// The shape's mass properties as a solid of `density`, in its own frame:
272 /// each part weighed alone and the parts summed — see the module docs for
273 /// why an overlap counts twice.
274 ///
275 /// # Panics
276 ///
277 /// Panics if `density` is not positive and finite.
278 #[must_use]
279 pub fn mass_properties(&self, density: f64) -> MassProperties {
280 assert!(
281 density.is_finite() && density > 0.0,
282 "a density is positive and finite: {density}"
283 );
284 let parts: Vec<MassProperties> = self
285 .parts
286 .iter()
287 .map(|part| part.mass_properties(density))
288 .collect();
289 MassProperties::combine(&parts)
290 }
291
292 /// A dynamic body of `density` with this shape: its mass and inertia from
293 /// [`mass_properties`](Self::mass_properties), and a collider offset by
294 /// the centre of mass so the body's origin is that centre, as
295 /// [`RigidBody`] requires.
296 ///
297 /// # Panics
298 ///
299 /// Panics if `density` is not positive and finite, or so large that the
300 /// inertia it weighs leaves an `f64`'s range.
301 #[must_use]
302 pub fn dynamic_body(&self, density: f64) -> CompoundBody {
303 let props = self.mass_properties(density);
304 CompoundBody {
305 body: RigidBody::new_dynamic(props.mass).with_inertia(props.inertia),
306 collider: ColliderComponent::Compound {
307 offset: -props.centre_of_mass,
308 shape: self.clone(),
309 is_trigger: false,
310 },
311 centre_of_mass: props.centre_of_mass,
312 }
313 }
314
315 /// The world bounds of every part, with the shape `offset` from a body at
316 /// `transform`, as [`ColliderComponent::Compound`] places it.
317 #[must_use]
318 pub fn world_bounds(&self, offset: DVec3, transform: &Transform) -> Aabb {
319 self.parts.iter().fold(Aabb::EMPTY, |bounds, part| {
320 let placed = ContactShape::compound_part(part, offset, transform);
321 bounds.union(placed.aabb().expect("a box is bounded"))
322 })
323 }
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329 use core::f64::consts::FRAC_1_SQRT_2;
330
331 fn assert_close(got: DMat3, want: DMat3, what: &str) {
332 let error = (got - want)
333 .to_cols_array()
334 .iter()
335 .fold(0.0f64, |worst, e| worst.max(e.abs()));
336 assert!(error < 1e-12, "{what}: {got:?}, want {want:?}");
337 }
338
339 /// **An L of two unit cubes, by hand.** Cube 0 spans `[0,1]³` and cube 1
340 /// `[1,2]×[0,1]×[0,1]`, at density 1: each weighs 1 kg with `⅙` about
341 /// every axis through its own centre. The centre of mass is `(1, ½, ½)`,
342 /// each cube's centre half a metre from it along `x`, so the parallel-axis
343 /// term adds `2 · 1 · ½² = ½` about `y` and `z` and nothing about `x`:
344 /// `I = diag(⅓, ⅚, ⅚)`, with no products of inertia since both centres
345 /// lie on one line parallel to `x`.
346 #[test]
347 fn two_cubes_side_by_side_weigh_and_turn_as_computed_by_hand() {
348 let shape = CompoundShape::from_aabbs(&[
349 Aabb::new(DVec3::ZERO, DVec3::ONE),
350 Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
351 ])
352 .unwrap();
353 let props = shape.mass_properties(1.0);
354 assert_eq!(props.mass, 2.0);
355 assert_eq!(props.centre_of_mass, DVec3::new(1.0, 0.5, 0.5));
356 assert_close(
357 props.inertia,
358 DMat3::from_diagonal(DVec3::new(1.0 / 3.0, 5.0 / 6.0, 5.0 / 6.0)),
359 "two cubes",
360 );
361 }
362
363 /// **A given mass is shared among the parts**: the two cubes above at
364 /// 6 kg are three times the density-1 pair, `diag(1, 5/2, 5/2)`, about the
365 /// same centre moved by the collider's offset.
366 #[test]
367 fn a_given_mass_is_shared_among_the_parts() {
368 let shape = CompoundShape::from_aabbs(&[
369 Aabb::new(DVec3::ZERO, DVec3::ONE),
370 Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
371 ])
372 .unwrap();
373 let collider = ColliderComponent::Compound {
374 offset: DVec3::new(0.0, -1.0, 0.0),
375 shape,
376 is_trigger: false,
377 };
378 let props = MassProperties::of_collider(&collider, 6.0);
379 assert_eq!(props.mass, 6.0);
380 assert_eq!(props.centre_of_mass, DVec3::new(1.0, -0.5, 0.5));
381 assert_close(
382 props.inertia,
383 DMat3::from_diagonal(DVec3::new(1.0, 2.5, 2.5)),
384 "two cubes at 6 kg",
385 );
386 }
387
388 /// **An L-shaped compound, by hand, products of inertia and all.** A
389 /// 2 × 1 × 1 bar along `x` over `[0,2]×[0,1]×[0,1]` (2 kg at density 1)
390 /// and a 1 × 1 × 1 cube standing on its left end at `[0,1]×[1,2]×[0,1]`
391 /// (1 kg). Centre of mass: `(2·(1, ½, ½) + (½, 3/2, ½)) / 3 = (5/6, 5/6, ½)`.
392 ///
393 /// Bar, about its own centre: `2 (1 + 1) / 12 = ⅓` about `x`,
394 /// `2 (4 + 1) / 12 = ⅚` about `y` and `z`. Its offset from the centre of
395 /// mass is `d = (⅙, −⅓, 0)`: `2 (|d|² − d dᵀ)` adds `2·⅑ = 2/9` about `x`,
396 /// `2/36` about `y`, `2·5/36` about `z`, and `−2·(⅙)(−⅓) = +⅑` as the `xy`
397 /// product. Cube: `⅙` each way; offset `(−⅓, ⅔, 0)` adds `4/9` about `x`,
398 /// `1/9` about `y`, `5/9` about `z`, and `−(−⅓)(⅔) = +2/9` as `xy`.
399 ///
400 /// Summed: `I_xx = ⅓ + 2/9 + ⅙ + 4/9 = 7/6`, `I_yy = ⅚ + 1/18 + ⅙ + ⅑ =
401 /// 7/6`, `I_zz = ⅚ + 5/18 + ⅙ + 5/9 = 11/6`, `I_xy = ⅓`.
402 #[test]
403 fn an_l_shaped_compound_has_the_hand_computed_tensor() {
404 let shape = CompoundShape::from_aabbs(&[
405 Aabb::new(DVec3::ZERO, DVec3::new(2.0, 1.0, 1.0)),
406 Aabb::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(1.0, 2.0, 1.0)),
407 ])
408 .unwrap();
409 let props = shape.mass_properties(1.0);
410 assert_eq!(props.mass, 3.0);
411 assert!(
412 (props.centre_of_mass - DVec3::new(5.0 / 6.0, 5.0 / 6.0, 0.5)).length() < 1e-15,
413 "{:?}",
414 props.centre_of_mass
415 );
416 let third = 1.0 / 3.0;
417 assert_close(
418 props.inertia,
419 DMat3::from_cols(
420 DVec3::new(7.0 / 6.0, third, 0.0),
421 DVec3::new(third, 7.0 / 6.0, 0.0),
422 DVec3::new(0.0, 0.0, 11.0 / 6.0),
423 ),
424 "L",
425 );
426 }
427
428 /// **Two parts overlapping count the overlap twice**, the documented
429 /// choice: a cube listed twice weighs two cubes, about the same centre.
430 #[test]
431 fn an_overlap_is_counted_once_for_each_part_it_is_in() {
432 let cube = Aabb::new(DVec3::ZERO, DVec3::ONE);
433 let props = CompoundShape::from_aabbs(&[cube, cube])
434 .unwrap()
435 .mass_properties(1.0);
436 assert_eq!(props.mass, 2.0);
437 assert_close(
438 props.inertia,
439 DMat3::from_diagonal(DVec3::splat(2.0 / 6.0)),
440 "doubled cube",
441 );
442 }
443
444 /// **A turned part turns its tensor.** A 12 kg box 1 × 2 × 3 has
445 /// `diag(13, 10, 5)` (see `mass::tests`); turned a quarter about `z`, its
446 /// long `y` side lies along `x`, so `x` and `y` swap: `diag(10, 13, 5)`,
447 /// and the tensor stays symmetric to the bit.
448 #[test]
449 fn a_turned_part_swaps_its_moments() {
450 let quarter = DQuat::from_xyzw(0.0, 0.0, FRAC_1_SQRT_2, FRAC_1_SQRT_2);
451 let part = CompoundPart::new(DVec3::ZERO, quarter, DVec3::new(0.5, 1.0, 1.5));
452 let shape = CompoundShape::new(vec![part]).unwrap();
453 let props = shape.mass_properties(2.0);
454 assert_eq!(props.mass, 12.0);
455 assert_close(
456 props.inertia,
457 DMat3::from_diagonal(DVec3::new(10.0, 13.0, 5.0)),
458 "turned box",
459 );
460 let m = props.inertia;
461 assert_eq!(m.x_axis.y, m.y_axis.x);
462 assert_eq!(m.x_axis.z, m.z_axis.x);
463 assert_eq!(m.y_axis.z, m.z_axis.y);
464
465 // Turned about a skew axis the products appear, and the tensor is
466 // still symmetric to the bit, so a body accepts it.
467 let skew = crate::rotation_from_scaled_axis(DVec3::new(0.3, 0.7, -0.2));
468 let turned = CompoundShape::new(vec![CompoundPart::new(
469 DVec3::ZERO,
470 skew,
471 DVec3::new(0.5, 1.0, 1.5),
472 )])
473 .unwrap()
474 .dynamic_body(2.0);
475 assert!(turned.body.has_rotational_inertia());
476 }
477
478 /// The body a shape builds is centred on the parts' centre of mass: its
479 /// collider is offset by that much back, so the parts sit where they were
480 /// relative to the shape's own origin.
481 #[test]
482 fn a_dynamic_body_is_offset_to_its_centre_of_mass() {
483 let shape = CompoundShape::from_aabbs(&[
484 Aabb::new(DVec3::ZERO, DVec3::ONE),
485 Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
486 ])
487 .unwrap();
488 let built = shape.dynamic_body(500.0);
489 assert_eq!(built.body.mass, 1000.0);
490 assert_eq!(built.centre_of_mass, DVec3::new(1.0, 0.5, 0.5));
491 let ColliderComponent::Compound { offset, .. } = built.collider else {
492 panic!("{:?}", built.collider);
493 };
494 assert_eq!(offset, -built.centre_of_mass);
495 let bounds = shape.world_bounds(offset, &Transform::from_position(built.centre_of_mass));
496 assert_eq!(bounds, Aabb::new(DVec3::ZERO, DVec3::new(2.0, 1.0, 1.0)));
497 }
498
499 #[test]
500 fn a_shape_refuses_what_cannot_be_a_body() {
501 let unit = CompoundPart::from_aabb(&Aabb::new(DVec3::ZERO, DVec3::ONE));
502 let flat = CompoundPart::from_aabb(&Aabb::new(DVec3::ZERO, DVec3::new(1.0, 0.0, 1.0)));
503 assert_eq!(CompoundShape::new(Vec::new()), Err(CompoundError::NoParts));
504 assert_eq!(
505 CompoundShape::new(vec![unit; CompoundShape::MAX_PARTS + 1]),
506 Err(CompoundError::TooManyParts {
507 count: CompoundShape::MAX_PARTS + 1
508 })
509 );
510 assert!(CompoundShape::new(vec![unit; CompoundShape::MAX_PARTS]).is_ok());
511 assert_eq!(
512 CompoundShape::new(vec![
513 unit,
514 CompoundPart {
515 centre: DVec3::new(0.0, f64::NAN, 0.0),
516 ..unit
517 }
518 ]),
519 Err(CompoundError::NonFinitePart { index: 1 })
520 );
521 assert_eq!(
522 CompoundShape::new(vec![CompoundPart {
523 half_extents: DVec3::new(1.0, -0.5, 1.0),
524 ..unit
525 }]),
526 Err(CompoundError::InvertedPart { index: 0 })
527 );
528 assert_eq!(
529 CompoundShape::new(vec![
530 unit,
531 CompoundPart {
532 rotation: DQuat::from_xyzw(0.0, 0.0, 0.0, 2.0),
533 ..unit
534 }
535 ]),
536 Err(CompoundError::NonUnitRotation { index: 1 })
537 );
538 assert_eq!(
539 CompoundShape::new(vec![flat, flat]),
540 Err(CompoundError::NoVolume)
541 );
542 assert!(
543 CompoundShape::new(vec![flat, unit]).is_ok(),
544 "one flat part is fine"
545 );
546 assert_eq!(
547 CompoundShape::from_aabbs(&[Aabb::new(DVec3::ONE, DVec3::ZERO)]),
548 Err(CompoundError::InvertedPart { index: 0 }),
549 "AabbCompound's own refusals come first"
550 );
551 }
552
553 /// **Bounds no body can weigh are refused, not left for the solver.** EW
554 /// loaded a fuzzed save whose item reached to `1e300` m: the parts were
555 /// finite, the inertia was not, and `with_inertia` panicked on the `NaN`.
556 #[test]
557 fn parts_whose_mass_leaves_the_f64_range_are_refused() {
558 let unit = CompoundPart::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::splat(0.5));
559 assert_eq!(
560 CompoundShape::from_aabbs(&[Aabb::new(DVec3::ZERO, DVec3::new(1e300, 1.0, 1.0))]),
561 Err(CompoundError::UnweighableMass),
562 "a volume that overflows"
563 );
564 assert_eq!(
565 CompoundShape::new(vec![
566 unit,
567 CompoundPart::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(1e70, 1e70, 1e70)),
568 ]),
569 Err(CompoundError::UnweighableMass),
570 "a finite volume whose second moment overflows"
571 );
572 assert_eq!(
573 CompoundShape::new(vec![
574 unit,
575 CompoundPart::new(DVec3::ZERO, DQuat::IDENTITY, DVec3::new(1e300, 1e300, 0.0)),
576 ]),
577 Err(CompoundError::UnweighableMass),
578 "a flat part whose volume is inf * 0"
579 );
580 assert_eq!(
581 CompoundShape::new(vec![CompoundPart::new(
582 DVec3::ZERO,
583 DQuat::IDENTITY,
584 DVec3::splat(1e-30),
585 )]),
586 Err(CompoundError::UnweighableMass),
587 "a tensor whose determinant underflows to zero"
588 );
589 assert_eq!(
590 CompoundShape::new(vec![
591 CompoundPart::new(DVec3::splat(-1e200), DQuat::IDENTITY, DVec3::splat(0.5)),
592 CompoundPart::new(DVec3::splat(1e200), DQuat::IDENTITY, DVec3::splat(0.5)),
593 ]),
594 Err(CompoundError::UnweighableMass),
595 "unit parts whose parallel-axis shift overflows"
596 );
597 let big = CompoundShape::new(vec![CompoundPart::new(
598 DVec3::ZERO,
599 DQuat::IDENTITY,
600 DVec3::splat(1e4),
601 )])
602 .expect("a twenty-kilometre box is weighable");
603 let _ = big.dynamic_body(CompoundShape::DEFAULT_DENSITY);
604 }
605}