astrodyn_dynamics 0.1.1

Rigid-body dynamics, integrators (RK4, RKF45, GJ, ABM4), mass tree, and body initialization
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! [`MassProperties`] and the typed sibling [`MassPropertiesTyped`] —
//! mass, inertia tensor, and CoM offset for a rigid body.
//!
//! Ports
//! [`models/dynamics/mass/`](https://github.com/nasa/jeod/blob/jeod_v5.4.0/models/dynamics/mass/)
//! from JEOD v5.4.0. Inertia is stored about the body-frame axes
//! through the centre of mass; composing child masses into a parent
//! applies the parallel-axis (Steiner) theorem.

use core::marker::PhantomData;

use astrodyn_quantities::aliases::{InertiaTensor, Position};
use astrodyn_quantities::frame::{BodyFrame, StructuralFrame, Vehicle};
use glam::{DMat3, DVec3};
use uom::si::f64::Mass;
use uom::si::mass::kilogram;

/// Default tolerance for [`MassProperties::validate_consistency`].
///
/// Checks that `I * I^-1` is within this tolerance of the identity matrix.
/// Matches the precision expected from `DMat3::inverse()` for typical
/// spacecraft inertia tensors (principal moments ~1–10000 kg*m^2).
pub const INERTIA_CONSISTENCY_TOL: f64 = 1e-6;

/// Rigid-body mass / inertia / CoM-offset block.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MassProperties {
    /// Total mass in kg.
    pub mass: f64,
    /// Pre-computed inverse mass (`1/mass`, in `1/kg`). Mirrors JEOD's
    /// `MassPointState::inverse_mass` so the inner loop is a multiply.
    pub inverse_mass: f64,
    /// Inertia tensor about the body-frame axes through the centre of
    /// mass (kg·m²).
    pub inertia: DMat3,
    /// Pre-computed inverse inertia tensor.
    pub inverse_inertia: DMat3,
    /// Centre-of-mass position relative to the structural-frame
    /// origin, in metres.
    pub position: DVec3,
    /// Rotation matrix from the structural frame to the body frame,
    /// matching JEOD `MassPointState::T_parent_this` for the
    /// composite-body point. Defaults to `IDENTITY` (struct = body), which
    /// is the right answer for any body whose `pt_orientation` was set to
    /// identity in JEOD's `Modified_data/mass/*.py`. Bodies with a
    /// non-identity orientation (e.g. SIM_Apollo's CM/LES/DM/Ascent
    /// modules each declare a 180° eigen-rotation about Z) must set this
    /// explicitly, otherwise the attach-algorithm conversion of
    /// struct-frame quantities to inertial picks up the wrong rotation.
    pub t_parent_this: DMat3,
    /// Set to `true` after mutating `mass` or `inertia` to trigger
    /// recomputation of `inverse_mass` and `inverse_inertia` on the next
    /// call to [`Self::recompute_derived`]. Constructors leave this `false`
    /// (derived quantities are already computed).
    pub dirty: bool,
}

impl MassProperties {
    /// Create mass properties for a point mass (unit sphere inertia: I = m * I_{3x3}).
    ///
    /// **Warning:** The placeholder inertia `I = m * I_{3x3}` is only valid for
    /// translational dynamics. It will produce **wrong results** for rotational
    /// dynamics because real spacecraft have non-spherical inertia tensors with
    /// distinct principal moments (I_xx != I_yy != I_zz) and potentially
    /// non-zero products of inertia. When rotational dynamics are enabled,
    /// callers must specify the actual inertia tensor for their geometry.
    // JEOD_INV: MA.02 — mass > 0 for meaningful dynamics
    pub fn new(mass: f64) -> Self {
        assert!(mass > 0.0, "mass must be positive, got {mass}");
        Self {
            mass,
            inverse_mass: 1.0 / mass,
            inertia: DMat3::IDENTITY * mass,
            inverse_inertia: DMat3::IDENTITY / mass,
            position: DVec3::ZERO,
            t_parent_this: DMat3::IDENTITY,
            dirty: false,
        }
    }

