avian3d/dynamics/rigid_body/mass_properties/
mod.rs

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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Mass property functionality for [rigid bodies] and [colliders].
//!
//! # Overview
//!
//! Every dynamic rigid body has [mass], [angular inertia], and a [center of mass].
//! These mass properties determine how the rigid body responds to forces and torques.
//!
//! - **Mass**: Represents resistance to linear acceleration. A higher mass requires more force for the same acceleration.
//! - **Angular Inertia**: Represents resistance to angular acceleration. A higher angular inertia requires more torque for the same angular acceleration.
//! - **Center of Mass**: The average position of mass in the body. Applying forces at this point produces no torque.
//!
//! Static and kinematic rigid bodies have infinite mass and angular inertia,
//! and do not respond to forces or torques. Zero mass for a dynamic body is also
//! treated as a special case, and corresponds to infinite mass.
//!
//! Mass properties can be set for individual entities using the [`Mass`], [`AngularInertia`],
//! and [`CenterOfMass`] components. If they are not present, mass properties are instead computed
//! automatically from attached colliders based on their shape and [`ColliderDensity`].
//!
//! If a rigid body has child entities, their mass properties are combined to compute
//! the total mass properties of the rigid body. These are stored in the [`ComputedMass`],
//! [`ComputedAngularInertia`], and [`ComputedCenterOfMass`] components, which are updated
//! automatically when mass properties are changed, or when colliders are added or removed.
//!
//! To prevent mass properties of child entities from contributing to the total mass properties,
//! you can use the [`NoAutoMass`], [`NoAutoAngularInertia`], and [`NoAutoCenterOfMass`] marker components.
//! This can be useful when full control over mass properties is desired.
//!
//! [rigid bodies]: crate::dynamics::rigid_body::RigidBody
//! [colliders]: crate::dynamics::collider::Collider
//! [mass]: components::Mass
//! [angular inertia]: components::AngularInertia
//! [center of mass]: components::CenterOfMass
//!
//! ## Example
//!
//! If no mass properties are set, they are computed automatically from attached colliders
//! based on their shape and density.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! # fn setup(mut commands: Commands) {
//! // Note: `ColliderDensity` is optional, and defaults to `1.0` if not present.
//! commands.spawn((
//!     RigidBody::Dynamic,
//!     Collider::capsule(0.5, 1.5),
//!     ColliderDensity(2.0),
//! ));
//! # }
//! ```
//!
//! If mass properties are set with the [`Mass`], [`AngularInertia`], and [`CenterOfMass`] components,
//! they override the values computed from colliders.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! # fn setup(mut commands: Commands) {
//! // Override mass and the center of mass, but use the collider's angular inertia.
//! commands.spawn((
//!     RigidBody::Dynamic,
//!     Collider::capsule(0.5, 1.5),
//!     Mass(5.0),
#![cfg_attr(feature = "2d", doc = "    CenterOfMass::new(0.0, -0.5),")]
#![cfg_attr(feature = "3d", doc = "    CenterOfMass::new(0.0, -0.5, 0.0),")]
//! ));
//! # }
//! ```
//!
//! If the rigid body has child colliders, their mass properties will be combined for
//! the total [`ComputedMass`], [`ComputedAngularInertia`], and [`ComputedCenterOfMass`].
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! # fn setup(mut commands: Commands) {
//! // Total mass: 10.0 + 5.0 = 15.0
#![cfg_attr(
    feature = "2d",
    doc = "// Total center of mass: (10.0 * [0.0, -0.5] + 5.0 * [0.0, 4.0]) / (10.0 + 5.0) = [0.0, 1.0]"
)]
#![cfg_attr(
    feature = "3d",
    doc = "// Total center of mass: (10.0 * [0.0, -0.5, 0.0] + 5.0 * [0.0, 4.0, 0.0]) / (10.0 + 5.0) = [0.0, 1.0, 0.0]"
)]
//! commands.spawn((
//!     RigidBody::Dynamic,
//!     Collider::capsule(0.5, 1.5),
//!     Mass(10.0),
#![cfg_attr(feature = "2d", doc = "    CenterOfMass::new(0.0, -0.5),")]
#![cfg_attr(feature = "3d", doc = "    CenterOfMass::new(0.0, -0.5, 0.0),")]
//!     Transform::default(),
//! ))
//! .with_child((
#![cfg_attr(feature = "2d", doc = "    Collider::circle(1.0),")]
#![cfg_attr(feature = "3d", doc = "    Collider::sphere(1.0),")]
//!     Mass(5.0),
//!     Transform::from_xyz(0.0, 4.0, 0.0),
//! ));
//! # }
//! ```
//!
//! To prevent child entities from contributing to the total mass properties, use the [`NoAutoMass`],
//! [`NoAutoAngularInertia`], and [`NoAutoCenterOfMass`] marker components.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! # fn setup(mut commands: Commands) {
//! // Total mass: 10.0
#![cfg_attr(feature = "2d", doc = "// Total center of mass: [0.0, -0.5]")]
#![cfg_attr(feature = "3d", doc = "// Total center of mass: [0.0, -0.5, 0.0]")]
//! commands.spawn((
//!     RigidBody::Dynamic,
//!     Collider::capsule(0.5, 1.5),
//!     Mass(10.0),
#![cfg_attr(feature = "2d", doc = "    CenterOfMass::new(0.0, -0.5),")]
#![cfg_attr(feature = "3d", doc = "    CenterOfMass::new(0.0, -0.5, 0.0),")]
//!     NoAutoMass,
//!     NoAutoCenterOfMass,
//!     Transform::default(),
//! ))
//! .with_child((
#![cfg_attr(feature = "2d", doc = "    Collider::circle(1.0),")]
#![cfg_attr(feature = "3d", doc = "    Collider::sphere(1.0),")]
//!     Mass(5.0),
//!     Transform::from_xyz(0.0, 4.0, 0.0),
//! ));
//! # }
//! ```
//!
//! # Computing Mass Properties for Shapes
//!
//! Mass properties of colliders and Bevy's primitive shapes can be computed using methods
//! provided by the [`ComputeMassProperties2d`] and [`ComputeMassProperties3d`] traits.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! #
//! // Compute mass properties for a capsule collider with a density of `2.0`.
//! let capsule = Collider::capsule(0.5, 1.5);
//! let mass_properties = capsule.mass_properties(2.0);
//!
//! // Compute individual mass properties for a `Circle`.
//! let circle = Circle::new(1.0);
//! let mass = circle.mass(2.0);
//! let angular_inertia = circle.angular_inertia(mass);
//! let center_of_mass = circle.center_of_mass();
//! ```
//!
//! Similarly, shapes can be used to construct the [`Mass`], [`AngularInertia`],
//! and [`CenterOfMass`] components, or the [`MassPropertiesBundle`].
//!
//! ```
#![cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
//! # use bevy::prelude::*;
//! #
//! # fn setup(mut commands: Commands) {
//! // Construct individual mass properties from a collider.
#![cfg_attr(feature = "2d", doc = "let shape = Collider::circle(0.5);")]
#![cfg_attr(feature = "3d", doc = "let shape = Collider::sphere(0.5);")]
//! commands.spawn((
//!     RigidBody::Dynamic,
//!     Mass::from_shape(&shape, 2.0),
//!     AngularInertia::from_shape(&shape, 1.5),
//!     CenterOfMass::from_shape(&shape),
//! ));
//!
//! // Construct a `MassPropertiesBundle` from a primitive shape.
#![cfg_attr(feature = "2d", doc = "let shape = Circle::new(0.5);")]
#![cfg_attr(feature = "3d", doc = "let shape = Sphere::new(0.5);")]
//! commands.spawn((RigidBody::Dynamic, MassPropertiesBundle::from_shape(&shape, 2.0)));
//! # }
//! ```
//!
//! This mass property computation functionality is provided by the [`bevy_heavy`] crate.
//!
//! # Mass Property Helper
//!
//! [`MassPropertyHelper`] is a [`SystemParam`](bevy::ecs::system::SystemParam) that provides convenient helper methods
//! that can be used to modify or compute mass properties for individual entities and hierarchies at runtime.
//!
//! For example, [`MassPropertyHelper::total_mass_properties`] computes the total mass properties of an entity,
//! taking into account the mass properties of descendants and colliders.

