avian2d/collision/collider/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
//! Components, traits, and plugins related to collider functionality.
use crate::prelude::*;
use bevy::{
ecs::{
component::Mutable,
entity::{hash_set::EntityHashSet, EntityMapper, MapEntities},
system::{ReadOnlySystemParam, SystemParam, SystemParamItem},
},
prelude::*,
};
use derive_more::From;
mod backend;
pub use backend::{ColliderBackendPlugin, ColliderMarker};
pub mod collider_hierarchy;
pub mod collider_transform;
mod layers;
pub use layers::*;
/// The default [`Collider`] that uses Parry.
#[cfg(all(
feature = "default-collider",
any(feature = "parry-f32", feature = "parry-f64")
))]
mod parry;
#[cfg(all(
feature = "default-collider",
any(feature = "parry-f32", feature = "parry-f64")
))]
pub use parry::*;
mod world_query;
pub use world_query::*;
#[cfg(feature = "default-collider")]
mod constructor;
#[cfg(feature = "default-collider")]
pub use constructor::{
ColliderConstructor, ColliderConstructorHierarchy, ColliderConstructorHierarchyConfig,
};
/// A trait for creating colliders from other types.
pub trait IntoCollider<C: AnyCollider> {
/// Creates a collider from `self`.
fn collider(&self) -> C;
}
/// Context necessary to calculate [`ColliderAabb`]s for an [`AnyCollider`]
#[derive(Deref)]
pub struct AabbContext<'a, 'w, 's, T: ReadOnlySystemParam> {
/// The entity for which the aabb is being calculated
pub entity: Entity,
#[deref]
item: &'a SystemParamItem<'w, 's, T>,
}
impl<T: ReadOnlySystemParam> Clone for AabbContext<'_, '_, '_, T> {
fn clone(&self) -> Self {
Self {
entity: self.entity,
item: self.item,
}
}
}
impl<'a, 'w, 's, T: ReadOnlySystemParam> AabbContext<'a, 'w, 's, T> {
/// Construct an [`AabbContext`]
pub fn new(entity: Entity, item: &'a <T as SystemParam>::Item<'w, 's>) -> Self {
Self { entity, item }
}
}
impl AabbContext<'_, '_, '_, ()> {
fn fake() -> Self {
Self {
entity: Entity::PLACEHOLDER,
item: &(),
}
}
}
/// Context necessary to calculate [`ContactManifold`]s for a set of [`AnyCollider`]
#[derive(Deref)]
pub struct ContactManifoldContext<'a, 'w, 's, T: ReadOnlySystemParam> {
/// The first collider entity involved in the contact.
pub entity1: Entity,
/// The second collider entity involved in the contact.
pub entity2: Entity,
#[deref]
item: &'a SystemParamItem<'w, 's, T>,
}
impl<'a, 'w, 's, T: ReadOnlySystemParam> ContactManifoldContext<'a, 'w, 's, T> {
/// Construct a [`ContactManifoldContext`]
pub fn new(
entity1: Entity,
entity2: Entity,
item: &'a <T as SystemParam>::Item<'w, 's>,
) -> Self {
Self {
entity1,
entity2,
item,
}
}
}
impl ContactManifoldContext<'_, '_, '_, ()> {
fn fake() -> Self {
Self {
entity1: Entity::PLACEHOLDER,
entity2: Entity::PLACEHOLDER,
item: &(),
}
}
}
/// A trait that generalizes over colliders. Implementing this trait
/// allows colliders to be used with the physics engine.
pub trait AnyCollider: Component<Mutability = Mutable> + ComputeMassProperties {
/// A type providing additional context for collider operations.
///
/// `Context` allows you to access an arbitrary [`ReadOnlySystemParam`] on
/// the world, for context-sensitive behavior in collider operations. You
/// can use this to query components on the collider entity, or get any
/// other necessary context from the world.
///
/// # Example
///
/// ```
#[cfg_attr(
feature = "2d",
doc = "# use avian2d::{prelude::*, math::{Vector, Scalar}};"
)]
#[cfg_attr(
feature = "3d",
doc = "# use avian3d::{prelude::*, math::{Vector, Scalar}};"
)]
/// # use bevy::prelude::*;
/// # use bevy::ecs::system::{SystemParam, lifetimeless::{SRes, SQuery}};
/// #
/// #[derive(Component)]
/// pub struct VoxelCollider;
///
/// #[derive(Component)]
/// pub struct VoxelData {
/// // collider voxel data...
/// }
///
/// # impl ComputeMassProperties2d for VoxelCollider {
/// # fn mass(&self, density: f32) -> f32 {0.}
/// # fn unit_angular_inertia(&self) -> f32 { 0.}
/// # fn center_of_mass(&self) -> Vec2 { Vec2::ZERO }
/// # }
/// #
/// # impl ComputeMassProperties3d for VoxelCollider {
/// # fn mass(&self, density: f32) -> f32 {0.}
/// # fn unit_principal_angular_inertia(&self) -> Vec3 { Vec3::ZERO }
/// # fn center_of_mass(&self) -> Vec3 { Vec3::ZERO }
/// # }
/// #
/// impl AnyCollider for VoxelCollider {
/// type Context = (
/// // you can query extra components here
/// SQuery<&'static VoxelData>,
/// // or put any other read-only system param here
/// SRes<Time>,
/// );
///
/// # fn aabb_with_context(
/// # &self,
/// # _: Vector,
/// # _: impl Into<Rotation>,
/// # _: AabbContext<Self::Context>,
/// # ) -> ColliderAabb { unimplemented!() }
/// #
/// fn contact_manifolds_with_context(
/// &self,
/// other: &Self,
/// position1: Vector,
/// rotation1: impl Into<Rotation>,
/// position2: Vector,
/// rotation2: impl Into<Rotation>,
/// prediction_distance: Scalar,
/// manifolds: &mut Vec<ContactManifold>,
/// context: ContactManifoldContext<Self::Context>,
/// ) {
/// let [voxels1, voxels2] = context.0.get_many([context.entity1, context.entity2])
/// .expect("our own `VoxelCollider` entities should have `VoxelData`");
/// let elapsed = context.1.elapsed();
/// // do some computation...
/// # unimplemented!()
/// }
/// }
/// ```
type Context: for<'w, 's> ReadOnlySystemParam<Item<'w, 's>: Send + Sync>;
/// Computes the [Axis-Aligned Bounding Box](ColliderAabb) of the collider
/// with the given position and rotation.
///
/// See [`SimpleCollider::aabb`] for collider types with empty [`AnyCollider::Context`]
#[cfg_attr(
feature = "2d",
doc = "\n\nThe rotation is counterclockwise and in radians."
)]
fn aabb_with_context(
&self,
position: Vector,
rotation: impl Into<Rotation>,
context: AabbContext<Self::Context>,
) -> ColliderAabb;
/// Computes the swept [Axis-Aligned Bounding Box](ColliderAabb) of the collider.
/// This corresponds to the space the shape would occupy if it moved from the given
/// start position to the given end position.
///
/// See [`SimpleCollider::swept_aabb`] for collider types with empty [`AnyCollider::Context`]
#[cfg_attr(
feature = "2d",
doc = "\n\nThe rotation is counterclockwise and in radians."
)]
fn swept_aabb_with_context(
&self,
start_position: Vector,
start_rotation: impl Into<Rotation>,
end_position: Vector,
end_rotation: impl Into<Rotation>,
context: AabbContext<Self::Context>,
) -> ColliderAabb {
self.aabb_with_context(start_position, start_rotation, context.clone())
.merged(self.aabb_with_context(end_position, end_rotation, context))
}
/// Computes all [`ContactManifold`]s between two colliders.
///
/// Returns an empty vector if the colliders are separated by a distance greater than `prediction_distance`
/// or if the given shapes are invalid.
///
/// See [`SimpleCollider::contact_manifolds`] for collider types with empty [`AnyCollider::Context`]
fn contact_manifolds_with_context(
&self,
other: &Self,
position1: Vector,
rotation1: impl Into<Rotation>,
position2: Vector,
rotation2: impl Into<Rotation>,
prediction_distance: Scalar,
manifolds: &mut Vec<ContactManifold>,
context: ContactManifoldContext<Self::Context>,
);
}
/// A simplified wrapper around [`AnyCollider`] that doesn't require passing in the context for
/// implementations that don't need context
pub trait SimpleCollider: AnyCollider<Context = ()> {
/// Computes the [Axis-Aligned Bounding Box](ColliderAabb) of the collider
/// with the given position and rotation.
///
/// See [`AnyCollider::aabb_with_context`] for collider types with non-empty [`AnyCollider::Context`]
fn aabb(&self, position: Vector, rotation: impl Into<Rotation>) -> ColliderAabb {
self.aabb_with_context(position, rotation, AabbContext::fake())
}
/// Computes the swept [Axis-Aligned Bounding Box](ColliderAabb) of the collider.
/// This corresponds to the space the shape would occupy if it moved from the given
/// start position to the given end position.
///
/// See [`AnyCollider::swept_aabb_with_context`] for collider types with non-empty [`AnyCollider::Context`]
fn swept_aabb(
&self,
start_position: Vector,
start_rotation: impl Into<Rotation>,
end_position: Vector,
end_rotation: impl Into<Rotation>,
) -> ColliderAabb {
self.swept_aabb_with_context(
start_position,
start_rotation,
end_position,
end_rotation,
AabbContext::fake(),
)
}
/// Computes all [`ContactManifold`]s between two colliders, writing the results into `manifolds`.
///
/// `manifolds` is cleared if the colliders are separated by a distance greater than `prediction_distance`
/// or if the given shapes are invalid.
///
/// See [`AnyCollider::contact_manifolds_with_context`] for collider types with non-empty [`AnyCollider::Context`]
fn contact_manifolds(
&self,
other: &Self,
position1: Vector,
rotation1: impl Into<Rotation>,
position2: Vector,
rotation2: impl Into<Rotation>,
prediction_distance: Scalar,
manifolds: &mut Vec<ContactManifold>,
) {
self.contact_manifolds_with_context(
other,
position1,
rotation1,
position2,
rotation2,
prediction_distance,
manifolds,
ContactManifoldContext::fake(),
)
}
}
impl<C: AnyCollider<Context = ()>> SimpleCollider for C {}
/// A trait for colliders that support scaling.
pub trait ScalableCollider: AnyCollider {
/// Returns the global scaling factor of the collider.
fn scale(&self) -> Vector;
/// Sets the global scaling factor of the collider.
///
/// If the scaling factor is not uniform and the resulting scaled shape
/// can not be represented exactly, the given `detail` is used for an approximation.
fn set_scale(&mut self, scale: Vector, detail: u32);
/// Scales the collider by the given scaling factor.
///
/// If the scaling factor is not uniform and the resulting scaled shape
/// can not be represented exactly, the given `detail` is used for an approximation.
fn scale_by(&mut self, factor: Vector, detail: u32) {
self.set_scale(factor * self.scale(), detail)
}
}
/// A marker component that indicates that a [collider](Collider) is disabled
/// and should not detect collisions or be included in spatial queries.
///
/// This is useful for temporarily disabling a collider without removing it from the world.
/// To re-enable the collider, simply remove this component.
///
/// Note that a disabled collider will still contribute to the mass properties of the rigid body
/// it is attached to. Set the [`Mass`] of the collider to zero to prevent this.
///
/// [`ColliderDisabled`] only applies to the entity it is attached to, not its children.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// #[derive(Component)]
/// pub struct Character;
///
/// /// Disables colliders for all rigid body characters, for example during cutscenes.
/// fn disable_character_colliders(
/// mut commands: Commands,
/// query: Query<Entity, (With<RigidBody>, With<Character>)>,
/// ) {
/// for entity in &query {
/// commands.entity(entity).insert(ColliderDisabled);
/// }
/// }
///
/// /// Enables colliders for all rigid body characters.
/// fn enable_character_colliders(
/// mut commands: Commands,
/// query: Query<Entity, (With<RigidBody>, With<Character>)>,
/// ) {
/// for entity in &query {
/// commands.entity(entity).remove::<ColliderDisabled>();
/// }
/// }
/// ```
///
/// # Related Components
///
/// - [`RigidBodyDisabled`]: Disables a rigid body.
/// - [`JointDisabled`]: Disables a joint constraint.
#[derive(Reflect, Clone, Copy, Component, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default)]
pub struct ColliderDisabled;
/// A component that marks a [`Collider`] as a sensor, also known as a trigger.
///
/// Sensor colliders send [collision events](crate::collision#collision-events) and register intersections,
/// but allow other bodies to pass through them. This is often used to detect when something enters
/// or leaves an area or is intersecting some shape.
///
/// Sensor colliders do *not* contribute to the mass properties of rigid bodies.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
/// // Spawn a static body with a sensor collider.
/// // Other bodies will pass through, but it will still send collision events.
#[cfg_attr(
feature = "2d",
doc = " commands.spawn((RigidBody::Static, Collider::circle(0.5), Sensor));"
)]
#[cfg_attr(
feature = "3d",
doc = " commands.spawn((RigidBody::Static, Collider::sphere(0.5), Sensor));"
)]
/// }
/// ```
#[doc(alias = "Trigger")]
#[derive(Reflect, Clone, Component, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct Sensor;
/// The Axis-Aligned Bounding Box of a [collider](Collider) in world space.
///
/// Note that the AABB will be [`ColliderAabb::INVALID`] until the first physics update.
#[derive(Reflect, Clone, Copy, Component, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, PartialEq)]
pub struct ColliderAabb {
/// The minimum point of the AABB.
pub min: Vector,
/// The maximum point of thr AABB.
pub max: Vector,
}
impl Default for ColliderAabb {
fn default() -> Self {
ColliderAabb::INVALID
}
}
impl ColliderAabb {
/// An invalid [`ColliderAabb`] that represents an empty AABB.
pub const INVALID: Self = Self {
min: Vector::INFINITY,
max: Vector::NEG_INFINITY,
};
/// Creates a new [`ColliderAabb`] from the given `center` and `half_size`.
pub fn new(center: Vector, half_size: Vector) -> Self {
Self {
min: center - half_size,
max: center + half_size,
}
}
/// Creates a new [`ColliderAabb`] from its minimum and maximum points.
pub fn from_min_max(min: Vector, max: Vector) -> Self {
Self { min, max }
}
/// Creates a new [`ColliderAabb`] from a given `SharedShape`.
#[cfg(all(
feature = "default-collider",
any(feature = "parry-f32", feature = "parry-f64")
))]
pub fn from_shape(shape: &crate::parry::shape::SharedShape) -> Self {
let aabb = shape.compute_local_aabb();
Self {
min: aabb.mins.into(),
max: aabb.maxs.into(),
}
}
/// Computes the center of the AABB,
#[inline(always)]
pub fn center(self) -> Vector {
self.min.midpoint(self.max)
}
/// Computes the size of the AABB.
#[inline(always)]
pub fn size(self) -> Vector {
self.max - self.min
}
/// Merges this AABB with another one.
#[inline(always)]
pub fn merged(self, other: Self) -> Self {
ColliderAabb {
min: self.min.min(other.min),
max: self.max.max(other.max),
}
}
/// Increases the size of the bounding volume in each direction by the given amount.
#[inline(always)]
pub fn grow(&self, amount: Vector) -> Self {
let b = Self {
min: self.min - amount,
max: self.max + amount,
};
debug_assert!(b.min.cmple(b.max).all());
b
}
/// Decreases the size of the bounding volume in each direction by the given amount.
#[inline(always)]
pub fn shrink(&self, amount: Vector) -> Self {
let b = Self {
min: self.min + amount,
max: self.max - amount,
};
debug_assert!(b.min.cmple(b.max).all());
b
}
/// Checks if `self` intersects with `other`.
#[inline(always)]
#[cfg(feature = "2d")]
pub fn intersects(&self, other: &Self) -> bool {
let x_overlaps = self.min.x <= other.max.x && self.max.x >= other.min.x;
let y_overlaps = self.min.y <= other.max.y && self.max.y >= other.min.y;
x_overlaps && y_overlaps
}
/// Checks if `self` intersects with `other`.
#[inline(always)]
#[cfg(feature = "3d")]
pub fn intersects(&self, other: &Self) -> bool {
let x_overlaps = self.min.x <= other.max.x && self.max.x >= other.min.x;
let y_overlaps = self.min.y <= other.max.y && self.max.y >= other.min.y;
let z_overlaps = self.min.z <= other.max.z && self.max.z >= other.min.z;
x_overlaps && y_overlaps && z_overlaps
}
}
/// A component that adds an extra margin or "skin" around [`Collider`] shapes to help maintain
/// additional separation to other objects. This added thickness can help improve
/// stability and performance in some cases, especially for thin shapes such as trimeshes.
///
/// There are three primary reasons for collision margins:
///
/// 1. Collision detection is often more efficient when shapes are not overlapping
/// further than their collision margins. Deeply overlapping shapes require
/// more expensive collision algorithms.
///
/// 2. Some shapes such as triangles and planes are infinitely thin,
/// which can cause precision errors. A collision margin adds artificial
/// thickness to shapes, improving stability.
///
/// 3. Overall, collision margins give the physics engine more
/// room for error when resolving contacts. This can also help
/// prevent visible artifacts such as objects poking through the ground.
///
/// If a rigid body with a [`CollisionMargin`] has colliders as child entities,
/// and those colliders don't have their own [`CollisionMargin`] components,
/// the colliders will use the rigid body's [`CollisionMargin`].
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
#[cfg_attr(
feature = "2d",
doc = " // Spawn a rigid body with a collider.
// A margin of `0.1` is added around the shape.
commands.spawn((
RigidBody::Dynamic,
Collider::capsule(2.0, 0.5),
CollisionMargin(0.1),
));"
)]
#[cfg_attr(
feature = "3d",
doc = " let mesh = Mesh::from(Torus::default());
// Spawn a rigid body with a triangle mesh collider.
// A margin of `0.1` is added around the shape.
commands.spawn((
RigidBody::Dynamic,
Collider::trimesh_from_mesh(&mesh).unwrap(),
CollisionMargin(0.1),
));"
)]
/// }
/// ```
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Component)]
#[doc(alias = "ContactSkin")]
pub struct CollisionMargin(pub Scalar);
/// A component for reading which entities are colliding with a collider entity.
/// Must be added manually for desired colliders.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
/// commands.spawn((
/// RigidBody::Dynamic,
/// Collider::capsule(0.5, 1.5),
/// // Add the `CollidingEntities` component to read entities colliding with this entity.
/// CollidingEntities::default(),
/// ));
/// }
///
/// fn my_system(query: Query<(Entity, &CollidingEntities)>) {
/// for (entity, colliding_entities) in &query {
/// println!(
/// "{} is colliding with the following entities: {:?}",
/// entity,
/// colliding_entities,
/// );
/// }
/// }
/// ```
#[derive(Reflect, Clone, Component, Debug, Default, Deref, DerefMut, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct CollidingEntities(pub EntityHashSet);
impl MapEntities for CollidingEntities {
fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
self.0 = self
.0
.clone()
.into_iter()
.map(|e| entity_mapper.get_mapped(e))
.collect()
}
}