    /// Create mass properties with explicit inertia tensor and center-of-mass position.
    ///
    /// The inertia tensor is about the body frame axes through the center of mass.
    /// The position is the center of mass in the structural frame.
    // JEOD_INV: MA.02 — mass > 0 for meaningful dynamics
    // JEOD_INV: MA.05 — JEOD computes inverse inertia only for root bodies; we compute for all (structural divergence)
    // JEOD_INV: DB.23 — compute_inverse_inertia enabled (always computed here)
    // JEOD_INV: MA.04 — inverse_inertia consistent with inertia (computed from inertia)
    pub fn with_inertia(mass: f64, inertia: DMat3, position: DVec3) -> Self {
        assert!(mass > 0.0, "mass must be positive, got {mass}");
        let det = inertia.determinant();
        assert!(
            det.abs() > 1e-30,
            "inertia tensor is singular or near-singular (det={det:.2e}); \
             inverse will produce inf/NaN"
        );
        let inverse_inertia = inertia.inverse();
        Self {
            mass,
            inverse_mass: 1.0 / mass,
            inertia,
            inverse_inertia,
            position,
            t_parent_this: DMat3::IDENTITY,
            dirty: false,
        }
    }

    /// Builder: set the struct→body rotation. See the [`Self::t_parent_this`]
    /// field doc-comment for when this is needed.
    pub fn with_t_parent_this(mut self, t_parent_this: DMat3) -> Self {
        self.t_parent_this = t_parent_this;
        self
    }

    /// Recompute `inverse_mass` and `inverse_inertia` from `mass` and `inertia`.
    ///
    /// Port of the recomputation logic in JEOD's `MassBody::update_mass_properties()`
    /// (`mass_update.cc` lines 62-68, 118-124). JEOD runs this every timestep
    /// at the dynamics rate to pick up runtime mass changes (fuel burn, staging,
    /// attach/detach).
    ///
    /// Call this after modifying `mass` or `inertia` directly on the struct.
    /// Constructors (`new`, `with_inertia`) call this implicitly.
    ///
    /// # Panics
    /// Panics if `mass <= 0` or `inertia` is singular.
    // JEOD_INV: MA.03 — inverse_mass consistent with mass (recomputed as 1/mass)
    // JEOD_INV: MA.04 — inverse_inertia consistent with inertia (recomputed from inertia)
    // JEOD_INV: MA.07 — derived quantities recomputed after mutation
    pub fn recompute_derived(&mut self) {
        if !self.dirty {
            return;
        }
        self.dirty = false;

        assert!(self.mass > 0.0, "mass must be positive, got {}", self.mass);
        self.inverse_mass = 1.0 / self.mass;

        let det = self.inertia.determinant();
        assert!(
            det.abs() > 1e-30,
            "inertia tensor is singular or near-singular (det={det:.2e}); \
             inverse will produce inf/NaN"
        );
        self.inverse_inertia = self.inertia.inverse();
    }

    /// Validate that `inertia` and `inverse_inertia` are consistent.
    ///
    /// In JEOD, `inverse_inertia` is always recomputed from `inertia` (via
    /// `compute_inverse_inertia()`), so they are guaranteed consistent. In ECS
    /// both fields are public, so external code could set them independently.
    /// This method checks that `I * I^-1 ≈ identity` to the given tolerance.
    ///
    /// # Panics
    /// Panics if `I * I^-1` deviates from identity by more than `tol`.
    // JEOD_INV: DB.19 — inverse_inertia used for Euler equation (validated I*I^-1 ≈ identity)
    // JEOD_INV: MA.04 — inverse_inertia consistent with inertia
    pub fn validate_consistency(&self, tol: f64) {
        let product = self.inertia * self.inverse_inertia;
        assert!(
            (product - DMat3::IDENTITY).abs_diff_eq(DMat3::ZERO, tol),
            "MassProperties: inertia and inverse_inertia are inconsistent \
             (I * I^-1 != identity to {tol:.0e}). In JEOD, inverse_inertia \
             is always recomputed from inertia. Use MassProperties::with_inertia() \
             when constructing, or call MassProperties::recompute_derived() after \
             mutating mass/inertia."
        );
    }
}