use crate::{prelude::*, prepare::PrepareSet};
#[cfg(feature = "3d")]
use bevy::ecs::query::QueryFilter;
use bevy::{
    ecs::{intern::Interned, schedule::ScheduleLabel},
    prelude::*,
};

pub mod components;
use components::RecomputeMassProperties;

mod system_param;
pub use system_param::MassPropertyHelper;

/// Mass property computation with `bevy_heavy`, re-exported for your convenience.
pub use bevy_heavy;

#[cfg(feature = "2d")]
pub(crate) use bevy_heavy::{
    ComputeMassProperties2d as ComputeMassProperties, MassProperties2d as MassProperties,
};
#[cfg(feature = "3d")]
pub(crate) use bevy_heavy::{
    ComputeMassProperties3d as ComputeMassProperties, MassProperties3d as MassProperties,
};

/// An extension trait for [`MassProperties`].
pub trait MassPropertiesExt {
    /// Converts the [`MassProperties`] to a [`MassPropertiesBundle`]
    /// containing the [`Mass`], [`AngularInertia`], and [`CenterOfMass`] components.
    fn to_bundle(&self) -> MassPropertiesBundle;
}

impl MassPropertiesExt for MassProperties {
    fn to_bundle(&self) -> MassPropertiesBundle {
        #[cfg(feature = "2d")]
        let angular_inertia = AngularInertia(self.angular_inertia);
        #[cfg(feature = "3d")]
        let angular_inertia = AngularInertia::new_with_local_frame(
            self.principal_angular_inertia.f32(),
            self.local_inertial_frame.f32(),
        );

        MassPropertiesBundle {
            mass: Mass(self.mass),
            angular_inertia,
            center_of_mass: CenterOfMass(self.center_of_mass),
        }
    }
}

