ferravex_physics/
mass.rs

1//! Body-space symmetric inertia tensors and primitive/compound mass properties.
2use crate::{
3    PhysicsError,
4    body::{Collider, Shape},
5};
6use ferravex_math::{Quat, Vec3};
7
8/// Why checked mass construction failed.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum MassPropertyIssue {
11    /// A dynamic body needs at least one collider.
12    EmptyCompound,
13    /// The compound exceeds [`crate::MAX_CHILDREN`].
14    TooManyChildren,
15    /// The collider's material or local pose is invalid for this dimension.
16    InvalidCollider,
17    /// Density must be finite and in `0..=1e6`.
18    InvalidDensity,
19    /// A shape coordinate or dimension is not finite.
20    NonFiniteShape,
21    /// A radius or half extent is not strictly positive.
22    DegenerateShape,
23    /// The shape cannot be used in the requested dimension.
24    UnsupportedShape,
25    /// All children have zero density.
26    ZeroMass,
27    /// Positive density and dimensions produced zero mass in `f32` arithmetic.
28    MassUnderflow,
29    /// A primitive or accumulated mass is not finite.
30    MassOverflow,
31    /// The reciprocal of the total mass is not finite.
32    InverseMassOverflow,
33    /// A primitive center or weighted center calculation is not finite.
34    CenterOverflow,
35    /// A primitive, transformed, or accumulated inertia is not finite.
36    InertiaOverflow,
37    /// Active inertia is nonpositive or numerically singular.
38    DegenerateInertia,
39    /// Inverting inertia produced a nonfinite or nonpositive active diagonal.
40    InverseInertiaOverflow,
41}
42
43/// A mass-construction failure, with the zero-based input child when known.
44///
45/// `child == None` identifies a compound-wide failure, such as zero total mass
46/// or a singular combined inertia. This error also converts to the existing
47/// [`PhysicsError`] categories used by world insertion and mass refresh.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct MassPropertyError {
50    /// Zero-based input child, or `None` for a failure of the combined result.
51    pub child: Option<usize>,
52    /// The failed validation or calculation stage.
53    pub issue: MassPropertyIssue,
54}
55
56impl From<MassPropertyIssue> for MassPropertyError {
57    fn from(issue: MassPropertyIssue) -> Self {
58        Self { child: None, issue }
59    }
60}
61
62impl From<MassPropertyError> for PhysicsError {
63    fn from(error: MassPropertyError) -> Self {
64        use MassPropertyIssue::*;
65        match error.issue {
66            TooManyChildren => Self::ChildCapacity,
67            InvalidCollider | InvalidDensity | NonFiniteShape | DegenerateShape
68            | UnsupportedShape => Self::InvalidCollider,
69            _ => Self::InvalidMass,
70        }
71    }
72}
73
74impl std::fmt::Display for MassPropertyError {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        use MassPropertyIssue::*;
77        let message = match self.issue {
78            EmptyCompound => "compound has no colliders",
79            TooManyChildren => "compound exceeds the collider child limit",
80            InvalidCollider => "collider material or local pose is invalid",
81            InvalidDensity => "density must be finite and in 0..=1e6",
82            NonFiniteShape => "shape dimensions and coordinates must be finite",
83            DegenerateShape => "shape radii and half extents must be positive",
84            UnsupportedShape => "shape is incompatible with the requested dimension",
85            ZeroMass => "compound has no positive-density children",
86            MassUnderflow => "positive-density shape mass underflowed to zero",
87            MassOverflow => "mass calculation overflowed",
88            InverseMassOverflow => "reciprocal mass overflowed",
89            CenterOverflow => "center-of-mass calculation overflowed",
90            InertiaOverflow => "inertia calculation overflowed",
91            DegenerateInertia => "inertia is nonpositive or numerically singular",
92            InverseInertiaOverflow => "inverse inertia is not finite and positive",
93        };
94        if let Some(child) = self.child {
95            write!(f, "mass properties, child {child}: {message}")
96        } else {
97            write!(f, "mass properties: {message}")
98        }
99    }
100}
101
102impl std::error::Error for MassPropertyError {}
103
104/// Checked body-local mass and inertia, computed using the solver's formulas.
105///
106/// The inertia is about the combined center of mass. Inspect a collider without
107/// inserting it into a world:
108///
109/// ```
110/// # #[cfg(feature = "dim3")] {
111/// use ferravex_physics::{Collider, d3::ColliderBuilder};
112/// let collider: Collider = ColliderBuilder::cuboid(1., 2., 3.).density(2.).into();
113/// let properties = collider.try_mass_properties(false).unwrap();
114/// assert_eq!(properties.mass(), 96.);
115/// assert_eq!(properties.local_center_of_mass(), ferravex_math::Vec3::ZERO);
116/// let (diagonal, off_diagonal) = properties.inertia();
117/// assert_eq!(diagonal, ferravex_math::Vec3::new(416., 320., 160.));
118/// assert_eq!(off_diagonal, ferravex_math::Vec3::ZERO);
119/// let (inverse, _) = properties.inverse_inertia();
120/// assert!((inverse.x * diagonal.x - 1.).abs() < 1e-6);
121/// # }
122/// ```
123#[derive(Clone, Copy, Debug)]
124pub struct MassProperties {
125    properties: Mass,
126    inertia: Tensor,
127}
128
129impl MassProperties {
130    /// Compute a compound without allocating or mutating its colliders.
131    ///
132    /// Uses at most two passes over the same ordered inputs; clones of the
133    /// iterator must yield the same colliders. At most [`crate::MAX_CHILDREN`]
134    /// children are accepted. Zero-density children contribute no mass; sensors
135    /// contribute normally, matching world insertion. `planar` selects area
136    /// density and Z-axis rotation instead of volume density and 3D rotation.
137    /// The 3D solver's normalized determinant cutoff (`1e-10`) is retained.
138    ///
139    /// Invalid geometry, nonfinite intermediate results, underflowed mass and
140    /// unrepresentable reciprocals return a diagnostic. No input is clamped.
141    pub fn try_from_colliders<'a>(
142        children: impl Iterator<Item = &'a Collider> + Clone,
143        planar: bool,
144    ) -> Result<Self, MassPropertyError> {
145        checked_compound(children, planar)
146    }
147
148    /// The finite, positive total mass.
149    pub fn mass(&self) -> f32 {
150        self.properties.mass
151    }
152
153    /// The center of mass relative to the authored body origin.
154    pub fn local_center_of_mass(&self) -> Vec3 {
155        self.properties.center
156    }
157
158    /// Symmetric inertia as `(xx/yy/zz, xy/xz/yz)` about the center of mass.
159    /// Only `zz` is active for planar bodies.
160    pub fn inertia(&self) -> (Vec3, Vec3) {
161        (self.inertia.diagonal, self.inertia.off)
162    }
163
164    /// Inverse inertia as `(xx/yy/zz, xy/xz/yz)` in body-local coordinates.
165    /// Planar bodies have only `zz`; all other inverse entries are zero.
166    pub fn inverse_inertia(&self) -> (Vec3, Vec3) {
167        (
168            self.properties.inverse.diagonal,
169            self.properties.inverse.off,
170        )
171    }
172}
173
174impl Collider {
175    /// Check this collider's mass and inertia without inserting it into a world.
176    ///
177    /// `planar` must match the intended world's dimension. A zero-density
178    /// collider is valid as part of a compound but cannot supply mass by itself.
179    ///
180    /// ```
181    /// # #[cfg(feature = "dim2")] {
182    /// use ferravex_physics::{Collider, d2::ColliderBuilder};
183    /// let collider: Collider = ColliderBuilder::ball(1.).density(0.).into();
184    /// let error = collider.try_mass_properties(true).unwrap_err();
185    /// assert_eq!(error.child, None);
186    /// assert!(error.to_string().contains("positive-density"));
187    /// # }
188    /// ```
189    pub fn try_mass_properties(&self, planar: bool) -> Result<MassProperties, MassPropertyError> {
190        MassProperties::try_from_colliders(std::iter::once(self), planar)
191    }
192}
193
194#[derive(Clone, Copy, Debug, Default)]
195pub(crate) struct Tensor {
196    pub diagonal: Vec3,
197    pub off: Vec3,
198}
199impl Tensor {
200    pub const ZERO: Self = Self {
201        diagonal: Vec3::ZERO,
202        off: Vec3::ZERO,
203    };
204    pub fn diagonal(v: Vec3) -> Self {
205        Self {
206            diagonal: v,
207            off: Vec3::ZERO,
208        }
209    }
210    pub fn outer(v: Vec3) -> Self {
211        Self {
212            diagonal: v * v,
213            off: Vec3::new(v.x * v.y, v.x * v.z, v.y * v.z),
214        }
215    }
216    pub fn apply(self, v: Vec3) -> Vec3 {
217        let d = self.diagonal * v;
218        if self.off == Vec3::ZERO {
219            return d;
220        }
221        d + Vec3::new(
222            self.off.x * v.y + self.off.y * v.z,
223            self.off.x * v.x + self.off.z * v.z,
224            self.off.y * v.x + self.off.z * v.y,
225        )
226    }
227    pub fn rotated(self, q: Quat) -> Self {
228        let a = q * self.apply(q.conjugate() * Vec3::X);
229        let b = q * self.apply(q.conjugate() * Vec3::Y);
230        let c = q * self.apply(q.conjugate() * Vec3::Z);
231        Self {
232            diagonal: Vec3::new(a.x, b.y, c.z),
233            off: Vec3::new((a.y + b.x) * 0.5, (a.z + c.x) * 0.5, (b.z + c.y) * 0.5),
234        }
235    }
236    pub fn inverse(self, planar: bool) -> Result<Self, MassPropertyIssue> {
237        if !self.diagonal.is_finite() || !self.off.is_finite() {
238            return Err(MassPropertyIssue::InertiaOverflow);
239        }
240        if planar {
241            if self.diagonal.z <= 0. {
242                return Err(MassPropertyIssue::DegenerateInertia);
243            }
244            let z = 1. / self.diagonal.z;
245            return if z.is_finite() && z > 0. {
246                Ok(Self::diagonal(Vec3::Z * z))
247            } else {
248                Err(MassPropertyIssue::InverseInertiaOverflow)
249            };
250        }
251        let scale = self
252            .diagonal
253            .abs()
254            .max_element()
255            .max(self.off.abs().max_element());
256        if !scale.is_finite() || scale <= 0. {
257            return Err(MassPropertyIssue::DegenerateInertia);
258        }
259        let m = if (1. / scale).is_finite() {
260            self * (1. / scale)
261        } else {
262            Self {
263                diagonal: self.diagonal / scale,
264                off: self.off / scale,
265            }
266        };
267        let d = m.diagonal;
268        let o = m.off;
269        // A positive determinant alone also admits two negative eigenvalues.
270        if d.x <= 0. || d.y <= 0. || d.z <= 0. || d.x * d.y - o.x * o.x <= 0. {
271            return Err(MassPropertyIssue::DegenerateInertia);
272        }
273        let a = Vec3::new(d.x, o.x, o.y);
274        let b = Vec3::new(o.x, d.y, o.z);
275        let c = Vec3::new(o.y, o.z, d.z);
276        let determinant = a.dot(b.cross(c));
277        if !determinant.is_finite() || determinant <= 1e-10 {
278            return Err(MassPropertyIssue::DegenerateInertia);
279        }
280        let denominator = determinant * scale;
281        let divide = |v: Vec3| {
282            if denominator.is_finite() && denominator > 0. {
283                v / denominator
284            } else {
285                (v / determinant) / scale
286            }
287        };
288        let r0 = divide(b.cross(c));
289        let r1 = divide(c.cross(a));
290        let r2 = divide(a.cross(b));
291        let average = |a: f32, b: f32| {
292            if (a + b).is_finite() {
293                (a + b) * 0.5
294            } else {
295                a * 0.5 + b * 0.5
296            }
297        };
298        let inverse = Self {
299            diagonal: Vec3::new(r0.x, r1.y, r2.z),
300            off: Vec3::new(
301                average(r0.y, r1.x),
302                average(r0.z, r2.x),
303                average(r1.z, r2.y),
304            ),
305        };
306        if !inverse.diagonal.is_finite()
307            || !inverse.off.is_finite()
308            || inverse.diagonal.min_element() <= 0.
309        {
310            return Err(MassPropertyIssue::InverseInertiaOverflow);
311        }
312        Ok(inverse)
313    }
314}
315impl std::ops::Add for Tensor {
316    type Output = Self;
317    fn add(self, b: Self) -> Self {
318        Self {
319            diagonal: self.diagonal + b.diagonal,
320            off: self.off + b.off,
321        }
322    }
323}
324impl std::ops::Sub for Tensor {
325    type Output = Self;
326    fn sub(self, b: Self) -> Self {
327        Self {
328            diagonal: self.diagonal - b.diagonal,
329            off: self.off - b.off,
330        }
331    }
332}
333impl std::ops::Mul<f32> for Tensor {
334    type Output = Self;
335    fn mul(self, s: f32) -> Self {
336        Self {
337            diagonal: self.diagonal * s,
338            off: self.off * s,
339        }
340    }
341}
342#[derive(Clone, Copy, Debug)]
343pub(crate) struct Mass {
344    pub mass: f32,
345    pub center: Vec3,
346    pub inverse: Tensor,
347}
348
349fn validate_shape(shape: Shape, _planar: bool) -> Result<(), MassPropertyIssue> {
350    let positive = |v: f32| {
351        if !v.is_finite() {
352            Err(MassPropertyIssue::NonFiniteShape)
353        } else if v <= 0. {
354            Err(MassPropertyIssue::DegenerateShape)
355        } else {
356            Ok(())
357        }
358    };
359    match shape {
360        Shape::Ball(radius) => positive(radius),
361        Shape::Box(half) => {
362            positive(half.x)?;
363            positive(half.y)?;
364            positive(half.z)
365        }
366        #[cfg(feature = "dim2")]
367        Shape::Capsule { a, b, radius } => {
368            positive(radius)?;
369            if !a.is_finite() || !b.is_finite() {
370                return Err(MassPropertyIssue::NonFiniteShape);
371            }
372            if _planar && (a.z != 0. || b.z != 0.) {
373                return Err(MassPropertyIssue::UnsupportedShape);
374            }
375            Ok(())
376        }
377        #[cfg(feature = "dim3")]
378        Shape::Cylinder {
379            half_height,
380            radius,
381        } => {
382            positive(half_height)?;
383            positive(radius)?;
384            if _planar {
385                Err(MassPropertyIssue::UnsupportedShape)
386            } else {
387                Ok(())
388            }
389        }
390    }
391}
392
393fn primitive(
394    shape: Shape,
395    density: f32,
396    planar: bool,
397) -> Result<(f32, Vec3, Tensor), MassPropertyIssue> {
398    if !density.is_finite() || !(0. ..=1e6).contains(&density) {
399        return Err(MassPropertyIssue::InvalidDensity);
400    }
401    validate_shape(shape, planar)?;
402    // Massless collision geometry must not introduce 0 * infinity into a
403    // compound. Still validate its dimensions before ignoring its contribution.
404    if density == 0. {
405        return Ok((0., Vec3::ZERO, Tensor::ZERO));
406    }
407    let pi = std::f32::consts::PI;
408    let (mass, center, inertia) = match shape {
409        Shape::Ball(r) => {
410            let mass = if planar {
411                pi * r * r * density
412            } else {
413                4. / 3. * pi * r * r * r * density
414            };
415            (
416                mass,
417                Vec3::ZERO,
418                Tensor::diagonal(if planar {
419                    Vec3::Z * (0.5 * mass * r * r)
420                } else {
421                    Vec3::splat(0.4 * mass * r * r)
422                }),
423            )
424        }
425        Shape::Box(h) => {
426            let mass = if planar {
427                4. * h.x * h.y * density
428            } else {
429                8. * h.x * h.y * h.z * density
430            };
431            (
432                mass,
433                Vec3::ZERO,
434                Tensor::diagonal(if planar {
435                    Vec3::Z * (mass * (h.x * h.x + h.y * h.y) / 3.)
436                } else {
437                    Vec3::new(
438                        h.y * h.y + h.z * h.z,
439                        h.x * h.x + h.z * h.z,
440                        h.x * h.x + h.y * h.y,
441                    ) * mass
442                        / 3.
443                }),
444            )
445        }
446        #[cfg(feature = "dim2")]
447        Shape::Capsule { a, b, radius: r } => {
448            let length = a.distance(b);
449            let center = (a + b) * 0.5;
450            if planar {
451                let mr = 2. * r * length * density;
452                let ms = pi * r * r * density;
453                let inertia = mr * (length * length + 4. * r * r) / 12.
454                    + ms * (0.5 * r * r + 0.25 * length * length + 4. * length * r / (3. * pi));
455                (mr + ms, center, Tensor::diagonal(Vec3::Z * inertia))
456            } else {
457                let mc = pi * r * r * length * density;
458                let ms = 4. / 3. * pi * r * r * r * density;
459                let parallel = 0.5 * mc * r * r + 0.4 * ms * r * r;
460                let perpendicular = mc * (3. * r * r + length * length) / 12.
461                    + ms * (0.4 * r * r + length * length / 4. + 3. * length * r / 8.);
462                let axis = (b - a).try_normalize().unwrap_or(Vec3::Y);
463                (
464                    mc + ms,
465                    center,
466                    Tensor::diagonal(Vec3::splat(perpendicular))
467                        + Tensor::outer(axis) * (parallel - perpendicular),
468                )
469            }
470        }
471        #[cfg(feature = "dim3")]
472        Shape::Cylinder {
473            half_height: h,
474            radius: r,
475        } => {
476            if planar {
477                return Err(MassPropertyIssue::UnsupportedShape);
478            }
479            let mass = 2. * pi * r * r * h * density;
480            (
481                mass,
482                Vec3::ZERO,
483                Tensor::diagonal(
484                    Vec3::new(r * r / 4. + h * h / 3., r * r / 2., r * r / 4. + h * h / 3.) * mass,
485                ),
486            )
487        }
488    };
489    if !mass.is_finite() {
490        return Err(MassPropertyIssue::MassOverflow);
491    }
492    if mass <= 0. {
493        return Err(MassPropertyIssue::MassUnderflow);
494    }
495    if !center.is_finite() {
496        return Err(MassPropertyIssue::CenterOverflow);
497    }
498    if !inertia.diagonal.is_finite() || !inertia.off.is_finite() {
499        return Err(MassPropertyIssue::InertiaOverflow);
500    }
501    Ok((mass, center, inertia))
502}
503pub(crate) fn compound<'a>(
504    children: impl Iterator<Item = &'a Collider> + Clone,
505    planar: bool,
506) -> Result<Mass, PhysicsError> {
507    MassProperties::try_from_colliders(children, planar)
508        .map(|p| p.properties)
509        .map_err(PhysicsError::from)
510}
511
512fn checked_compound<'a>(
513    children: impl Iterator<Item = &'a Collider> + Clone,
514    planar: bool,
515) -> Result<MassProperties, MassPropertyError> {
516    let mut mass = 0.;
517    let mut center = Vec3::ZERO;
518    let mut any = false;
519    for (child, c) in children.clone().enumerate() {
520        let error = |issue| MassPropertyError {
521            child: Some(child),
522            issue,
523        };
524        if child >= crate::MAX_CHILDREN {
525            return Err(error(MassPropertyIssue::TooManyChildren));
526        }
527        any = true;
528        let (m, p, _) = primitive(c.shape, c.density, planar).map_err(error)?;
529        if !c.valid(planar) {
530            return Err(error(MassPropertyIssue::InvalidCollider));
531        }
532        if m == 0. {
533            continue;
534        }
535        mass += m;
536        if !mass.is_finite() {
537            return Err(error(MassPropertyIssue::MassOverflow));
538        }
539        center += (c.local_translation + c.local_rotation * p) * m;
540        if !center.is_finite() {
541            return Err(error(MassPropertyIssue::CenterOverflow));
542        }
543    }
544    if !any {
545        return Err(MassPropertyIssue::EmptyCompound.into());
546    }
547    if mass <= 0. {
548        return Err(MassPropertyIssue::ZeroMass.into());
549    }
550    if !(1. / mass).is_finite() {
551        return Err(MassPropertyIssue::InverseMassOverflow.into());
552    }
553    center /= mass;
554    if !center.is_finite() {
555        return Err(MassPropertyIssue::CenterOverflow.into());
556    }
557    let mut inertia = Tensor::ZERO;
558    for (child, c) in children.enumerate() {
559        let error = |issue| MassPropertyError {
560            child: Some(child),
561            issue,
562        };
563        // Bound both passes even for a caller-supplied inconsistent iterator.
564        if child >= crate::MAX_CHILDREN {
565            return Err(error(MassPropertyIssue::TooManyChildren));
566        }
567        let (m, p, i) = primitive(c.shape, c.density, planar).map_err(error)?;
568        if m == 0. {
569            continue;
570        }
571        let delta = c.local_translation + c.local_rotation * p - center;
572        inertia = inertia
573            + i.rotated(c.local_rotation)
574            + (Tensor::diagonal(Vec3::splat(delta.length_squared())) - Tensor::outer(delta)) * m;
575        if !inertia.diagonal.is_finite() || !inertia.off.is_finite() {
576            return Err(error(MassPropertyIssue::InertiaOverflow));
577        }
578    }
579    let inverse = inertia.inverse(planar)?;
580    Ok(MassProperties {
581        properties: Mass {
582            mass,
583            center,
584            inverse,
585        },
586        inertia,
587    })
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    fn close(actual: f32, expected: f32) {
595        assert!(
596            (actual - expected).abs() <= expected.abs().max(1.) * 2e-6,
597            "{actual} != {expected}"
598        );
599    }
600
601    fn check_diagonal(properties: MassProperties, mass: f32, diagonal: Vec3, planar: bool) {
602        close(properties.mass(), mass);
603        assert_eq!(properties.local_center_of_mass(), Vec3::ZERO);
604        assert_eq!(properties.inertia().1, Vec3::ZERO);
605        assert_eq!(properties.inverse_inertia().1, Vec3::ZERO);
606        let actual = properties.inertia().0;
607        let inverse = properties.inverse_inertia().0;
608        for (a, e) in actual.to_array().into_iter().zip(diagonal.to_array()) {
609            close(a, e);
610        }
611        if planar {
612            assert_eq!(inverse.x, 0.);
613            assert_eq!(inverse.y, 0.);
614            close(inverse.z * diagonal.z, 1.);
615        } else {
616            for product in (inverse * diagonal).to_array() {
617                close(product, 1.);
618            }
619        }
620    }
621
622    fn failure(
623        children: &[Collider],
624        planar: bool,
625        child: Option<usize>,
626        issue: MassPropertyIssue,
627    ) {
628        let error = MassProperties::try_from_colliders(children.iter(), planar).unwrap_err();
629        assert_eq!(error, MassPropertyError { child, issue });
630    }
631
632    #[test]
633    fn ball_and_box_match_analytic_mass_and_inertia_in_both_dimensions() {
634        let mut ball = Collider::new(Shape::Ball(2.));
635        ball.density = 3.;
636        let disk_mass = 12. * std::f32::consts::PI;
637        check_diagonal(
638            ball.try_mass_properties(true).unwrap(),
639            disk_mass,
640            Vec3::Z * (disk_mass * 2.),
641            true,
642        );
643        let sphere_mass = 32. * std::f32::consts::PI;
644        check_diagonal(
645            ball.try_mass_properties(false).unwrap(),
646            sphere_mass,
647            Vec3::splat(sphere_mass * 1.6),
648            false,
649        );
650
651        let mut cuboid = Collider::new(Shape::Box(Vec3::new(1., 2., 3.)));
652        cuboid.density = 2.;
653        check_diagonal(
654            cuboid.try_mass_properties(true).unwrap(),
655            16.,
656            Vec3::Z * (80. / 3.),
657            true,
658        );
659        check_diagonal(
660            cuboid.try_mass_properties(false).unwrap(),
661            96.,
662            Vec3::new(416., 320., 160.),
663            false,
664        );
665    }
666
667    #[cfg(feature = "dim3")]
668    #[test]
669    fn cylinder_matches_analytic_axial_and_transverse_moments() {
670        let cylinder = Collider::new(Shape::Cylinder {
671            half_height: 3.,
672            radius: 2.,
673        });
674        let mass = 24. * std::f32::consts::PI;
675        check_diagonal(
676            cylinder.try_mass_properties(false).unwrap(),
677            mass,
678            Vec3::new(4., 2., 4.) * mass,
679            false,
680        );
681        failure(
682            &[cylinder],
683            true,
684            Some(0),
685            MassPropertyIssue::UnsupportedShape,
686        );
687    }
688
689    #[cfg(feature = "dim2")]
690    #[test]
691    fn capsule_matches_stadium_and_solid_capsule_moments() {
692        let capsule = Collider::new(Shape::Capsule {
693            a: -Vec3::X,
694            b: Vec3::X,
695            radius: 1.,
696        });
697        let pi = std::f32::consts::PI;
698        check_diagonal(
699            capsule.try_mass_properties(true).unwrap(),
700            4. + pi,
701            Vec3::Z * (16. / 3. + 1.5 * pi),
702            true,
703        );
704        check_diagonal(
705            capsule.try_mass_properties(false).unwrap(),
706            10. / 3. * pi,
707            Vec3::new(23. / 15., 121. / 30., 121. / 30.) * pi,
708            false,
709        );
710    }
711
712    #[cfg(feature = "dim2")]
713    #[test]
714    fn coincident_capsule_endpoints_are_a_valid_offset_ball() {
715        let mut capsule = Collider::new(Shape::Capsule {
716            a: Vec3::new(3., 4., 0.),
717            b: Vec3::new(3., 4., 0.),
718            radius: 0.5,
719        });
720        capsule.local_rotation = Quat::from_rotation_z(0.5);
721        capsule.local_translation = Vec3::X;
722        let center = capsule.local_translation + capsule.local_rotation * Vec3::new(3., 4., 0.);
723        let ball = Collider::new(Shape::Ball(0.5));
724        for planar in [true, false] {
725            let properties = capsule.try_mass_properties(planar).unwrap();
726            let expected = ball.try_mass_properties(planar).unwrap();
727            assert!(properties.local_center_of_mass().distance(center) < 1e-6);
728            close(properties.mass(), expected.mass());
729            for (a, b) in properties
730                .inertia()
731                .0
732                .to_array()
733                .into_iter()
734                .zip(expected.inertia().0.to_array())
735            {
736                close(a, b);
737            }
738        }
739    }
740
741    #[test]
742    fn compound_matches_weighted_center_and_parallel_axis_theorem() {
743        let mut a = Collider::new(Shape::Ball(1.));
744        a.local_translation = -Vec3::X;
745        let mut b = Collider::new(Shape::Ball(1.));
746        b.local_translation = Vec3::X;
747        b.density = 3.;
748        let children = [a, b];
749        let properties = MassProperties::try_from_colliders(children.iter(), false).unwrap();
750        let mass = 16. / 3. * std::f32::consts::PI;
751        close(properties.mass(), mass);
752        close(properties.local_center_of_mass().x, 0.5);
753        close(properties.inertia().0.x, mass * 0.4);
754        close(properties.inertia().0.y, mass * (0.4 + 0.75));
755        close(properties.inertia().0.z, mass * (0.4 + 0.75));
756        assert_eq!(properties.inertia().1, Vec3::ZERO);
757    }
758
759    #[test]
760    fn rotated_inertia_and_its_inverse_preserve_off_diagonal_response() {
761        let mut collider = Collider::new(Shape::Box(Vec3::new(2., 0.5, 0.25)));
762        collider.local_rotation = Quat::from_rotation_z(0.6);
763        let q = collider.local_rotation;
764        let properties = collider.try_mass_properties(false).unwrap();
765        assert!(properties.inertia().1.x.abs() > 0.1);
766        let moment = Vec3::new(0.3125, 4.0625, 4.25) * properties.mass() / 3.;
767        for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
768            let expected = q * ((q.conjugate() * axis) / moment);
769            let actual = properties.properties.inverse.apply(axis);
770            assert!(actual.distance(expected) < 1e-5);
771            assert!(properties.inertia.apply(actual).distance(axis) < 1e-5);
772        }
773    }
774
775    #[test]
776    fn distinguishes_empty_zero_density_and_child_capacity() {
777        failure(&[], false, None, MassPropertyIssue::EmptyCompound);
778        let mut massless = Collider::new(Shape::Ball(1.));
779        massless.density = 0.;
780        failure(&[massless], false, None, MassPropertyIssue::ZeroMass);
781        let children = vec![Collider::new(Shape::Ball(1.)); crate::MAX_CHILDREN + 1];
782        MassProperties::try_from_colliders(children[..crate::MAX_CHILDREN].iter(), false).unwrap();
783        failure(
784            &children,
785            false,
786            Some(crate::MAX_CHILDREN),
787            MassPropertyIssue::TooManyChildren,
788        );
789    }
790
791    #[test]
792    fn density_errors_report_the_input_child() {
793        for density in [-1., f32::NAN, f32::INFINITY, 1_000_001.] {
794            let mut invalid = Collider::new(Shape::Ball(1.));
795            invalid.density = density;
796            let children = [Collider::new(Shape::Ball(1.)), invalid];
797            failure(&children, false, Some(1), MassPropertyIssue::InvalidDensity);
798            let error = MassProperties::try_from_colliders(children.iter(), false).unwrap_err();
799            assert_eq!(PhysicsError::from(error), PhysicsError::InvalidCollider);
800            assert_eq!(
801                error.to_string(),
802                "mass properties, child 1: density must be finite and in 0..=1e6"
803            );
804        }
805    }
806
807    #[test]
808    fn shape_validation_rejects_nonfinite_and_degenerate_dimensions() {
809        for shape in [
810            Shape::Ball(0.),
811            Shape::Ball(-1.),
812            Shape::Box(Vec3::new(1., 0., 1.)),
813        ] {
814            failure(
815                &[Collider::new(shape)],
816                false,
817                Some(0),
818                MassPropertyIssue::DegenerateShape,
819            );
820        }
821        for shape in [
822            Shape::Ball(f32::NAN),
823            Shape::Ball(f32::INFINITY),
824            Shape::Box(Vec3::splat(f32::INFINITY)),
825        ] {
826            failure(
827                &[Collider::new(shape)],
828                false,
829                Some(0),
830                MassPropertyIssue::NonFiniteShape,
831            );
832        }
833        let mut invalid_pose = Collider::new(Shape::Ball(1.));
834        invalid_pose.local_translation = Vec3::Z;
835        failure(
836            &[invalid_pose],
837            true,
838            Some(0),
839            MassPropertyIssue::InvalidCollider,
840        );
841    }
842
843    #[test]
844    fn mass_and_inertia_overflow_identify_the_child_and_stage() {
845        failure(
846            &[Collider::new(Shape::Ball(1e20))],
847            false,
848            Some(0),
849            MassPropertyIssue::MassOverflow,
850        );
851        failure(
852            &[Collider::new(Shape::Ball(1e9))],
853            false,
854            Some(0),
855            MassPropertyIssue::InertiaOverflow,
856        );
857        let child = Collider::new(Shape::Ball(4e7));
858        child.try_mass_properties(false).unwrap();
859        failure(
860            &[child.clone(), child],
861            false,
862            Some(1),
863            MassPropertyIssue::InertiaOverflow,
864        );
865    }
866
867    #[cfg(feature = "dim2")]
868    #[test]
869    fn capsule_center_and_parallel_axis_overflow_are_diagnosed() {
870        let capsule_at = |x| {
871            Collider::new(Shape::Capsule {
872                a: Vec3::X * x,
873                b: Vec3::X * x,
874                radius: 1.,
875            })
876        };
877        failure(
878            &[capsule_at(f32::MAX)],
879            false,
880            Some(0),
881            MassPropertyIssue::CenterOverflow,
882        );
883        failure(
884            &[capsule_at(1e20), capsule_at(-1e20)],
885            false,
886            Some(0),
887            MassPropertyIssue::InertiaOverflow,
888        );
889    }
890
891    #[test]
892    fn underflow_and_unrepresentable_reciprocals_are_distinct() {
893        failure(
894            &[Collider::new(Shape::Ball(f32::MIN_POSITIVE))],
895            true,
896            Some(0),
897            MassPropertyIssue::MassUnderflow,
898        );
899        let mut tiny_mass = Collider::new(Shape::Ball(1.));
900        tiny_mass.density = f32::from_bits(1);
901        failure(
902            &[tiny_mass],
903            true,
904            None,
905            MassPropertyIssue::InverseMassOverflow,
906        );
907        failure(
908            &[Collider::new(Shape::Ball(1e-12))],
909            true,
910            None,
911            MassPropertyIssue::DegenerateInertia,
912        );
913        failure(
914            &[Collider::new(Shape::Ball(1e-10))],
915            true,
916            None,
917            MassPropertyIssue::InverseInertiaOverflow,
918        );
919    }
920
921    #[test]
922    fn zero_density_children_do_not_contaminate_valid_mass_arithmetic() {
923        let ball = Collider::new(Shape::Ball(1.));
924        let expected = ball.try_mass_properties(false).unwrap();
925        let mut massless = Collider::new(Shape::Ball(f32::MAX));
926        massless.density = 0.;
927        massless.local_translation = Vec3::X * 1e6;
928        let children = [massless.clone(), ball];
929        let properties = MassProperties::try_from_colliders(children.iter(), false).unwrap();
930        assert_eq!(properties.mass(), expected.mass());
931        assert_eq!(
932            properties.local_center_of_mass(),
933            expected.local_center_of_mass()
934        );
935        assert_eq!(properties.inertia(), expected.inertia());
936        assert_eq!(properties.inverse_inertia(), expected.inverse_inertia());
937        massless.shape = Shape::Ball(0.);
938        failure(
939            &[massless],
940            false,
941            Some(0),
942            MassPropertyIssue::DegenerateShape,
943        );
944    }
945
946    #[test]
947    fn tensor_rejects_indefinite_singular_and_nonfinite_inertia() {
948        for diagonal in [
949            Vec3::new(-1., -1., 1.),
950            Vec3::new(0., 1., 1.),
951            Vec3::new(1e-12, 1., 1.),
952        ] {
953            assert_eq!(
954                Tensor::diagonal(diagonal).inverse(false).unwrap_err(),
955                MassPropertyIssue::DegenerateInertia
956            );
957        }
958        let indefinite = Tensor {
959            diagonal: Vec3::ONE,
960            off: Vec3::splat(2.),
961        };
962        assert_eq!(
963            indefinite.inverse(false).unwrap_err(),
964            MassPropertyIssue::DegenerateInertia
965        );
966        let nonfinite = Tensor {
967            diagonal: Vec3::ONE,
968            off: Vec3::X * f32::INFINITY,
969        };
970        for planar in [true, false] {
971            assert_eq!(
972                nonfinite.inverse(planar).unwrap_err(),
973                MassPropertyIssue::InertiaOverflow
974            );
975        }
976    }
977
978    #[test]
979    fn tensor_inversion_handles_extreme_finite_scales() {
980        for scale in [4e-39, 1., f32::MAX] {
981            let inverse = Tensor::diagonal(Vec3::splat(scale)).inverse(false).unwrap();
982            for product in (inverse.diagonal * scale).to_array() {
983                close(product, 1.);
984            }
985            assert_eq!(inverse.off, Vec3::ZERO);
986        }
987        assert_eq!(
988            Tensor::diagonal(Vec3::splat(f32::from_bits(1)))
989                .inverse(false)
990                .unwrap_err(),
991            MassPropertyIssue::InverseInertiaOverflow
992        );
993        // Each inverse off-diagonal is representable even though adding the
994        // two symmetric entries before averaging would overflow.
995        let tensor = Tensor {
996            diagonal: Vec3::splat(2e-38),
997            off: Vec3::new(1.8e-38, 0., 0.),
998        };
999        let inverse = tensor.inverse(false).unwrap();
1000        assert!(inverse.off.x < -2e38);
1001        for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
1002            assert!(tensor.apply(inverse.apply(axis)).distance(axis) < 1e-5);
1003        }
1004    }
1005
1006    #[cfg(feature = "dim2")]
1007    #[test]
1008    fn rejected_mass_construction_leaves_world_unchanged() {
1009        use crate::d2::{ColliderBuilder, PhysicsWorld, RigidBodyBuilder};
1010        let mut world = PhysicsWorld::new([0.; 2]);
1011        assert_eq!(
1012            world.insert_compound(RigidBodyBuilder::dynamic(), [ColliderBuilder::ball(1e-10)]),
1013            Err(PhysicsError::InvalidMass)
1014        );
1015        assert!(world.bodies.is_empty());
1016        assert!(world.colliders.is_empty());
1017    }
1018}