/// Typed sibling of [`MassProperties`] parameterized by a vehicle marker
/// `V`. Mass becomes a `uom::si::f64::Mass`, inertia is wrapped in
/// [`InertiaTensor<BodyFrame<V>>`], and the center-of-mass position
/// carries the `StructuralFrame<V>` phantom tag.
///
/// `inverse_mass` and `inverse_inertia` remain untyped (`f64` and
/// `DMat3`): they are the integrator-hot-path caches for `F = m·a`
/// resolution. The dimension is `1/M` and `1/(M·L²)` respectively —
/// `astrodyn_quantities` does not expose a typed `Inverse<Mass>` alias and
/// adding one would be churn for no enforced invariant beyond the f64
/// path's own unit consistency.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MassPropertiesTyped<V: Vehicle> {
    /// Total mass.
    pub mass: Mass,
    /// Precomputed `1 / mass` in `kg⁻¹` (caller maintains consistency
    /// via [`Self::recompute_derived`]).
    pub inverse_mass: f64,
    /// Inertia tensor about the body-frame axes through the center of mass.
    pub inertia: InertiaTensor<BodyFrame<V>>,
    /// Precomputed `inertia⁻¹`. Maintained consistent with `inertia` via
    /// [`Self::recompute_derived`].
    pub inverse_inertia: DMat3,
    /// Center of mass in the structural frame.
    pub center_of_mass: Position<StructuralFrame<V>>,
    /// Structure-to-body rotation. Same semantic as
    /// [`MassProperties::t_parent_this`]; carried on the typed sibling
    /// because Apollo (and any vehicle whose `pt_orientation` is not
    /// the identity) sets a non-identity value, and a round-trip that
    /// silently rewrote it to identity caused launch-stack composite
    /// COMs to drift in `tier3_sim_apollo_trajectory`.
    pub t_parent_this: DMat3,
    /// See [`MassProperties::dirty`].
    pub dirty: bool,
    _v: PhantomData<V>,
}

impl<V: Vehicle> MassPropertiesTyped<V> {
    /// Point-mass constructor with placeholder spherical inertia
    /// (`I = m · I_{3×3}`) — see [`MassProperties::new`] for the same
    /// caveat about translational-only validity.
    // JEOD_INV: MA.02 — mass > 0 for meaningful dynamics
    pub fn new(mass: Mass) -> Self {
        let m = mass.get::<kilogram>();
        assert!(m > 0.0, "mass must be positive, got {m}");
        Self {
            mass,
            inverse_mass: 1.0 / m,
            inertia: InertiaTensor::<BodyFrame<V>>::from_dmat3_unchecked(DMat3::IDENTITY * m),
            inverse_inertia: DMat3::IDENTITY / m,
            center_of_mass: Position::<StructuralFrame<V>>::zero(),
            t_parent_this: DMat3::IDENTITY,
            dirty: false,
            _v: PhantomData,
        }
    }

    /// Constructor with explicit inertia and center-of-mass position.
    // JEOD_INV: MA.02 — mass > 0 for meaningful dynamics
    // JEOD_INV: MA.04 — inverse_inertia computed from inertia
    // JEOD_INV: DB.23 — inverse_inertia always computed
    pub fn with_inertia(
        mass: Mass,
        inertia: InertiaTensor<BodyFrame<V>>,
        center_of_mass: Position<StructuralFrame<V>>,
    ) -> Self {
        let m = mass.get::<kilogram>();
        assert!(m > 0.0, "mass must be positive, got {m}");
        let inertia_dmat = inertia.as_dmat3();
        let det = inertia_dmat.determinant();
        assert!(
            det.abs() > 1e-30,
            "inertia tensor is singular or near-singular (det={det:.2e}); \
             inverse will produce inf/NaN"
        );
        Self {
            mass,
            inverse_mass: 1.0 / m,
            inertia,
            inverse_inertia: inertia_dmat.inverse(),
            center_of_mass,
            t_parent_this: DMat3::IDENTITY,
            dirty: false,
            _v: PhantomData,
        }
    }

    /// Set the structure-to-body rotation (mirrors
    /// [`MassProperties::with_t_parent_this`]).
    pub fn with_t_parent_this(mut self, t_parent_this: DMat3) -> Self {
        self.t_parent_this = t_parent_this;
        self
    }