/// A plugin for managing [mass properties] of rigid bodies.
///
/// - Updates the [`ComputedMass`], [`ComputedAngularInertia`], and [`ComputedCenterOfMass`] components
///   for rigid bodies when their mass properties are changed, or when colliders are added or removed.
/// - Logs warnings when dynamic bodies have invalid [`Mass`] or [`AngularInertia`].
///
/// [mass properties]: crate::dynamics::rigid_body::mass_properties
pub struct MassPropertyPlugin {
    schedule: Interned<dyn ScheduleLabel>,
}

impl MassPropertyPlugin {
    /// Creates a [`MassPropertyPlugin`] with the schedule that is used for running the [`PhysicsSchedule`].
    ///
    /// The default schedule is `FixedPostUpdate`.
    pub fn new(schedule: impl ScheduleLabel) -> Self {
        Self {
            schedule: schedule.intern(),
        }
    }
}

impl Default for MassPropertyPlugin {
    fn default() -> Self {
        Self::new(FixedPostUpdate)
    }
}

impl Plugin for MassPropertyPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<(
            Mass,
            AngularInertia,
            CenterOfMass,
            ComputedMass,
            ComputedAngularInertia,
            ComputedCenterOfMass,
            ColliderDensity,
            ColliderMassProperties,
            NoAutoMass,
            NoAutoAngularInertia,
            NoAutoCenterOfMass,
        )>();

        // Force mass property computation for new rigid bodies.
        app.register_required_components::<RigidBody, RecomputeMassProperties>();

        // Configure system sets for mass property computation.
        app.configure_sets(
            self.schedule,
            (
                MassPropertySystems::UpdateColliderMassProperties,
                MassPropertySystems::QueueRecomputation,
                MassPropertySystems::UpdateComputedMassProperties,
            )
                .chain()
                .in_set(PrepareSet::Finalize),
        );

        // Queue mass property recomputation when mass properties are changed.
        app.add_systems(
            self.schedule,
            (
                queue_mass_recomputation_on_mass_change,
                queue_mass_recomputation_on_collider_mass_change,
            )
                .in_set(MassPropertySystems::QueueRecomputation),
        );

        // Update mass properties for entities with the `RecomputeMassProperties` component.
        app.add_systems(
            self.schedule,
            (
                update_mass_properties,
                #[cfg(feature = "3d")]
                update_global_angular_inertia::<Added<RigidBody>>,
                warn_missing_mass,
            )
                .chain()
                .in_set(MassPropertySystems::UpdateComputedMassProperties),
        );
    }
}

/// A system set for logic related to updating mass properties.
#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MassPropertySystems {
    /// Update [`ColliderMassProperties`] for colliders.
    UpdateColliderMassProperties,
    /// Adds the [`RecomputeMassProperties`] component to entities with changed mass properties.
    QueueRecomputation,
    /// Update [`ComputedMass`], [`ComputedAngularInertia`], and [`ComputedCenterOfMass`]
    /// for entities with the [`RecomputeMassProperties`] component. The component is removed after updating.
    UpdateComputedMassProperties,
}

