avian2d/spatial_query/
mod.rs

1//! Functionality for performing ray casts, shape casts, and other spatial queries.
2//!
3//! Spatial queries query the world for geometric information about [`Collider`s](Collider)
4//! and various types of intersections. Currently, four types of spatial queries are supported:
5//!
6//! - [Raycasts](#raycasting)
7//! - [Shapecasts](#shapecasting)
8//! - [Point projection](#point-projection)
9//! - [Intersection tests](#intersection-tests)
10//!
11//! All spatial queries can be done using the various methods provided by the [`SpatialQuery`] system parameter.
12//!
13//! Raycasting and shapecasting can also be done with a component-based approach using the [`RayCaster`] and
14//! [`ShapeCaster`] components. They enable performing casts every frame in a way that is often more convenient
15//! than the normal [`SpatialQuery`] methods. See their documentation for more information.
16//!
17//! # Raycasting
18//!
19//! **Raycasting** is a spatial query that finds intersections between colliders and a half-line. This can be used for
20//! a variety of things like getting information about the environment for character controllers and AI,
21//! and even rendering using ray tracing.
22//!
23//! For each hit during raycasting, the hit entity, a distance, and a normal will be stored in [`RayHitData`].
24//! The distance is the distance from the ray origin to the point of intersection, indicating how far the ray travelled.
25//!
26//! There are two ways to perform raycasts.
27//!
28//! 1. For simple raycasts, use the [`RayCaster`] component. It returns the results of the raycast
29//!    in the [`RayHits`] component every frame. It uses local coordinates, so it will automatically follow the entity
30//!    it's attached to or its parent.
31//! 2. When you need more control or don't want to cast every frame, use the raycasting methods provided by
32//!    [`SpatialQuery`], like [`cast_ray`](SpatialQuery::cast_ray), [`ray_hits`](SpatialQuery::ray_hits) or
33//!    [`ray_hits_callback`](SpatialQuery::ray_hits_callback).
34//!
35//! See the documentation of the components and methods for more information.
36//!
37//! A simple example using the component-based method looks like this:
38//!
39//! ```
40//! # #[cfg(feature = "2d")]
41//! # use avian2d::prelude::*;
42//! # #[cfg(feature = "3d")]
43//! use avian3d::prelude::*;
44//! use bevy::prelude::*;
45//!
46//! # #[cfg(all(feature = "3d", feature = "f32"))]
47//! fn setup(mut commands: Commands) {
48//!     // Spawn a ray caster at the center with the rays travelling right
49//!     commands.spawn(RayCaster::new(Vec3::ZERO, Dir3::X));
50//!     // ...spawn colliders and other things
51//! }
52//!
53//! # #[cfg(all(feature = "3d", feature = "f32"))]
54//! fn print_hits(query: Query<(&RayCaster, &RayHits)>) {
55//!     for (ray, hits) in &query {
56//!         // For the faster iterator that isn't sorted, use `.iter()`
57//!         for hit in hits.iter_sorted() {
58//!             println!(
59//!                 "Hit entity {} at {} with normal {}",
60//!                 hit.entity,
61//!                 ray.origin + *ray.direction * hit.distance,
62//!                 hit.normal,
63//!             );
64//!         }
65//!     }
66//! }
67//! ```
68//!
69//! To specify which colliders should be considered in the query, use a [spatial query filter](`SpatialQueryFilter`).
70//!
71//! # Shapecasting
72//!
73//! **Shapecasting** or **sweep testing** is a spatial query that finds intersections between colliders and a shape
74//! that is travelling along a half-line. It is very similar to [raycasting](#raycasting), but instead of a "point"
75//! we have an entire shape travelling along a half-line. One use case is determining how far an object can move
76//! before it hits the environment.
77//!
78//! For each hit during shapecasting, the hit entity, a distance, two world-space points of intersection and two world-space
79//! normals will be stored in [`ShapeHitData`]. The distance refers to how far the shape travelled before the initial hit.
80//!
81//! There are two ways to perform shapecasts.
82//!
83//! 1. For simple shapecasts, use the [`ShapeCaster`] component. It returns the results of the shapecast
84//!    in the [`ShapeHits`] component every frame. It uses local coordinates, so it will automatically follow the entity
85//!    it's attached to or its parent.
86//! 2. When you need more control or don't want to cast every frame, use the shapecasting methods provided by
87//!    [`SpatialQuery`], like [`cast_shape`](SpatialQuery::cast_shape), [`shape_hits`](SpatialQuery::shape_hits) or
88//!    [`shape_hits_callback`](SpatialQuery::shape_hits_callback).
89//!
90//! See the documentation of the components and methods for more information.
91//!
92//! A simple example using the component-based method looks like this:
93//!
94//! ```
95//! # #[cfg(feature = "2d")]
96//! # use avian2d::prelude::*;
97//! # #[cfg(feature = "3d")]
98//! use avian3d::prelude::*;
99//! use bevy::prelude::*;
100//!
101//! # #[cfg(all(feature = "3d", feature = "f32"))]
102//! fn setup(mut commands: Commands) {
103//!     // Spawn a shape caster with a sphere shape at the center travelling right
104//!     commands.spawn(ShapeCaster::new(
105//!         Collider::sphere(0.5), // Shape
106//!         Vec3::ZERO,            // Origin
107//!         Quat::default(),       // Shape rotation
108//!         Dir3::X                // Direction
109//!     ));
110//!     // ...spawn colliders and other things
111//! }
112//!
113//! fn print_hits(query: Query<(&ShapeCaster, &ShapeHits)>) {
114//!     for (shape_caster, hits) in &query {
115//!         for hit in hits.iter() {
116//!             println!("Hit entity {}", hit.entity);
117//!         }
118//!     }
119//! }
120//! ```
121//!
122//! To specify which colliders should be considered in the query, use a [spatial query filter](`SpatialQueryFilter`).
123//!
124//! # Point projection
125//!
126//! **Point projection** is a spatial query that projects a point on the closest collider. It returns the collider's
127//! entity, the projected point, and whether the point is inside of the collider.
128//!
129//! Point projection can be done with the [`project_point`](SpatialQuery::project_point) method of the [`SpatialQuery`]
130//! system parameter. See its documentation for more information.
131//!
132//! To specify which colliders should be considered in the query, use a [spatial query filter](`SpatialQueryFilter`).
133//!
134//! # Intersection tests
135//!
136//! **Intersection tests** are spatial queries that return the entities of colliders that are intersecting a given
137//! shape or area.
138//!
139//! There are three types of intersection tests. They are all methods of the [`SpatialQuery`] system parameter,
140//! and they all have callback variants that call a given callback on each intersection.
141//!
142//! - [`point_intersections`](SpatialQuery::point_intersections): Finds all entities with a collider that contains
143//!   the given point.
144//! - [`aabb_intersections_with_aabb`](SpatialQuery::aabb_intersections_with_aabb):
145//!   Finds all entities with a [`ColliderAabb`] that is intersecting the given [`ColliderAabb`].
146//! - [`shape_intersections`](SpatialQuery::shape_intersections): Finds all entities with a [collider](Collider)
147//!   that is intersecting the given shape.
148//!
149//! See the documentation of the components and methods for more information.
150//!
151//! To specify which colliders should be considered in the query, use a [spatial query filter](`SpatialQueryFilter`).
152
153mod query_filter;
154mod ray_caster;
155#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
156mod shape_caster;
157#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
158mod system_param;
159
160mod diagnostics;
161pub use diagnostics::SpatialQueryDiagnostics;
162
163pub use query_filter::*;
164pub use ray_caster::*;
165#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
166pub use shape_caster::*;
167#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
168pub use system_param::*;
169
170use crate::prelude::*;
171use bevy::prelude::*;
172
173/// Handles component-based [spatial queries](spatial_query) like [raycasting](spatial_query#raycasting)
174/// and [shapecasting](spatial_query#shapecasting) with [`RayCaster`] and [`ShapeCaster`].
175pub struct SpatialQueryPlugin;
176
177impl Plugin for SpatialQueryPlugin {
178    fn build(&self, app: &mut App) {
179        let physics_schedule = app
180            .get_schedule_mut(PhysicsSchedule)
181            .expect("add PhysicsSchedule first");
182
183        physics_schedule.add_systems(
184            (
185                update_ray_caster_positions,
186                #[cfg(all(
187                    feature = "default-collider",
188                    any(feature = "parry-f32", feature = "parry-f64")
189                ))]
190                (update_shape_caster_positions, raycast, shapecast).chain(),
191            )
192                .chain()
193                .in_set(PhysicsStepSystems::SpatialQuery),
194        );
195    }
196
197    fn finish(&self, app: &mut App) {
198        // Register timer diagnostics for spatial queries.
199        app.register_physics_diagnostics::<SpatialQueryDiagnostics>();
200    }
201}
202
203type RayCasterPositionQueryComponents = (
204    &'static mut RayCaster,
205    Option<&'static Position>,
206    Option<&'static Rotation>,
207    Option<&'static ChildOf>,
208    Option<&'static GlobalTransform>,
209);
210
211#[allow(clippy::type_complexity)]
212fn update_ray_caster_positions(
213    mut rays: Query<RayCasterPositionQueryComponents>,
214    parents: Query<
215        (
216            Option<&Position>,
217            Option<&Rotation>,
218            Option<&GlobalTransform>,
219        ),
220        With<Children>,
221    >,
222) {
223    for (mut ray, position, rotation, parent, transform) in &mut rays {
224        let origin = ray.origin;
225        let direction = ray.direction;
226
227        let global_position = position.copied().or(transform.map(Position::from));
228        let global_rotation = rotation.copied().or(transform.map(Rotation::from));
229
230        if let Some(global_position) = global_position {
231            ray.set_global_origin(global_position.0 + rotation.map_or(origin, |rot| rot * origin));
232        } else if parent.is_none() {
233            ray.set_global_origin(origin);
234        }
235
236        if let Some(global_rotation) = global_rotation {
237            let global_direction = global_rotation * ray.direction;
238            ray.set_global_direction(global_direction);
239        } else if parent.is_none() {
240            ray.set_global_direction(direction);
241        }
242
243        if let Some(Ok((parent_position, parent_rotation, parent_transform))) =
244            parent.map(|&ChildOf(parent)| parents.get(parent))
245        {
246            let parent_position = parent_position
247                .copied()
248                .or(parent_transform.map(Position::from));
249            let parent_rotation = parent_rotation
250                .copied()
251                .or(parent_transform.map(Rotation::from));
252
253            // Apply parent transformations
254            if global_position.is_none()
255                && let Some(position) = parent_position
256            {
257                let rotation = global_rotation.unwrap_or(parent_rotation.unwrap_or_default());
258                ray.set_global_origin(position.0 + rotation * origin);
259            }
260            if global_rotation.is_none()
261                && let Some(rotation) = parent_rotation
262            {
263                let global_direction = rotation * ray.direction;
264                ray.set_global_direction(global_direction);
265            }
266        }
267    }
268}
269
270#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
271type ShapeCasterPositionQueryComponents = (
272    &'static mut ShapeCaster,
273    Option<&'static Position>,
274    Option<&'static Rotation>,
275    Option<&'static ChildOf>,
276    Option<&'static GlobalTransform>,
277);
278
279#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
280#[allow(clippy::type_complexity)]
281fn update_shape_caster_positions(
282    mut shape_casters: Query<ShapeCasterPositionQueryComponents>,
283    parents: Query<
284        (
285            Option<&Position>,
286            Option<&Rotation>,
287            Option<&GlobalTransform>,
288        ),
289        With<Children>,
290    >,
291) {
292    for (mut shape_caster, position, rotation, parent, transform) in &mut shape_casters {
293        let origin = shape_caster.origin;
294        let shape_rotation = shape_caster.shape_rotation;
295        let direction = shape_caster.direction;
296
297        let global_position = position.copied().or(transform.map(Position::from));
298        let global_rotation = rotation.copied().or(transform.map(Rotation::from));
299
300        if let Some(global_position) = global_position {
301            shape_caster
302                .set_global_origin(global_position.0 + rotation.map_or(origin, |rot| rot * origin));
303        } else if parent.is_none() {
304            shape_caster.set_global_origin(origin);
305        }
306
307        if let Some(global_rotation) = global_rotation {
308            let global_direction = global_rotation * shape_caster.direction;
309            shape_caster.set_global_direction(global_direction);
310            #[cfg(feature = "2d")]
311            {
312                shape_caster
313                    .set_global_shape_rotation(shape_rotation + global_rotation.as_radians());
314            }
315            #[cfg(feature = "3d")]
316            {
317                shape_caster.set_global_shape_rotation(shape_rotation * global_rotation.0);
318            }
319        } else if parent.is_none() {
320            shape_caster.set_global_direction(direction);
321            #[cfg(feature = "2d")]
322            {
323                shape_caster.set_global_shape_rotation(shape_rotation);
324            }
325            #[cfg(feature = "3d")]
326            {
327                shape_caster.set_global_shape_rotation(shape_rotation);
328            }
329        }
330
331        if let Some(Ok((parent_position, parent_rotation, parent_transform))) =
332            parent.map(|&ChildOf(parent)| parents.get(parent))
333        {
334            let parent_position = parent_position
335                .copied()
336                .or(parent_transform.map(Position::from));
337            let parent_rotation = parent_rotation
338                .copied()
339                .or(parent_transform.map(Rotation::from));
340
341            // Apply parent transformations
342            if global_position.is_none()
343                && let Some(position) = parent_position
344            {
345                let rotation = global_rotation.unwrap_or(parent_rotation.unwrap_or_default());
346                shape_caster.set_global_origin(position.0 + rotation * origin);
347            }
348            if global_rotation.is_none()
349                && let Some(rotation) = parent_rotation
350            {
351                let global_direction = rotation * shape_caster.direction;
352                shape_caster.set_global_direction(global_direction);
353                #[cfg(feature = "2d")]
354                {
355                    shape_caster.set_global_shape_rotation(shape_rotation + rotation.as_radians());
356                }
357                #[cfg(feature = "3d")]
358                {
359                    shape_caster.set_global_shape_rotation(shape_rotation * rotation.0);
360                }
361            }
362        }
363    }
364}
365
366#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
367fn raycast(
368    mut rays: Query<(Entity, &mut RayCaster, &mut RayHits)>,
369    spatial_query: SpatialQuery,
370    mut diagnostics: ResMut<SpatialQueryDiagnostics>,
371) {
372    let start = crate::utils::Instant::now();
373
374    for (entity, mut ray_caster, mut hits) in &mut rays {
375        if ray_caster.enabled {
376            ray_caster.cast(entity, &mut hits, &spatial_query);
377        } else if !hits.is_empty() {
378            hits.clear();
379        }
380    }
381
382    diagnostics.update_ray_casters = start.elapsed();
383}
384
385#[cfg(any(feature = "parry-f32", feature = "parry-f64"))]
386fn shapecast(
387    mut shape_casters: Query<(Entity, &mut ShapeCaster, &mut ShapeHits)>,
388    spatial_query: SpatialQuery,
389    mut diagnostics: ResMut<SpatialQueryDiagnostics>,
390) {
391    let start = crate::utils::Instant::now();
392
393    for (entity, mut shape_caster, mut hits) in &mut shape_casters {
394        if shape_caster.enabled {
395            shape_caster.cast(entity, &mut hits, &spatial_query);
396        } else if !hits.is_empty() {
397            hits.clear();
398        }
399    }
400
401    diagnostics.update_shape_casters = start.elapsed();
402}