    /// Recompute `inverse_mass` and `inverse_inertia`.
    // JEOD_INV: MA.03 — inverse_mass = 1/mass (recomputed)
    // JEOD_INV: MA.04 — inverse_inertia consistent with inertia (recomputed)
    // JEOD_INV: MA.07 — derived quantities recomputed after mutation
    pub fn recompute_derived(&mut self) {
        if !self.dirty {
            return;
        }
        self.dirty = false;
        let m = self.mass.get::<kilogram>();
        assert!(m > 0.0, "mass must be positive, got {m}");
        self.inverse_mass = 1.0 / m;
        let inertia_dmat = self.inertia.as_dmat3();
        let det = inertia_dmat.determinant();
        assert!(
            det.abs() > 1e-30,
            "inertia tensor is singular or near-singular (det={det:.2e}); \
             inverse will produce inf/NaN"
        );
        self.inverse_inertia = inertia_dmat.inverse();
    }

    /// JEOD MA.04 invariant check: `inertia · inverse_inertia ≈ I`.
    // JEOD_INV: MA.04 — inverse_inertia consistent with inertia
    pub fn validate_consistency(&self, tol: f64) {
        let product = self.inertia.as_dmat3() * self.inverse_inertia;
        assert!(
            (product - DMat3::IDENTITY).abs_diff_eq(DMat3::ZERO, tol),
            "MassPropertiesTyped: inertia and inverse_inertia inconsistent \
             (I·I⁻¹ != identity to {tol:.0e})"
        );
    }

    /// Drop the phantoms and emit the untyped storage form, preserving
    /// every field verbatim (including the cache fields `inverse_mass`,
    /// `inverse_inertia`, and `dirty`, plus `t_parent_this` — the field
    /// whose silent drop was the Apollo regression in #393).
    #[inline]
    pub fn to_untyped(&self) -> MassProperties {
        MassProperties {
            mass: self.mass.get::<kilogram>(),
            inverse_mass: self.inverse_mass,
            inertia: self.inertia.as_dmat3(),
            inverse_inertia: self.inverse_inertia,
            position: self.center_of_mass.raw_si(),
            t_parent_this: self.t_parent_this,
            dirty: self.dirty,
        }
    }