/// A query filter for entities with [`ComputedMass`], [`ComputedAngularInertia`], or [`ComputedCenterOfMass`].
pub type WithComputedMassProperty = Or<(
    With<ComputedMass>,
    With<ComputedAngularInertia>,
    With<ComputedCenterOfMass>,
)>;

/// A query filter for entities with changed [`Mass`], [`AngularInertia`], or [`CenterOfMass`].
pub type MassPropertyChanged = Or<(
    Changed<Mass>,
    Changed<AngularInertia>,
    Changed<CenterOfMass>,
)>;

/// Queues mass property recomputation for rigid bodies when their [`Mass`], [`AngularInertia`],
/// or [`CenterOfMass`] components are changed.
///
/// Entities with a [`ColliderParent`] are excluded, as they are handled by
/// [`queue_mass_recomputation_on_collider_mass_change`].
fn queue_mass_recomputation_on_mass_change(
    mut commands: Commands,
    mut query: Query<
        Entity,
        (
            WithComputedMassProperty,
            Without<ColliderParent>,
            MassPropertyChanged,
        ),
    >,
) {
    for entity in &mut query {
        commands.entity(entity).insert(RecomputeMassProperties);
    }
}

/// Queues mass property recomputation for rigid bodies when the [`ColliderMassProperties`],
/// [`Mass`], [`AngularInertia`], or [`CenterOfMass`] components of their colliders are changed.
fn queue_mass_recomputation_on_collider_mass_change(
    mut commands: Commands,
    mut query: Query<
        &ColliderParent,
        Or<(
            Changed<ColliderMassProperties>,
            Changed<ColliderTransform>,
            MassPropertyChanged,
        )>,
    >,
) {
    for collider_parent in &mut query {
        if let Some(mut entity_commands) = commands.get_entity(collider_parent.get()) {
            entity_commands.insert(RecomputeMassProperties);
        }
    }
}

fn update_mass_properties(
    mut commands: Commands,
    query: Query<Entity, With<RecomputeMassProperties>>,
    mut mass_helper: MassPropertyHelper,
) {
    // TODO: Parallelize mass property updates.
    for entity in query.iter() {
        mass_helper.update_mass_properties(entity);
        commands.entity(entity).remove::<RecomputeMassProperties>();
    }
}

/// Updates [`GlobalAngularInertia`] for entities that match the given query filter `F`.
#[cfg(feature = "3d")]
pub(crate) fn update_global_angular_inertia<F: QueryFilter>(
    mut query: Populated<
        (
            &Rotation,
            &ComputedAngularInertia,
            &mut GlobalAngularInertia,
        ),
        (Or<(Changed<ComputedAngularInertia>, Changed<Rotation>)>, F),
    >,
) {
    query
        .par_iter_mut()
        .for_each(|(rotation, angular_inertia, mut global_angular_inertia)| {
            global_angular_inertia.update(*angular_inertia, rotation.0);
        });
}

/// Logs warnings when dynamic bodies have invalid [`Mass`] or [`AngularInertia`].
fn warn_missing_mass(
    mut bodies: Query<
        (
            Entity,
            &RigidBody,
            Ref<ComputedMass>,
            Ref<ComputedAngularInertia>,
        ),
        Or<(Changed<ComputedMass>, Changed<ComputedAngularInertia>)>,
    >,
) {
    for (entity, rb, mass, inertia) in &mut bodies {
        let is_mass_valid = mass.value().is_finite();
        #[cfg(feature = "2d")]
        let is_inertia_valid = inertia.value().is_finite();
        #[cfg(feature = "3d")]
        let is_inertia_valid = inertia.value().is_finite();

        // Warn about dynamic bodies with no mass or inertia
        if rb.is_dynamic() && !(is_mass_valid && is_inertia_valid) {
            warn!(
                "Dynamic rigid body {:?} has no mass or inertia. This can cause NaN values. Consider adding a `MassPropertiesBundle` or a `Collider` with mass.",
                entity
            );
        }
    }
}

#[cfg(test)]
#[cfg(feature = "2d")]
#[expect(clippy::unnecessary_cast)]
mod tests {
    use approx::assert_relative_eq;

    use super::*;

