Skip to main content

rapier3d/geometry/
mod.rs

1//! Structures related to geometry: colliders, shapes, etc.
2
3#[cfg(feature = "alloc")]
4pub(crate) use self::broad_phase_bvh::DeferredBvhOptimize;
5#[cfg(feature = "alloc")]
6pub use self::broad_phase_bvh::{BroadPhaseBvh, BvhOptimizationStrategy};
7pub use self::broad_phase_pair_event::{BroadPhasePairEvent, ColliderPair};
8#[cfg(feature = "alloc")]
9pub use self::collider::{Collider, ColliderBuilder};
10#[cfg(feature = "alloc")]
11pub use self::collider_components::*;
12pub use self::collider_handle::ColliderHandle;
13#[cfg(feature = "alloc")]
14pub use self::collider_set::{ColliderSet, ModifiedColliders};
15#[cfg(feature = "alloc")]
16pub(crate) use self::contact_pair::ContactRecycleState;
17#[cfg(feature = "alloc")]
18pub(crate) use self::contact_pair::PairEventStatus;
19#[cfg(feature = "alloc")]
20pub(crate) use self::contact_pair::SOLVER_DYNAMIC_COLOR_COUNT;
21#[cfg(feature = "alloc")]
22pub(crate) use self::contact_pair::relative_pose_drift;
23#[cfg(feature = "alloc")]
24pub use self::contact_pair::{
25    ContactData, ContactId, ContactManifoldData, ContactPair, IntersectionPair, NEW_CONTACT_BIT,
26    SimdSolverContact, SolverContact, SolverContactGeneric, SolverContacts, SolverFlags, is_bouncy,
27    is_bouncy_simd,
28};
29#[cfg(feature = "alloc")]
30pub use self::interaction_graph::{
31    ColliderGraphIndex, InteractionGraph, RigidBodyGraphIndex, TemporaryInteractionIndex,
32};
33pub use self::interaction_groups::{Group, InteractionGroups, InteractionTestMode};
34#[cfg(feature = "alloc")]
35pub use self::mesh_converter::{MeshConverter, MeshConverterError};
36#[cfg(feature = "alloc")]
37pub use self::narrow_phase::NarrowPhase;
38#[cfg(feature = "alloc")]
39pub use parry::utils::Array2;
40
41pub use parry::bounding_volume::BoundingVolume;
42#[cfg(feature = "alloc")]
43pub use parry::partitioning::{Bvh, BvhBuildStrategy};
44#[cfg(feature = "alloc")]
45pub use parry::query::{PointQuery, PointQueryWithLocation, RayCast, TrackedContact};
46#[cfg(feature = "alloc")]
47pub use parry::shape::{SharedShape, VoxelState, VoxelType, Voxels};
48
49#[cfg(feature = "alloc")]
50use crate::math::{Real, Vector};
51
52/// A contact between two colliders.
53#[cfg(feature = "alloc")]
54pub type Contact = parry::query::TrackedContact<ContactData>;
55/// A contact manifold between two colliders.
56#[cfg(feature = "alloc")]
57pub type ContactManifold = parry::query::ContactManifold<ContactManifoldData, ContactData>;
58/// A segment shape.
59pub type Segment = parry::shape::Segment;
60/// A cuboid shape.
61pub type Cuboid = parry::shape::Cuboid;
62/// A triangle shape.
63pub type Triangle = parry::shape::Triangle;
64/// A ball shape.
65pub type Ball = parry::shape::Ball;
66/// A capsule shape.
67pub type Capsule = parry::shape::Capsule;
68/// A heightfield shape.
69#[cfg(feature = "alloc")]
70pub type HeightField = parry::shape::HeightField;
71/// A cylindrical shape.
72#[cfg(feature = "dim3")]
73pub type Cylinder = parry::shape::Cylinder;
74/// A cone shape.
75#[cfg(feature = "dim3")]
76pub type Cone = parry::shape::Cone;
77/// An axis-aligned bounding box.
78pub type Aabb = parry::bounding_volume::Aabb;
79/// A ray that can be cast against colliders.
80pub type Ray = parry::query::Ray;
81/// The intersection between a ray and a  collider.
82pub type RayIntersection = parry::query::RayIntersection;
83/// The projection of a point on a collider.
84pub type PointProjection = parry::query::PointProjection;
85/// The result of a shape-cast between two shapes.
86pub type ShapeCastHit = parry::query::ShapeCastHit;
87/// The default broad-phase implementation recommended for general-purpose usage.
88#[cfg(feature = "alloc")]
89pub type DefaultBroadPhase = BroadPhaseBvh;
90
91bitflags::bitflags! {
92    /// Flags providing more information regarding a collision event.
93    #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
94    #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
95    pub struct CollisionEventFlags: u32 {
96        /// Flag set if at least one of the colliders involved in the
97        /// collision was a sensor when the event was fired.
98        const SENSOR = 0b0001;
99        /// Flag set if a `CollisionEvent::Stopped` was fired because
100        /// at least one of the colliders was removed.
101        const REMOVED = 0b0010;
102    }
103}
104
105#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
106#[derive(Copy, Clone, Hash, Debug)]
107/// Events triggered when two colliders start or stop touching.
108///
109/// Receive these through an [`EventHandler`](crate::pipeline::EventHandler) implementation.
110/// At least one collider must have [`ActiveEvents::COLLISION_EVENTS`](crate::pipeline::ActiveEvents::COLLISION_EVENTS) enabled.
111///
112/// Use for:
113/// - Trigger zones (player entered/exited area)
114/// - Collectible items (player touched coin)
115/// - Sound effects (objects started colliding)
116/// - Game logic based on contact state
117///
118/// # Example
119/// ```
120/// # use rapier3d::prelude::*;
121/// # let h1 = ColliderHandle::from_raw_parts(0, 0);
122/// # let h2 = ColliderHandle::from_raw_parts(1, 0);
123/// # let event = CollisionEvent::Started(h1, h2, CollisionEventFlags::empty());
124/// match event {
125///     CollisionEvent::Started(h1, h2, flags) => {
126///         println!("Colliders {:?} and {:?} started touching", h1, h2);
127///         if flags.contains(CollisionEventFlags::SENSOR) {
128///             println!("At least one is a sensor!");
129///         }
130///     }
131///     CollisionEvent::Stopped(h1, h2, _) => {
132///         println!("Colliders {:?} and {:?} stopped touching", h1, h2);
133///     }
134/// }
135/// ```
136pub enum CollisionEvent {
137    /// Two colliders just started touching this frame.
138    Started(ColliderHandle, ColliderHandle, CollisionEventFlags),
139    /// Two colliders just stopped touching this frame.
140    Stopped(ColliderHandle, ColliderHandle, CollisionEventFlags),
141}
142
143impl CollisionEvent {
144    /// Returns `true` if this is a Started event (colliders began touching).
145    pub fn started(self) -> bool {
146        matches!(self, CollisionEvent::Started(..))
147    }
148
149    /// Returns `true` if this is a Stopped event (colliders stopped touching).
150    pub fn stopped(self) -> bool {
151        matches!(self, CollisionEvent::Stopped(..))
152    }
153
154    /// Returns the handle of the first collider in this collision.
155    pub fn collider1(self) -> ColliderHandle {
156        match self {
157            Self::Started(h, _, _) | Self::Stopped(h, _, _) => h,
158        }
159    }
160
161    /// Returns the handle of the second collider in this collision.
162    pub fn collider2(self) -> ColliderHandle {
163        match self {
164            Self::Started(_, h, _) | Self::Stopped(_, h, _) => h,
165        }
166    }
167
168    /// Was at least one of the colliders involved in the collision a sensor?
169    pub fn sensor(self) -> bool {
170        match self {
171            Self::Started(_, _, f) | Self::Stopped(_, _, f) => {
172                f.contains(CollisionEventFlags::SENSOR)
173            }
174        }
175    }
176
177    /// Was at least one of the colliders involved in the collision removed?
178    pub fn removed(self) -> bool {
179        match self {
180            Self::Started(_, _, f) | Self::Stopped(_, _, f) => {
181                f.contains(CollisionEventFlags::REMOVED)
182            }
183        }
184    }
185}
186
187#[cfg(feature = "alloc")]
188#[derive(Copy, Clone, PartialEq, Debug, Default)]
189/// Event occurring when the sum of the magnitudes of the contact forces
190/// between two colliders exceed a threshold.
191pub struct ContactForceEvent {
192    /// The first collider involved in the contact.
193    pub collider1: ColliderHandle,
194    /// The second collider involved in the contact.
195    pub collider2: ColliderHandle,
196    /// The sum of all the forces between the two colliders.
197    pub total_force: Vector,
198    /// The sum of the magnitudes of each force between the two colliders.
199    ///
200    /// Note that this is **not** the same as the magnitude of `self.total_force`.
201    /// Here we are summing the magnitude of all the forces, instead of taking
202    /// the magnitude of their sum.
203    pub total_force_magnitude: Real,
204    /// The world-space (unit) direction of the force with strongest magnitude.
205    pub max_force_direction: Vector,
206    /// The magnitude of the largest force at a contact point of this contact pair.
207    pub max_force_magnitude: Real,
208    /// Is this the first step the pair's total force exceeded its threshold?
209    ///
210    /// `true` on the step the force crosses the pair's
211    /// [`Collider::contact_force_event_threshold`] coming from below (or from not
212    /// touching), `false` while it stays above on consecutive steps. The status resets
213    /// when the force drops back below the threshold or the colliders separate, so the
214    /// next crossing reports `true` again. Note that this is about the *force*
215    /// threshold, not contact newness: a pair can touch gently for many steps (emitting
216    /// no force event) before its first `started` event.
217    pub started: bool,
218}
219
220#[cfg(feature = "alloc")]
221impl ContactForceEvent {
222    /// Init a contact force event from a contact pair.
223    pub fn from_contact_pair(dt: Real, pair: &ContactPair, total_force_magnitude: Real) -> Self {
224        let mut result = ContactForceEvent {
225            collider1: pair.collider1,
226            collider2: pair.collider2,
227            total_force_magnitude,
228            // The pair's status is updated only after the event handlers ran, so at
229            // this point it still holds the previous step's value.
230            started: !pair
231                .event_status
232                .contains(PairEventStatus::INITIAL_FORCE_THRESHOLD_EVENT_EMITTED),
233            ..ContactForceEvent::default()
234        };
235
236        for m in pair.solver_manifolds() {
237            let mut total_manifold_impulse = 0.0;
238            for pt in m.contacts() {
239                total_manifold_impulse += pt.data.impulse;
240
241                if pt.data.impulse > result.max_force_magnitude {
242                    result.max_force_magnitude = pt.data.impulse;
243                    result.max_force_direction = m.data.normal;
244                }
245            }
246
247            result.total_force += m.data.normal * total_manifold_impulse;
248        }
249
250        let inv_dt = crate::utils::inv(dt);
251        // NOTE: convert impulses to forces. Note that we
252        //       don’t need to convert the `total_force_magnitude`
253        //       because it’s an input of this function already
254        //       assumed to be a force instead of an impulse.
255        result.total_force *= inv_dt;
256        result.max_force_magnitude *= inv_dt;
257        result
258    }
259}
260
261#[cfg(feature = "alloc")]
262pub(crate) use self::narrow_phase::ContactManifoldIndex;
263#[cfg(feature = "alloc")]
264pub use parry::shape::*;
265
266#[cfg(all(feature = "serde-serialize", feature = "alloc"))]
267pub(crate) fn default_persistent_query_dispatcher()
268-> alloc::sync::Arc<dyn parry::query::PersistentQueryDispatcher<ContactManifoldData, ContactData>> {
269    alloc::sync::Arc::new(parry::query::DefaultQueryDispatcher)
270}
271
272#[cfg(feature = "alloc")]
273mod collider_components;
274mod collider_handle;
275#[cfg(feature = "alloc")]
276pub(crate) mod contact_pair;
277#[cfg(feature = "alloc")]
278mod interaction_graph;
279mod interaction_groups;
280#[cfg(feature = "alloc")]
281mod narrow_phase;
282
283#[cfg(feature = "alloc")]
284mod broad_phase_bvh;
285mod broad_phase_pair_event;
286#[cfg(feature = "alloc")]
287mod collider;
288#[cfg(feature = "alloc")]
289mod collider_set;
290#[cfg(feature = "alloc")]
291mod mesh_converter;
292
293#[cfg(all(feature = "dim3", feature = "alloc"))]
294mod manifold_reduction;
295
296#[cfg(all(feature = "dim3", feature = "alloc"))]
297mod contact_clustering;