    /// Wrap an untyped [`MassProperties`] as typed. **The caller
    /// asserts** body-frame inertia, structural-frame center of mass,
    /// and consistency between `inverse_mass`/`inverse_inertia` and
    /// `mass`/`inertia` — the latter is the same contract the untyped
    /// struct exposes, since both fields are public there too.
    #[inline]
    pub fn from_untyped_unchecked(s: &MassProperties) -> Self {
        Self {
            mass: Mass::new::<kilogram>(s.mass),
            inverse_mass: s.inverse_mass,
            inertia: InertiaTensor::<BodyFrame<V>>::from_dmat3_unchecked(s.inertia),
            inverse_inertia: s.inverse_inertia,
            center_of_mass: Position::<StructuralFrame<V>>::from_raw_si(s.position),
            t_parent_this: s.t_parent_this,
            dirty: s.dirty,
            _v: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn point_mass_inertia() {
        let mp = MassProperties::new(10.0);
        assert_eq!(mp.mass, 10.0);
        assert_eq!(mp.inverse_mass, 0.1);
        assert_eq!(mp.inertia, DMat3::IDENTITY * 10.0);
        assert_eq!(mp.inverse_inertia, DMat3::IDENTITY / 10.0);
        assert_eq!(mp.position, DVec3::ZERO);
    }

    #[test]
    fn inertia_times_inverse_is_identity() {
        let mp = MassProperties::new(42.0);
        let product = mp.inertia * mp.inverse_inertia;
        let diff = product - DMat3::IDENTITY;
        // Check all 9 elements are near zero
        assert!(diff.x_axis.length() < 1e-12);
        assert!(diff.y_axis.length() < 1e-12);
        assert!(diff.z_axis.length() < 1e-12);
    }

    #[test]
    fn validate_consistency_passes_for_consistent() {
        let mp = MassProperties::with_inertia(
            10.0,
            DMat3::from_diagonal(DVec3::new(100.0, 200.0, 300.0)),
            DVec3::ZERO,
        );
        mp.validate_consistency(1e-6); // should not panic
    }

    #[test]
    #[should_panic(expected = "inconsistent")]
    fn validate_consistency_fails_for_wrong_inverse() {
        let mut mp = MassProperties::with_inertia(
            10.0,
            DMat3::from_diagonal(DVec3::new(100.0, 200.0, 300.0)),
            DVec3::ZERO,
        );
        // Corrupt the inverse
        mp.inverse_inertia = DMat3::IDENTITY;
        mp.validate_consistency(1e-6);
    }

    #[test]
    fn recompute_derived_after_mass_change() {
        let mut mp = MassProperties::new(10.0);
        assert_eq!(mp.inverse_mass, 0.1);

        // Simulate fuel burn: mass decreases
        mp.mass = 8.0;
        mp.dirty = true;
        // inverse_mass is now stale (still 0.1)
        assert_eq!(mp.inverse_mass, 0.1);

        mp.recompute_derived();
        assert!((mp.inverse_mass - 0.125).abs() < 1e-15);
        assert!((mp.mass * mp.inverse_mass - 1.0).abs() < 1e-15);
        assert!(!mp.dirty);
    }

    #[test]
    fn recompute_derived_skips_when_clean() {
        let mut mp = MassProperties::new(10.0);
        assert!(!mp.dirty);
        // recompute_derived is a no-op when clean
        mp.recompute_derived();
        assert_eq!(mp.inverse_mass, 0.1);
    }

    #[test]
    fn recompute_derived_after_inertia_change() {
        let mut mp = MassProperties::with_inertia(
            10.0,
            DMat3::from_diagonal(DVec3::new(100.0, 200.0, 300.0)),
            DVec3::ZERO,
        );

        // Change inertia (e.g., fuel redistribution)
        mp.inertia = DMat3::from_diagonal(DVec3::new(50.0, 100.0, 150.0));
        mp.dirty = true;
        // inverse_inertia is now stale
        mp.recompute_derived();

        // Verify consistency
        mp.validate_consistency(1e-6);
        assert!((mp.inverse_mass - 0.1).abs() < 1e-15);
    }

    // ---- typed MassPropertiesTyped<V> ----------------------------------

    #[test]
    fn typed_point_mass_round_trips_to_untyped() {
        use astrodyn_quantities::frame::TestVehicle;

        let typed = MassPropertiesTyped::<TestVehicle>::new(Mass::new::<kilogram>(10.0));

        assert_eq!(typed.mass.get::<kilogram>(), 10.0);
        assert_eq!(typed.inverse_mass, 0.1);
        assert_eq!(typed.inertia.as_dmat3(), DMat3::IDENTITY * 10.0);
        assert_eq!(typed.inverse_inertia, DMat3::IDENTITY / 10.0);
        assert_eq!(typed.center_of_mass.raw_si(), DVec3::ZERO);
    }

    #[test]
    fn typed_with_inertia_matches_untyped() {
        use astrodyn_quantities::frame::TestVehicle;

        let m = 5.0;
        let i = DMat3::from_diagonal(DVec3::new(50.0, 60.0, 70.0));
        let pos = DVec3::new(0.1, 0.2, 0.3);

        let typed = MassPropertiesTyped::<TestVehicle>::with_inertia(
            Mass::new::<kilogram>(m),
            InertiaTensor::<BodyFrame<TestVehicle>>::from_dmat3_unchecked(i),
            Position::<StructuralFrame<TestVehicle>>::from_raw_si(pos),
        );
        let untyped = MassProperties::with_inertia(m, i, pos);

        assert_eq!(typed.mass.get::<kilogram>(), untyped.mass);
        assert_eq!(typed.inverse_mass, untyped.inverse_mass);
        assert_eq!(typed.inertia.as_dmat3(), untyped.inertia);
        assert_eq!(typed.inverse_inertia, untyped.inverse_inertia);
        assert_eq!(typed.center_of_mass.raw_si(), untyped.position);
        assert_eq!(typed.t_parent_this, untyped.t_parent_this);
        assert_eq!(typed.dirty, untyped.dirty);
    }

    #[test]
    fn typed_validate_consistency_passes() {
        use astrodyn_quantities::frame::TestVehicle;

        let typed = MassPropertiesTyped::<TestVehicle>::with_inertia(
            Mass::new::<kilogram>(10.0),
            InertiaTensor::<BodyFrame<TestVehicle>>::from_dmat3_unchecked(DMat3::from_diagonal(
                DVec3::new(100.0, 200.0, 300.0),
            )),
            Position::<StructuralFrame<TestVehicle>>::zero(),
        );
        typed.validate_consistency(1e-6);
    }

    // ---- proptest round-trips (#398) ----------------------------------
    //
    // Apollo regression class: the typed sibling silently dropped
    // `t_parent_this` in #393. These property tests assert verbatim
    // field-level round-trip equality so any future field added on one
    // side without updating the other fails CI immediately.

    use astrodyn_quantities::frame::TestVehicle;
    use proptest::prelude::*;

    fn arb_finite_bounded() -> impl Strategy<Value = f64> {
        prop_oneof![
            (1.0e-9_f64..1.0e9_f64),
            (1.0e-9_f64..1.0e9_f64).prop_map(|x| -x),
        ]
    }

    fn arb_dvec3() -> impl Strategy<Value = DVec3> {
        (
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
        )
            .prop_map(|(x, y, z)| DVec3::new(x, y, z))
    }

    fn arb_dmat3_full_rank() -> impl Strategy<Value = DMat3> {
        // Build a diagonal matrix with strictly positive principal
        // moments (ensures non-singular and `inverse()` is well-defined),
        // then conjugate by a small rotation so off-diagonal terms can
        // arise without risking degeneracy.
        (
            (1.0_f64..1.0e6_f64),
            (1.0_f64..1.0e6_f64),
            (1.0_f64..1.0e6_f64),
            (-1.0_f64..1.0_f64),
            (-1.0_f64..1.0_f64),
            (-1.0_f64..1.0_f64),
        )
            .prop_map(|(ix, iy, iz, ax, ay, az)| {
                let diag = DMat3::from_diagonal(DVec3::new(ix, iy, iz));
                let axis = DVec3::new(ax, ay, az);
                let rot = if axis.length_squared() > 1.0e-6 {
                    let angle = 0.1; // small bounded rotation; off-diagonal magnitude ~10%
                    glam::DMat3::from_axis_angle(axis.normalize(), angle)
                } else {
                    DMat3::IDENTITY
                };
                rot.transpose() * diag * rot
            })
    }

    fn arb_arbitrary_dmat3() -> impl Strategy<Value = DMat3> {
        // 9 independent finite scalars — used for `t_parent_this` and
        // `inverse_inertia` (both are stored verbatim and compared
        // verbatim, so no positive-definiteness constraint is needed
        // for round-trip purposes).
        (
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
            arb_finite_bounded(),
        )
            .prop_map(|(a, b, c, d, e, f, g, h, i)| {
                DMat3::from_cols(
                    DVec3::new(a, b, c),
                    DVec3::new(d, e, f),
                    DVec3::new(g, h, i),
                )
            })
    }

    fn arb_mass_properties() -> impl Strategy<Value = MassProperties> {
        // Generate self-consistent caches per the plan: inverse_mass =
        // 1/mass, inverse_inertia = inertia.inverse(), dirty = false.
        // `t_parent_this` is independent (and the regression-class
        // field — generate it as an arbitrary DMat3 so the round-trip
        // sees a non-identity value).
        (
            (1.0e-3_f64..1.0e6_f64),
            arb_dmat3_full_rank(),
            arb_dvec3(),
            arb_arbitrary_dmat3(),
        )
            .prop_map(|(mass, inertia, position, t_parent_this)| MassProperties {
                mass,
                inverse_mass: 1.0 / mass,
                inertia,
                inverse_inertia: inertia.inverse(),
                position,
                t_parent_this,
                dirty: false,
            })
    }

    proptest! {
        #[test]
        fn round_trip_mass_properties_untyped_typed_untyped(orig in arb_mass_properties()) {
            let typed = MassPropertiesTyped::<TestVehicle>::from_untyped_unchecked(&orig);
            prop_assert_eq!(typed.to_untyped(), orig);
        }

        // Asserted via the untyped projection — `MassPropertiesTyped`'s
        // derived `PartialEq` requires `TestVehicle: PartialEq`, which
        // it isn't. Catches dropped/added fields equally well.
        #[test]
        fn round_trip_mass_properties_typed_untyped_typed(orig in arb_mass_properties()) {
            let typed = MassPropertiesTyped::<TestVehicle>::from_untyped_unchecked(&orig);
            let lifted = MassPropertiesTyped::<TestVehicle>::from_untyped_unchecked(&typed.to_untyped());
            prop_assert_eq!(lifted.to_untyped(), typed.to_untyped());
        }
    }
}