    fn create_app() -> App {
        let mut app = App::new();
        app.add_plugins((
            MinimalPlugins,
            PhysicsPlugins::default(),
            TransformPlugin,
            HierarchyPlugin,
        ));
        app
    }

    fn get_computed_mass_properties(
        world: &mut World,
        entity: Entity,
    ) -> (
        &ComputedMass,
        &ComputedAngularInertia,
        &ComputedCenterOfMass,
    ) {
        let mut query = world.query::<(
            &ComputedMass,
            &ComputedAngularInertia,
            &ComputedCenterOfMass,
        )>();
        query.get(world, entity).unwrap()
    }

    #[test]
    fn mass_properties_zero_by_default() {
        // `RigidBody`

        let mut app = create_app();

        let body_entity = app.world_mut().spawn(RigidBody::Dynamic).id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(*mass, ComputedMass::default());
        assert_eq!(*angular_inertia, ComputedAngularInertia::default());
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_rb_collider() {
        // `RigidBody`, `Collider`

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app.world_mut().spawn((RigidBody::Dynamic, collider)).id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, collider_mass_props.mass);
        assert_eq!(
            angular_inertia.value() as f32,
            collider_mass_props.angular_inertia
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_rb_collider_with_set_mass() {
        // `RigidBody`, `Collider`, `Mass(5.0)`

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider, Mass(5.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0);
        assert_eq!(
            angular_inertia.value() as f32,
            mass.value() as f32 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_rb_collider_with_set_mass_and_angular_inertia() {
        // `RigidBody`, `Collider`, `Mass(5.0)`, `AngularInertia(10.0)`

        let mut app = create_app();

        let collider = Collider::circle(1.0);

        let body_entity = app
            .world_mut()
            .spawn((
                RigidBody::Dynamic,
                collider,
                Mass(5.0),
                AngularInertia(10.0),
            ))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0);
        assert_eq!(angular_inertia.value() as f32, 10.0);
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_rb_collider_with_set_mass_and_child_collider() {
        // `RigidBody`, `Collider`, `Mass(5.0)`
        // - `Collider`, `ColliderDensity(2.0)`

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(2.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider.clone(), Mass(5.0)))
            .with_child((collider, ColliderDensity(2.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0 + collider_mass_props.mass);
        assert_eq!(
            angular_inertia.value() as f32,
            5.0 * collider_mass_props.unit_angular_inertia() + collider_mass_props.angular_inertia
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_rb_collider_with_set_mass_and_child_collider_with_set_mass() {
        // `RigidBody`, `Collider`, `Mass(5.0)`
        // - `Collider`, `ColliderDensity(2.0)`, `Mass(10.0)`

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider.clone(), Mass(5.0)))
            .with_child((collider, ColliderDensity(2.0), Mass(10.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0 + 10.0);
        assert_eq!(
            angular_inertia.value() as f32,
            5.0 * collider_mass_props.unit_angular_inertia()
                + 10.0 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_no_auto_mass_collider_no_set_mass() {
        // `RigidBody`, `Collider`, `NoAutoMass`
        //
        // Mass properties should be zero.

        let mut app = create_app();

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, Collider::circle(1.0), NoAutoMass))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(*mass, ComputedMass::default());
        assert_eq!(*angular_inertia, ComputedAngularInertia::default());
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_no_auto_mass_hierarchy() {
        // `RigidBody`, `Collider`, `Mass(5.0)`, `NoAutoMass`
        // - `Collider`, `ColliderDensity(2.0)`, `Mass(10.0)`

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider.clone(), Mass(5.0), NoAutoMass))
            .with_child((collider, ColliderDensity(2.0), Mass(10.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0);
        assert_eq!(
            angular_inertia.value() as f32,
            mass.value() as f32
                * (5.0 * collider_mass_props.unit_angular_inertia()
                    + 10.0 * collider_mass_props.unit_angular_inertia())
                / 15.0
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_add_remove_collider() {
        // `RigidBody`, `Collider`
        //
        // - Check mass properties
        // - Add child `Collider`
        // - Check mass properties
        // - Remove child `Collider`
        // - Check mass properties

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app.world_mut().spawn((RigidBody::Dynamic, collider)).id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, collider_mass_props.mass);
        assert_eq!(
            angular_inertia.value() as f32,
            collider_mass_props.angular_inertia
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());

        // Add a child collider
        let child_collider = Collider::circle(2.0);
        let child_collider_mass_props = child_collider.mass_properties(1.0);

        app.world_mut()
            .entity_mut(body_entity)
            .with_child((child_collider, ColliderDensity(1.0)));

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(
            mass.value() as f32,
            collider_mass_props.mass + child_collider_mass_props.mass
        );
        assert_eq!(
            angular_inertia.value() as f32,
            collider_mass_props.angular_inertia + child_collider_mass_props.angular_inertia
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());

        // Remove the child collider
        app.world_mut()
            .entity_mut(body_entity)
            .despawn_descendants();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, collider_mass_props.mass);
        assert_eq!(
            angular_inertia.value() as f32,
            collider_mass_props.angular_inertia
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_change_mass() {
        // `RigidBody`, `Collider`, `Mass(5.0)`
        //
        // - Check mass properties
        // - Change mass
        // - Check mass properties

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider, Mass(5.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0);
        assert_eq!(
            angular_inertia.value() as f32,
            mass.value() as f32 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());

        // Change mass
        app.world_mut().entity_mut(body_entity).insert(Mass(10.0));

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 10.0);
        assert_eq!(
            angular_inertia.value() as f32,
            mass.value() as f32 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }

    #[test]
    fn mass_properties_move_child_collider() {
        // `RigidBody`, `Mass(10.0)`, `CenterOfMass(0.0, -0.5)`, `Transform`
        // - `Collider`, `Mass(5.0)`, `Transform`
        //
        // - Check mass properties
        // - Move child collider
        // - Check mass properties

        let mut app = create_app();

        let body_entity = app
            .world_mut()
            .spawn((
                RigidBody::Dynamic,
                Mass(10.0),
                CenterOfMass::new(0.0, -0.5),
                Transform::default(),
            ))
            .id();

        let child_entity = app
            .world_mut()
            .spawn((Collider::circle(1.0), Mass(5.0), Transform::default()))
            .set_parent(body_entity)
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, _, center_of_mass) = get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 10.0 + 5.0);
        assert_relative_eq!(
            center_of_mass.0,
            Vector::new(0.0, -1.0 / 3.0),
            epsilon = 1.0e-6
        );

        // Move child collider
        app.world_mut()
            .entity_mut(child_entity)
            .insert(Transform::from_xyz(0.0, 4.0, 0.0));

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, _, center_of_mass) = get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value(), 10.0 + 5.0);
        assert_relative_eq!(center_of_mass.0, Vector::new(0.0, 1.0));
    }

    #[test]
    fn mass_properties_no_auto_mass_add_remove() {
        // `RigidBody`, `Collider`, `Mass(5.0)`
        // - `Collider`, `Mass(10.0)`
        //
        // - Check mass properties
        // - Add `NoAutoMass`
        // - Check mass properties
        // - Remove `NoAutoMass`
        // - Check mass properties

        let mut app = create_app();

        let collider = Collider::circle(1.0);
        let collider_mass_props = collider.mass_properties(1.0);

        let body_entity = app
            .world_mut()
            .spawn((RigidBody::Dynamic, collider.clone(), Mass(5.0)))
            .with_child((collider, Mass(10.0)))
            .id();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0 + 10.0);
        assert_eq!(
            angular_inertia.value() as f32,
            5.0 * collider_mass_props.unit_angular_inertia()
                + 10.0 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());

        // Add `NoAutoMass`
        app.world_mut().entity_mut(body_entity).insert(NoAutoMass);

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0);
        assert_eq!(
            angular_inertia.value() as f32,
            5.0 * (5.0 * collider_mass_props.unit_angular_inertia()
                + 10.0 * collider_mass_props.unit_angular_inertia())
                / 15.0
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());

        // Remove `NoAutoMass`
        app.world_mut()
            .entity_mut(body_entity)
            .remove::<NoAutoMass>();

        app.world_mut().run_schedule(FixedPostUpdate);

        let (mass, angular_inertia, center_of_mass) =
            get_computed_mass_properties(app.world_mut(), body_entity);

        assert_eq!(mass.value() as f32, 5.0 + 10.0);
        assert_eq!(
            angular_inertia.value() as f32,
            5.0 * collider_mass_props.unit_angular_inertia()
                + 10.0 * collider_mass_props.unit_angular_inertia()
        );
        assert_eq!(*center_of_mass, ComputedCenterOfMass::default());
    }
}