Skip to main content

avian3d/collision/collider/
constructor.rs

1use core::iter::once;
2
3use crate::{math::Real, prelude::*};
4use bevy::{platform::collections::HashMap, prelude::*};
5use itertools::Either;
6
7/// A component that will automatically generate [`Collider`]s on its descendants at runtime.
8/// The type of the generated collider can be specified using [`ColliderConstructor`].
9/// This supports computing the shape dynamically from the mesh, in which case only the descendants
10/// with a [`Mesh`] will have colliders generated.
11///
12/// In contrast to [`ColliderConstructor`], this component will *not* generate a collider on its own entity.
13///
14/// If this component is used on a scene, such as one spawned by a `WorldAssetRoot`, it will
15/// wait until the scene is loaded before generating colliders. Note that this requires
16/// the `bevy_scene` feature to be enabled.
17///
18/// The exact configuration for each descendant can be specified using the helper methods
19/// such as [`with_constructor_for_name`](Self::with_constructor_for_name).
20///
21/// This component will only override a pre-existing [`Collider`] component on a descendant entity
22/// when it has been explicitly mentioned in the `config`.
23///
24/// # See Also
25///
26/// For inserting colliders on the same entity, use [`ColliderConstructor`].
27///
28/// # Caveats
29///
30/// When a component has multiple ancestors with [`ColliderConstructorHierarchy`], the insertion order is undefined.
31///
32/// # Example
33///
34/// Below are some examples of using [`ColliderConstructorHierarchy`] to generate colliders
35/// for a glTF scene at runtime. Note that this requires the `bevy_scene` feature to be enabled.
36///
37/// ```
38#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
39#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
40/// use bevy::prelude::*;
41///
42/// fn setup(mut commands: Commands, mut assets: ResMut<AssetServer>) {
43///     let scene = assets.load("my_model.gltf#Scene0");
44///
45#[cfg_attr(
46    feature = "2d",
47    doc = "    // Spawn the scene and automatically generate circle colliders"
48)]
49#[cfg_attr(
50    feature = "3d",
51    doc = "    // Spawn the scene and automatically generate triangle mesh colliders"
52)]
53///     commands.spawn((
54///         WorldAssetRoot(scene.clone()),
55#[cfg_attr(
56    feature = "2d",
57    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::Circle { radius: 2.0 }),"
58)]
59#[cfg_attr(
60    feature = "3d",
61    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::TrimeshFromMesh),"
62)]
63///     ));
64///
65///     // Specify configuration for specific meshes by name
66///     commands.spawn((
67///         WorldAssetRoot(scene.clone()),
68#[cfg_attr(
69    feature = "2d",
70    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::Circle { radius: 2.0 })
71            .with_constructor_for_name(\"Tree\", ColliderConstructor::Rectangle { x_length: 1.0, y_length: 2.0 })"
72)]
73#[cfg_attr(
74    feature = "3d",
75    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::TrimeshFromMesh)
76            .with_constructor_for_name(\"Tree\", ColliderConstructor::ConvexHullFromMesh)"
77)]
78///             .with_layers_for_name("Tree", CollisionLayers::from_bits(0b0010, 0b1111))
79///             .with_density_for_name("Tree", 2.5),
80///     ));
81///
82///     // Only generate colliders for specific meshes by name
83///     commands.spawn((
84///         WorldAssetRoot(scene.clone()),
85///         ColliderConstructorHierarchy::new(None)
86#[cfg_attr(
87    feature = "2d",
88    doc = "            .with_constructor_for_name(\"Tree\", ColliderConstructor::Circle { radius: 2.0 }),"
89)]
90#[cfg_attr(
91    feature = "3d",
92    doc = "            .with_constructor_for_name(\"Tree\", ColliderConstructor::ConvexHullFromMesh),"
93)]
94///     ));
95///
96///     // Generate colliders for everything except specific meshes by name
97///     commands.spawn((
98///         WorldAssetRoot(scene),
99#[cfg_attr(
100    feature = "2d",
101    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::Circle { radius: 2.0 })
102            .without_constructor_for_name(\"Tree\"),"
103)]
104#[cfg_attr(
105    feature = "3d",
106    doc = "        ColliderConstructorHierarchy::new(ColliderConstructor::TrimeshFromMeshWithConfig(
107             TrimeshFlags::MERGE_DUPLICATE_VERTICES
108        ))
109        .without_constructor_for_name(\"Tree\"),"
110)]
111///     ));
112/// }
113/// ```
114#[derive(Component, Clone, Debug, Default, PartialEq, Reflect)]
115#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
116#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
117#[reflect(Component, Debug, PartialEq, Default)]
118pub struct ColliderConstructorHierarchy {
119    /// The default collider type used for each entity that isn't included in [`config`](Self::config).
120    /// If `None`, all entities except the ones in [`config`](Self::config) will be skipped.
121    pub default_constructor: Option<ColliderConstructor>,
122    /// The default [`CollisionLayers`] used for colliders in the hierarchy.
123    ///
124    /// [`CollisionLayers::default()`] by default, with the first layer and all filters.
125    pub default_layers: CollisionLayers,
126    /// The default [`ColliderDensity`] used for colliders in the hierarchy.
127    ///
128    /// `1.0` by default.
129    pub default_density: ColliderDensity,
130    /// Specifies data like the [`ColliderConstructor`] and [`CollisionLayers`] for entities
131    /// in the hierarchy by `Name`. Entries with a `None` value will be skipped.
132    ///
133    /// For the entities not found in this `HashMap`, [`default_constructor`](Self::default_constructor),
134    /// [`default_layers`](Self::default_layers), and [`default_density`](Self::default_density) will be used instead.
135    pub config: HashMap<String, Option<ColliderConstructorHierarchyConfig>>,
136}
137
138/// Triggered when a [`ColliderConstructor`] successfully inserted a [`Collider`].
139///
140/// The event is not triggered when the [`ColliderConstructor`] failed to construct the [`Collider`]
141/// or when there was already a [`Collider`] on the entity.
142#[derive(EntityEvent, Clone, Copy, Debug, PartialEq)]
143#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
144pub struct ColliderConstructorReady {
145    /// The entity that held the [`ColliderConstructor`].
146    pub entity: Entity,
147}
148
149/// Triggered when a [`ColliderConstructorHierarchy`] finished inserting all its [`Collider`]s.
150///
151/// Note that the event will still be triggered when when the hierarchy had no colliders to insert
152/// or failed to insert all of them, so this event is not a guarantee that there are actually
153/// any colliders in the scene.
154#[derive(EntityEvent, Clone, Copy, Debug, PartialEq)]
155#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
156pub struct ColliderConstructorHierarchyReady {
157    /// The entity that held the [`ColliderConstructorHierarchy`].
158    pub entity: Entity,
159}
160
161impl ColliderConstructorHierarchy {
162    /// Creates a new [`ColliderConstructorHierarchy`] with the default [`ColliderConstructor`] used for
163    /// generating colliders set to the given `default_constructor`.
164    ///
165    /// If the given constructor type is `None`, collider generation is skipped
166    /// for all entities in the hierarchy except the ones in [`config`](Self::config).
167    ///
168    /// Collider constructors can be specified for individual entities using
169    /// [`with_constructor_for_name`](Self::with_constructor_for_name).
170    pub fn new(default_constructor: impl Into<Option<ColliderConstructor>>) -> Self {
171        Self {
172            default_constructor: default_constructor.into(),
173            default_layers: CollisionLayers::default(),
174            default_density: ColliderDensity(1.0),
175            config: default(),
176        }
177    }
178
179    /// Specifies the default [`CollisionLayers`] used for colliders not included in [`ColliderConstructorHierarchy::config`].
180    pub fn with_default_layers(mut self, layers: CollisionLayers) -> Self {
181        self.default_layers = layers;
182        self
183    }
184
185    /// Specifies the default [`ColliderDensity`] used for colliders not included in [`ColliderConstructorHierarchy::config`].
186    pub fn with_default_density(mut self, density: impl Into<ColliderDensity>) -> Self {
187        self.default_density = density.into();
188        self
189    }
190
191    /// Specifies the [`ColliderConstructor`] used for an entity with the given `name`.
192    pub fn with_constructor_for_name(
193        mut self,
194        name: &str,
195        constructor: ColliderConstructor,
196    ) -> Self {
197        if let Some(Some(data)) = self.config.get_mut(name) {
198            data.constructor = Some(constructor);
199        } else {
200            self.config.insert(
201                name.to_string(),
202                Some(ColliderConstructorHierarchyConfig {
203                    constructor: Some(constructor),
204                    ..default()
205                }),
206            );
207        }
208        self
209    }
210
211    /// Specifies the [`CollisionLayers`] used for an entity with the given `name`.
212    pub fn with_layers_for_name(self, name: &str, layers: CollisionLayers) -> Self {
213        self.with_config_for_name(name, |config| config.layers = Some(layers))
214    }
215
216    /// Specifies the [`ColliderDensity`] used for an entity with the given `name`.
217    pub fn with_density_for_name(self, name: &str, density: impl Into<ColliderDensity>) -> Self {
218        let density = density.into();
219        self.with_config_for_name(name, |config| config.density = Some(density))
220    }
221
222    /// Sets the [`ColliderConstructor`] for the entity associated with the given `name` to `None`,
223    /// skipping collider generation for it.
224    pub fn without_constructor_for_name(mut self, name: &str) -> Self {
225        self.config.insert(name.to_string(), None);
226        self
227    }
228
229    fn with_config_for_name(
230        mut self,
231        name: &str,
232        mut mutate_config: impl FnMut(&mut ColliderConstructorHierarchyConfig),
233    ) -> Self {
234        if let Some(Some(config)) = self.config.get_mut(name) {
235            mutate_config(config);
236        } else {
237            let mut config = ColliderConstructorHierarchyConfig::default();
238            mutate_config(&mut config);
239            self.config.insert(name.to_string(), Some(config));
240        }
241        self
242    }
243}
244
245/// Configuration for a specific collider generated from a scene using [`ColliderConstructorHierarchy`].
246#[derive(Clone, Debug, Default, PartialEq, Reflect)]
247#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
248#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
249#[reflect(Debug, Default, PartialEq)]
250pub struct ColliderConstructorHierarchyConfig {
251    /// The type of collider generated for the mesh.
252    ///
253    /// If `None`, [`ColliderConstructorHierarchy::default_constructor`] is used instead.
254    pub constructor: Option<ColliderConstructor>,
255    /// The [`CollisionLayers`] used for this collider.
256    ///
257    /// If `None`, [`ColliderConstructorHierarchy::default_layers`] is used instead.
258    pub layers: Option<CollisionLayers>,
259    /// The [`ColliderDensity`] used for this collider.
260    ///
261    /// If `None`, [`ColliderConstructorHierarchy::default_density`] is used instead.
262    pub density: Option<ColliderDensity>,
263}
264
265/// A component that will automatically generate a [`Collider`] at runtime using [`Collider::try_from_constructor`].
266/// Enabling the `collider-from-mesh` feature activates support for computing the shape dynamically from the mesh attached to the same entity.
267///
268/// Since [`Collider`] is not [`Reflect`], you can use this type to statically specify a collider's shape instead.
269///
270/// This component will never override a pre-existing [`Collider`] component on the same entity.
271///
272/// # See Also
273///
274/// For inserting colliders on an entity's descendants, use [`ColliderConstructorHierarchy`].
275///
276/// # Panics
277///
278/// The system handling the generation of colliders will panic if the specified [`ColliderConstructor`]
279/// requires a mesh, but the entity does not have a `Handle<Mesh>` component.
280///
281/// # Example
282///
283/// ```
284#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
285#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
286/// use bevy::prelude::*;
287///
288/// fn setup(mut commands: Commands, mut assets: ResMut<AssetServer>, mut meshes: Assets<Mesh>) {
289#[cfg_attr(feature = "2d", doc = "     // Spawn a circle with radius 2")]
290#[cfg_attr(
291    feature = "3d",
292    doc = "    // Spawn a cube with a convex hull collider generated from the mesh"
293)]
294///     commands.spawn((
295#[cfg_attr(
296    feature = "2d",
297    doc = "        ColliderConstructor::Circle { radius: 2.0 },"
298)]
299#[cfg_attr(
300    feature = "3d",
301    doc = "        ColliderConstructor::ConvexHullFromMesh,"
302)]
303///         Mesh3d(meshes.add(Cuboid::default())),
304///     ));
305/// }
306/// ```
307#[derive(Clone, Debug, PartialEq, Reflect, Component)]
308#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
309#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
310#[cfg_attr(feature = "collider-from-mesh", derive(Default))]
311#[cfg_attr(feature = "collider-from-mesh", reflect(Default))]
312#[reflect(Debug, Component, PartialEq)]
313#[reflect(no_field_bounds)]
314#[non_exhaustive]
315#[allow(missing_docs)]
316pub enum ColliderConstructor {
317    /// Constructs a collider with [`Collider::circle`].
318    #[cfg(feature = "2d")]
319    Circle { radius: f32 },
320    /// Constructs a collider with [`Collider::sphere`].
321    #[cfg(feature = "3d")]
322    Sphere { radius: f32 },
323    /// Constructs a collider with [`Collider::ellipse`].
324    #[cfg(feature = "2d")]
325    Ellipse { half_width: f32, half_height: f32 },
326    /// Constructs a collider with [`Collider::rectangle`].
327    #[cfg(feature = "2d")]
328    Rectangle { x_length: f32, y_length: f32 },
329    /// Constructs a collider with [`Collider::cuboid`].
330    #[cfg(feature = "3d")]
331    Cuboid {
332        x_length: f32,
333        y_length: f32,
334        z_length: f32,
335    },
336    /// Constructs a collider with [`Collider::round_rectangle`].
337    #[cfg(feature = "2d")]
338    RoundRectangle {
339        x_length: f32,
340        y_length: f32,
341        border_radius: f32,
342    },
343    /// Constructs a collider with [`Collider::round_cuboid`].
344    #[cfg(feature = "3d")]
345    RoundCuboid {
346        x_length: f32,
347        y_length: f32,
348        z_length: f32,
349        border_radius: f32,
350    },
351    /// Constructs a collider with [`Collider::cylinder`].
352    #[cfg(feature = "3d")]
353    Cylinder { radius: f32, height: f32 },
354    /// Constructs a collider with [`Collider::cone`].
355    #[cfg(feature = "3d")]
356    Cone { radius: f32, height: f32 },
357    /// Constructs a collider with [`Collider::capsule`].
358    Capsule { radius: f32, height: f32 },
359    /// Constructs a collider with [`Collider::capsule_endpoints`].
360    CapsuleEndpoints { radius: f32, a: Vector, b: Vector },
361    /// Constructs a collider with [`Collider::half_space`].
362    HalfSpace { outward_normal: Vector },
363    /// Constructs a collider with [`Collider::segment`].
364    Segment { a: Vector, b: Vector },
365    /// Constructs a collider with [`Collider::triangle`].
366    Triangle { a: Vector, b: Vector, c: Vector },
367    /// Constructs a collider with [`Collider::regular_polygon`].
368    #[cfg(feature = "2d")]
369    RegularPolygon { circumradius: f32, sides: u32 },
370    /// Constructs a collider with [`Collider::polyline`].
371    Polyline {
372        vertices: Vec<RVector>,
373        indices: Option<Vec<[u32; 2]>>,
374    },
375    /// Constructs a collider with [`Collider::trimesh`].
376    Trimesh {
377        vertices: Vec<RVector>,
378        indices: Vec<[u32; 3]>,
379    },
380    /// Constructs a collider with [`Collider::trimesh_with_config`].
381    TrimeshWithConfig {
382        vertices: Vec<RVector>,
383        indices: Vec<[u32; 3]>,
384        flags: TrimeshFlags,
385    },
386    /// Constructs a collider with [`Collider::convex_decomposition`].
387    #[cfg(feature = "2d")]
388    ConvexDecomposition {
389        vertices: Vec<RVector>,
390        indices: Vec<[u32; 2]>,
391    },
392    /// Constructs a collider with [`Collider::convex_decomposition`].
393    #[cfg(feature = "3d")]
394    ConvexDecomposition {
395        vertices: Vec<RVector>,
396        indices: Vec<[u32; 3]>,
397    },
398    /// Constructs a collider with [`Collider::convex_decomposition_with_config`].
399    #[cfg(feature = "2d")]
400    ConvexDecompositionWithConfig {
401        vertices: Vec<RVector>,
402        indices: Vec<[u32; 2]>,
403        params: VhacdParameters,
404    },
405    /// Constructs a collider with [`Collider::convex_decomposition_with_config`].
406    #[cfg(feature = "3d")]
407    ConvexDecompositionWithConfig {
408        vertices: Vec<RVector>,
409        indices: Vec<[u32; 3]>,
410        params: VhacdParameters,
411    },
412    /// Constructs a collider with [`Collider::convex_hull`].
413    #[cfg(feature = "2d")]
414    ConvexHull { points: Vec<RVector> },
415    /// Constructs a collider with [`Collider::convex_hull`].
416    #[cfg(feature = "3d")]
417    ConvexHull { points: Vec<RVector> },
418    /// Constructs a collider with [`Collider::convex_polyline`].
419    #[cfg(feature = "2d")]
420    ConvexPolyline { points: Vec<RVector> },
421    /// Constructs a collider with [`Collider::voxels`].
422    Voxels {
423        voxel_size: Vector,
424        grid_coordinates: Vec<IVector>,
425    },
426    /// Constructs a collider with [`Collider::voxelized_polyline`].
427    #[cfg(feature = "2d")]
428    VoxelizedPolyline {
429        vertices: Vec<RVector>,
430        indices: Vec<[u32; 2]>,
431        voxel_size: f32,
432        fill_mode: FillMode,
433    },
434    /// Constructs a collider with [`Collider::voxelized_trimesh`].
435    #[cfg(feature = "3d")]
436    VoxelizedTrimesh {
437        vertices: Vec<RVector>,
438        indices: Vec<[u32; 3]>,
439        voxel_size: f32,
440        fill_mode: FillMode,
441    },
442    /// Constructs a collider with [`Collider::heightfield`].
443    #[cfg(feature = "2d")]
444    Heightfield { heights: Vec<Real>, scale: Vector },
445    /// Constructs a collider with [`Collider::heightfield`].
446    #[cfg(feature = "3d")]
447    Heightfield {
448        heights: Vec<Vec<Real>>,
449        scale: Vector,
450    },
451    /// Constructs a collider with [`Collider::trimesh_from_mesh`].
452    #[cfg(feature = "collider-from-mesh")]
453    #[default]
454    TrimeshFromMesh,
455    /// Constructs a collider with [`Collider::trimesh_from_mesh_with_config`].
456    #[cfg(all(
457        feature = "3d",
458        feature = "collider-from-mesh",
459        feature = "default-collider"
460    ))]
461    TrimeshFromMeshWithConfig(TrimeshFlags),
462    /// Constructs a collider with [`Collider::convex_decomposition_from_mesh`].
463    #[cfg(feature = "collider-from-mesh")]
464    ConvexDecompositionFromMesh,
465    /// Constructs a collider with [`Collider::convex_decomposition_from_mesh_with_config`].
466    #[cfg(all(
467        feature = "3d",
468        feature = "collider-from-mesh",
469        feature = "default-collider"
470    ))]
471    ConvexDecompositionFromMeshWithConfig(VhacdParameters),
472    /// Constructs a collider with [`Collider::convex_hull_from_mesh`].
473    #[cfg(feature = "collider-from-mesh")]
474    ConvexHullFromMesh,
475    /// Constructs a collider with [`Collider::voxelized_trimesh_from_mesh`].
476    #[cfg(feature = "collider-from-mesh")]
477    VoxelizedTrimeshFromMesh {
478        voxel_size: f32,
479        fill_mode: FillMode,
480    },
481    /// Constructs a collider with [`Collider::compound`].
482    Compound(Vec<(Position, Rotation, ColliderConstructor)>),
483}
484
485impl ColliderConstructor {
486    /// Returns `true` if the collider type requires a mesh to be generated.
487    #[cfg(feature = "collider-from-mesh")]
488    pub fn requires_mesh(&self) -> bool {
489        matches!(
490            self,
491            Self::TrimeshFromMesh
492                | Self::TrimeshFromMeshWithConfig(_)
493                | Self::ConvexDecompositionFromMesh
494                | Self::ConvexDecompositionFromMeshWithConfig(_)
495                | Self::ConvexHullFromMesh
496                | Self::VoxelizedTrimeshFromMesh { .. }
497        )
498    }
499
500    /// Construct a [`ColliderConstructor::Compound`] from arbitrary [`Position`] and [`Rotation`] representations.
501    pub fn compound<P, R>(shapes: Vec<(P, R, ColliderConstructor)>) -> Self
502    where
503        P: Into<Position>,
504        R: Into<Rotation>,
505    {
506        Self::Compound(
507            shapes
508                .into_iter()
509                .map(|(pos, rot, constructor)| (pos.into(), rot.into(), constructor))
510                .collect(),
511        )
512    }
513
514    pub(crate) fn flatten_compound_constructors(
515        constructors: Vec<(Position, Rotation, ColliderConstructor)>,
516    ) -> Vec<(Position, Rotation, ColliderConstructor)> {
517        constructors
518            .into_iter()
519            .flat_map(|(pos, rot, constructor)| match constructor {
520                ColliderConstructor::Compound(nested) => {
521                    Either::Left(Self::flatten_compound_constructors(nested).into_iter().map(
522                        move |(nested_pos, nested_rot, nested_constructor)| {
523                            (
524                                Position(pos.0 + rot.real() * nested_pos.0),
525                                rot * nested_rot,
526                                nested_constructor,
527                            )
528                        },
529                    ))
530                }
531                other => Either::Right(once((pos, rot, other))),
532            })
533            .collect()
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540    #[cfg(feature = "bevy_scene")]
541    use bevy::world_serialization::WorldSerializationPlugin;
542    use bevy::{ecs::query::QueryData, mesh::MeshPlugin};
543
544    #[test]
545    fn collider_constructor_requires_no_mesh_on_primitive() {
546        let mut app = create_test_app();
547
548        let entity = app.world_mut().spawn(PRIMITIVE_COLLIDER.clone()).id();
549
550        app.update();
551
552        assert!(app.query_ok::<&Collider>(entity));
553        assert!(app.query_err::<&ColliderConstructor>(entity));
554    }
555
556    #[cfg(feature = "collider-from-mesh")]
557    #[test]
558    #[should_panic]
559    fn collider_constructor_requires_mesh_on_computed() {
560        let mut app = create_test_app();
561
562        app.world_mut().spawn(COMPUTED_COLLIDER.clone());
563
564        app.update();
565    }
566
567    #[cfg(feature = "collider-from-mesh")]
568    #[test]
569    fn collider_constructor_converts_mesh_on_computed() {
570        let mut app = create_test_app();
571
572        let mesh = app.add_mesh();
573        let entity = app
574            .world_mut()
575            .spawn((COMPUTED_COLLIDER.clone(), Mesh3d(mesh)))
576            .id();
577
578        app.update();
579
580        assert!(app.query_ok::<&Collider>(entity));
581        assert!(app.query_ok::<&Mesh3d>(entity));
582        assert!(app.query_err::<&ColliderConstructor>(entity));
583    }
584
585    #[test]
586    fn collider_constructor_hierarchy_does_nothing_on_self_with_primitive() {
587        let mut app = create_test_app();
588
589        let entity = app
590            .world_mut()
591            .spawn(ColliderConstructorHierarchy::new(
592                PRIMITIVE_COLLIDER.clone(),
593            ))
594            .id();
595
596        app.update();
597
598        assert!(app.query_err::<&ColliderConstructorHierarchy>(entity));
599        assert!(app.query_err::<&Collider>(entity));
600    }
601
602    #[cfg(feature = "collider-from-mesh")]
603    #[test]
604    fn collider_constructor_hierarchy_does_nothing_on_self_with_computed() {
605        let mut app = create_test_app();
606
607        let mesh = app.add_mesh();
608        let entity = app
609            .world_mut()
610            .spawn((
611                ColliderConstructorHierarchy::new(COMPUTED_COLLIDER.clone()),
612                Mesh3d(mesh),
613            ))
614            .id();
615
616        app.update();
617
618        assert!(app.query_ok::<&Mesh3d>(entity));
619        assert!(app.query_err::<&ColliderConstructorHierarchy>(entity));
620        assert!(app.query_err::<&Collider>(entity));
621    }
622
623    #[cfg(feature = "collider-from-mesh")]
624    #[test]
625    fn collider_constructor_hierarchy_does_not_require_mesh_on_self_with_computed() {
626        let mut app = create_test_app();
627
628        let entity = app
629            .world_mut()
630            .spawn(ColliderConstructorHierarchy::new(COMPUTED_COLLIDER.clone()))
631            .id();
632
633        app.update();
634
635        assert!(app.query_err::<&Collider>(entity));
636        assert!(app.query_err::<&ColliderConstructorHierarchy>(entity));
637    }
638
639    #[test]
640    fn collider_constructor_hierarchy_inserts_primitive_colliders_on_all_descendants() {
641        let mut app = create_test_app();
642
643        // Hierarchy:
644        // - parent
645        //   - child1
646        //   - child2
647        //     - child3
648
649        let parent = app
650            .world_mut()
651            .spawn(ColliderConstructorHierarchy::new(
652                PRIMITIVE_COLLIDER.clone(),
653            ))
654            .id();
655        let child1 = app.world_mut().spawn(()).id();
656        let child2 = app.world_mut().spawn(()).id();
657        let child3 = app.world_mut().spawn(()).id();
658
659        app.world_mut()
660            .entity_mut(parent)
661            .add_children(&[child1, child2]);
662        app.world_mut().entity_mut(child2).add_children(&[child3]);
663
664        app.update();
665
666        // No entities should have ColliderConstructorHierarchy
667        assert!(app.query_err::<&ColliderConstructorHierarchy>(parent));
668        assert!(app.query_err::<&ColliderConstructorHierarchy>(child1));
669        assert!(app.query_err::<&ColliderConstructorHierarchy>(child2));
670        assert!(app.query_err::<&ColliderConstructorHierarchy>(child3));
671
672        assert!(app.query_err::<&Collider>(parent));
673        assert!(app.query_ok::<&Collider>(child1));
674        assert!(app.query_ok::<&Collider>(child2));
675        assert!(app.query_ok::<&Collider>(child3));
676    }
677
678    #[cfg(feature = "collider-from-mesh")]
679    #[test]
680    fn collider_constructor_hierarchy_inserts_computed_colliders_only_on_descendants_with_mesh() {
681        let mut app = create_test_app();
682        let mesh = Mesh3d(app.add_mesh());
683
684        // Hierarchy:
685        // - parent
686        //   - child1 (no mesh)
687        //   - child2 (no mesh)
688        //     - child3 (mesh)
689        //   - child4 (mesh)
690        //     - child5 (no mesh)
691        //   - child6 (mesh)
692        //   - child7 (mesh)
693        //     - child8 (mesh)
694
695        let parent = app
696            .world_mut()
697            .spawn(ColliderConstructorHierarchy::new(COMPUTED_COLLIDER.clone()))
698            .id();
699        let child1 = app.world_mut().spawn(()).id();
700        let child2 = app.world_mut().spawn(()).id();
701        let child3 = app.world_mut().spawn(mesh.clone()).id();
702        let child4 = app.world_mut().spawn(mesh.clone()).id();
703        let child5 = app.world_mut().spawn(()).id();
704        let child6 = app.world_mut().spawn(mesh.clone()).id();
705        let child7 = app.world_mut().spawn(mesh.clone()).id();
706        let child8 = app.world_mut().spawn(mesh.clone()).id();
707
708        app.world_mut()
709            .entity_mut(parent)
710            .add_children(&[child1, child2, child4, child6, child7]);
711        app.world_mut().entity_mut(child2).add_child(child3);
712        app.world_mut().entity_mut(child4).add_child(child5);
713        app.world_mut().entity_mut(child7).add_child(child8);
714
715        app.update();
716
717        // No entities should have ColliderConstructorHierarchy
718        assert!(app.query_err::<&ColliderConstructorHierarchy>(parent));
719        assert!(app.query_err::<&ColliderConstructorHierarchy>(child1));
720        assert!(app.query_err::<&ColliderConstructorHierarchy>(child2));
721        assert!(app.query_err::<&ColliderConstructorHierarchy>(child3));
722        assert!(app.query_err::<&ColliderConstructorHierarchy>(child4));
723        assert!(app.query_err::<&ColliderConstructorHierarchy>(child5));
724        assert!(app.query_err::<&ColliderConstructorHierarchy>(child6));
725        assert!(app.query_err::<&ColliderConstructorHierarchy>(child7));
726        assert!(app.query_err::<&ColliderConstructorHierarchy>(child8));
727
728        assert!(app.query_err::<&Collider>(parent));
729        assert!(app.query_err::<&Collider>(child1));
730        assert!(app.query_err::<&Collider>(child2));
731        assert!(app.query_ok::<&Collider>(child3));
732        assert!(app.query_ok::<&Collider>(child4));
733        assert!(app.query_err::<&Collider>(child5));
734        assert!(app.query_ok::<&Collider>(child6));
735        assert!(app.query_ok::<&Collider>(child7));
736        assert!(app.query_ok::<&Collider>(child8));
737    }
738
739    #[cfg(all(feature = "collider-from-mesh", feature = "bevy_scene"))]
740    #[test]
741    #[cfg_attr(
742        target_os = "linux",
743        ignore = "The plugin setup requires access to the GPU, which is not available in the linux test environment"
744    )]
745    fn collider_constructor_hierarchy_inserts_correct_configs_on_scene() {
746        use bevy::gltf::GltfMeshName;
747        use parry::shape::ShapeType;
748
749        #[derive(Resource)]
750        struct SceneReady;
751
752        let mut app = create_gltf_test_app();
753
754        app.add_observer(
755            |_trigger: On<bevy::world_serialization::WorldInstanceReady>,
756             mut commands: Commands| {
757                commands.insert_resource(SceneReady);
758            },
759        );
760
761        let scene_handle = app
762            .world_mut()
763            .resource_mut::<AssetServer>()
764            .load("ferris.glb#Scene0");
765
766        let hierarchy = app
767            .world_mut()
768            .spawn((
769                WorldAssetRoot(scene_handle),
770                ColliderConstructorHierarchy::new(ColliderConstructor::ConvexDecompositionFromMesh)
771                    // Use a primitive collider for the left arm.
772                    .with_constructor_for_name("armL_mesh.ferris_material", PRIMITIVE_COLLIDER)
773                    .with_density_for_name("armL_mesh.ferris_material", 2.0)
774                    // Remove the right arm. Don't worry, crabs can regrow lost limbs!
775                    .without_constructor_for_name("armR_mesh.ferris_material"),
776                RigidBody::Dynamic,
777            ))
778            .id();
779
780        let mut counter = 0;
781        loop {
782            if app.world().contains_resource::<SceneReady>() {
783                break;
784            }
785            app.update();
786            counter += 1;
787            if counter > 1000 {
788                panic!("WorldInstanceReady was never triggered");
789            }
790        }
791        app.update();
792
793        assert!(app.query_err::<&ColliderConstructorHierarchy>(hierarchy));
794        assert!(app.query_err::<&Collider>(hierarchy));
795
796        // Check densities
797        let densities: HashMap<_, _> = app
798            .world_mut()
799            .query::<(&GltfMeshName, &ColliderDensity)>()
800            .iter(app.world())
801            .map(|(name, density)| (name.to_string(), density.0))
802            .collect();
803
804        assert_eq!(densities["eyes_mesh"], 1.0);
805        assert_eq!(densities["armL_mesh"], 2.0);
806        assert!(densities.get("armR_mesh").is_none());
807
808        // Check collider shape types
809        let colliders: HashMap<_, _> = app
810            .world_mut()
811            .query::<(&GltfMeshName, &Collider)>()
812            .iter(app.world())
813            .map(|(name, collider)| (name.to_string(), collider))
814            .collect();
815
816        assert_eq!(
817            colliders["eyes_mesh"].shape().shape_type(),
818            ShapeType::Compound
819        );
820        assert_eq!(
821            colliders["armL_mesh"].shape().shape_type(),
822            ShapeType::Capsule
823        );
824        assert!(colliders.get("armR_mesh").is_none());
825    }
826
827    const PRIMITIVE_COLLIDER: ColliderConstructor = ColliderConstructor::Capsule {
828        height: 1.0,
829        radius: 0.5,
830    };
831
832    #[cfg(feature = "collider-from-mesh")]
833    const COMPUTED_COLLIDER: ColliderConstructor = ColliderConstructor::TrimeshFromMesh;
834
835    fn create_test_app() -> App {
836        let mut app = App::new();
837        app.add_plugins((
838            MinimalPlugins,
839            AssetPlugin::default(),
840            #[cfg(feature = "bevy_scene")]
841            WorldSerializationPlugin,
842            MeshPlugin,
843            PhysicsPlugins::default(),
844        ));
845
846        app
847    }
848
849    #[cfg(all(feature = "collider-from-mesh", feature = "bevy_scene"))]
850    fn create_gltf_test_app() -> App {
851        use bevy::{diagnostic::DiagnosticsPlugin, winit::WinitPlugin};
852
853        // Todo: it would be best to disable all rendering-related plugins,
854        // but we have so far not succeeded in finding the right plugin combination
855        // that still results in `WorldInstanceReady` being triggered.
856        let mut app = App::new();
857        app.add_plugins((
858            DefaultPlugins
859                .build()
860                .disable::<WinitPlugin>()
861                .disable::<DiagnosticsPlugin>(),
862            PhysicsPlugins::default(),
863        ));
864        app.finish();
865        app.cleanup();
866        app
867    }
868
869    trait AppExt {
870        fn query_ok<D: QueryData>(&mut self, entity: Entity) -> bool;
871        fn query_err<D: QueryData>(&mut self, entity: Entity) -> bool {
872            !self.query_ok::<D>(entity)
873        }
874
875        #[cfg(feature = "collider-from-mesh")]
876        fn add_mesh(&mut self) -> Handle<Mesh>;
877    }
878
879    impl AppExt for App {
880        fn query_ok<D: QueryData>(&mut self, entity: Entity) -> bool {
881            let mut query = self.world_mut().query::<D>();
882            let component = query.get(self.world(), entity);
883            component.is_ok()
884        }
885
886        #[cfg(feature = "collider-from-mesh")]
887        fn add_mesh(&mut self) -> Handle<Mesh> {
888            self.world_mut()
889                .get_resource_mut::<Assets<Mesh>>()
890                .unwrap()
891                .add(Mesh::from(Cuboid::default()))
892        }
893    }
894}