Skip to content

Commit

Permalink
Collision Hooks (#610)
Browse files Browse the repository at this point in the history
# Objective

Closes #150.

Advanced contact scenarios often require filtering or modifying contacts with custom logic. Use cases include:

- One-way platforms
- Conveyor belts
- Non-uniform friction and restitution for terrain

Physics engines typically handle this with *hooks* or *callbacks* that are called during specific parts of the simulation loop. For example:

- Box2D: `b2CustomFilterFcn()` and `b2PreSolveFcn` (see [docs](https://box2d.org/documentation/md_simulation.html#autotoc_md97))
- Rapier: `PhysicsHooks` trait with `filter_contact_pair`/`filter_intersection_pair` and `modify_solver_contacts` (see [docs](https://rapier.rs/docs/user_guides/bevy_plugin/advanced_collision_detection#physics-hooks))
- Jolt: `ContactListener` with `OnContactValidate`, `OnContactAdded`, `OnContactPersisted`, and `OnContactRemoved` (see [docs](https://jrouwe.github.io/JoltPhysics/class_contact_listener.html))

Currently, we just have a `PostProcessCollisions` schedule where users can freely add systems to operate on collision data before constraints are generated. However:

- It doesn't support filtering broad phase pairs.
- It results in unnecessary iteration. Filtering and modification should happen directly when contacts are being created or added.
- It adds more scheduling overhead.
- It forces us to handle collision events and other collision logic in a sub-optimal way.

`PostProcessCollisions` is generally not a good approach for performance, and it is not enough for our needs, even if it is highly flexible. We need proper collision hooks that are called as part of the simulation loop.

## Solution

Add a `CollisionHooks` trait for types implementing `ReadOnlySystemParam`, with a `filter_pairs` method for filtering broad phase pairs, and a `modify_contacts` method for modifying and filtering contacts computed by the narrow phase.

The system parameter allows ECS access in hooks. Only read-only access is allowed, because contact modification hooks may run in parallel, *but* deferred changes are supported through `Commands` passed to the hooks.

An example implementation to support interaction groups and one-way platforms might look like this:

```rust
use avian2d::prelude::*;
use bevy::{ecs::system::SystemParam, prelude::*};

/// A component that groups entities for interactions. Only entities in the same group can collide.
#[derive(Component)]
struct InteractionGroup(u32);

/// A component that marks an entity as a one-way platform.
#[derive(Component)]
struct OneWayPlatform;

// Define a `SystemParam` for the collision hooks.
#[derive(SystemParam)]
struct MyHooks<'w, 's> {
    interaction_query: Query<'w, 's, &'static InteractionGroup>,
    platform_query: Query<'w, 's, &'static Transform, With<OneWayPlatform>>,
}

// Implement the `CollisionHooks` trait.
impl CollisionHooks for MyHooks<'_, '_> {
    fn filter_pairs(&self, entity1: Entity, entity2: Entity, _commands: &mut Commands) -> bool {
        // Only allow collisions between entities in the same interaction group.
        // This could be a basic solution for "multiple physics worlds" that don't interact.
        let Ok([group1, group2]) = self.interaction_query.get_many([entity1, entity2]) else {
            return true;
        };
        group1.0 == group2.0
    }

    fn modify_contacts(&self, contacts: &mut Contacts, commands: &mut Commands) -> bool {
        // Allow entities to pass through the bottom and sides of one-way platforms.
        // See the `one_way_platform_2d` example for a full implementation.
        let (entity1, entity2) = (contacts.entity1, contacts.entity2);
        !self.is_hitting_top_of_platform(entity1, entity2, &self.platform_query, &contacts, commands)
    }
}
```

The hooks can then be added to the app using `PhysicsPlugins::with_collision_hooks`:

```rust
fn main() {
    App::new()
        .add_plugins((
            DefaultPlugins,
            PhysicsPlugins::default().with_collision_hooks::<MyHooks>(),
        ))
        .run();
}
```

> [!NOTE]
>
> The hooks are passed to the `BroadPhasePlugin` and `NarrowPhasePlugin` with generics. An app can only have one set of hooks defined.
>
> Where are the generics on `PhysicsPlugins` then? `bevy_rapier` requires them on `RapierPhysicsPlugin`, forcing people to specify generics even if hooks aren't used, like `RapierPhysicsPlugin::<()>::default()` (see dimforge/bevy_rapier#501).
>
> Given that this is the first thing users do with the engine, I wanted to avoid forcing unnecessary generics. I'm using a subtle trick to get around them; `PhysicsPlugins` has no generics, but there is a separate `PhysicsPluginsWithHooks` wrapper with a similar API that is returned by `with_collision_hooks`. This abstraction is largely transparent to users, and gets around unnecessary generics in the public API.

It is rare to want hooks to run for every single collision pair. Thus, hooks are *only* called for collisions where at least one entity has the new `ActiveCollisionHooks` component with the corresponding flags set. By default, no hooks are called.

```rust
// Spawn a collider with filtering hooks enabled.
commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::FILTER_PAIRS));

// Spawn a collider with both filtering and contact modification hooks enabled.
commands.spawn((
    Collider::capsule(0.5, 1.5),
    ActiveCollisionHooks::FILTER_PAIRS | ActiveCollisionHooks::MODIFY_CONTACTS
));

// Alternatively, all hooks can be enabled with `ActiveCollisionHooks::all()`.
commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::all()));
```

### Comparison With `bevy_rapier`

The design of the collision hooks is partially inspired by `bevy_rapier`, but with what I think is a slightly friendlier and more flexible API. Some core differences:

- Rapier has ["context views"](https://docs.rs/bevy_rapier3d/0.28.0/bevy_rapier3d/pipeline/struct.ContactModificationContextView.html) for both pair filters and contact modification, with a `raw` property you need to access. It provides read-only access to some internal Rapier data (using Nalgebra types) and a contact manifold, and write-access to a contact normal and "solver contacts". There seems to be no way to queue commands or otherwise perform changes to the ECS, only read-only access.
- My pair filters simply provide the entities and access to `Commands`, while the contact modification hook provides mutable access to the `Contacts` (*not* necessarily just one manifold) between a contact pair, and to `Commands`. Read-only data about the involved entities can be queried with the ECS.

Personally, I think `bevy_rapier`'s hooks introduce a bit too much complexity and new APIs for Bevy users; there are "context views", contact manifolds, solver contacts, a bunch of internal Rapier structures, and everything uses Nalgebra types. I tried to keep it more simple, with the same contact types people already use when accessing the `Collisions` resource, while supporting read-only ECS access using the system parameter and deferred changes using `Commands`. No weird context views or Nalgebra types.

Rapier provides solver contacts, while my implementation provides raw narrow phase contact data. Both have their trade-offs, but using raw contact data introduces less new concepts, *and* it allows earlier termination, since the data for solver contacts doesn't need to be computed (though our implementation there is somewhat different from Rapier anyway).

Currently, my implementation runs hooks per *collision pair* (`Contacts`), not per *manifold* (`ContactManifold`). This provides some more data and allows entire collision pairs to be ignored at once if desired. I'm not 100% sure which is preferable though; many other engines seem to have contact modification be per-manifold. There is a possibility that we change this at some point.

### Other Changes

- Updated the `one_way_platform_2d` example to use collision hooks, and overall improved the example code.
- The broad phase now stores `AabbIntervalFlags` instead of several booleans for AABB intervals.
- `BroadPhasePlugin`, `NarrowPhasePlugin`, and many `NarrowPhase` methods now take generics for `CollisionHooks`.
- Reworked some narrow phase contact logic slightly.
- Updated and improved some docs.

## Follow-Up Work

I have several follow-up PRs in progress:

1. Per-manifold tangent velocities (for e.g. conveyor belts) and friction and restitution (for non-uniform material properties)
2. Rename many contact types and properties for clarity, improve docs and APIs
3. Contact graph
4. Reworked contact pair management

I expect them to be ready in that order. For 3-4, I would like #564 first.

It is also highly likely that we will deprecate the `PostProcessCollisions` schedule in favor of these hooks.

---

## Migration Guide

For custom contact filtering and modification logic, it is now recommended to define `CollisionHooks` instead of manually accessing and modifying `Collisions` in the `PostProcessCollisions` schedule.

The `BroadPhasePlugin`, `NarrowPhasePlugin`, and many `NarrowPhase` methods now take generics for `CollisionHooks`.
  • Loading branch information
Jondolf authored Jan 1, 2025
1 parent 7e945ae commit 6424aa6
Show file tree
Hide file tree
Showing 9 changed files with 705 additions and 214 deletions.
231 changes: 150 additions & 81 deletions crates/avian2d/examples/one_way_platform_2d.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
//! A 2D platformer example with one-way platforms to demonstrate
//! filtering collisions with systems in the `PostProcessCollisions` schedule.
//! contact modification with `CollisionHooks`.
//!
//! Move with arrow keys, jump with Space and descend through
//! platforms by pressing Space while holding the down arrow.
#![allow(clippy::type_complexity)]

use avian2d::{math::*, prelude::*};
use bevy::{prelude::*, utils::HashSet};
use bevy::{
ecs::system::{lifetimeless::Read, SystemParam},
prelude::*,
utils::HashSet,
};
use examples_common_2d::ExampleCommonPlugin;

fn main() {
App::new()
.add_plugins((
DefaultPlugins,
ExampleCommonPlugin,
// Add physics plugins and specify a units-per-meter scaling factor, 1 meter = 20 pixels.
// The unit allows the engine to tune its parameters for the scale of the world, improving stability.
PhysicsPlugins::default().with_length_unit(20.0),
PhysicsPlugins::default()
// Specify a units-per-meter scaling factor, 1 meter = 20 pixels.
// The unit allows the engine to tune its parameters for the scale of the world, improving stability.
.with_length_unit(20.0)
// Add our custom collision hooks.
.with_collision_hooks::<PlatformerCollisionHooks>(),
))
.insert_resource(ClearColor(Color::srgb(0.05, 0.05, 0.1)))
.insert_resource(Gravity(Vector::NEG_Y * 1000.0))
.add_systems(Startup, setup)
.add_systems(Update, (movement, pass_through_one_way_platform))
.add_systems(PostProcessCollisions, one_way_platform)
.run();
}

Expand All @@ -34,17 +42,21 @@ struct MovementSpeed(Scalar);
#[derive(Component)]
struct JumpImpulse(Scalar);

// Enable contact modification for one-way platforms with the `ActiveCollisionHooks` component.
// Here we use required components, but you could also add it manually.
#[derive(Clone, Eq, PartialEq, Debug, Default, Component)]
#[require(ActiveCollisionHooks(|| ActiveCollisionHooks::MODIFY_CONTACTS))]
pub struct OneWayPlatform(HashSet<Entity>);

/// A component to control how an actor interacts with a one-way platform.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default, Component, Reflect)]
pub enum PassThroughOneWayPlatform {
#[default]
/// Passes through a `OneWayPlatform` if the contact normal is in line with the platform's local-space up vector
/// Passes through a `OneWayPlatform` if the contact normal is in line with the platform's local-space up vector.
ByNormal,
/// Always passes through a `OneWayPlatform`, temporarily set this to allow an actor to jump down through a platform
/// Always passes through a `OneWayPlatform`, temporarily set this to allow an actor to jump down through a platform.
Always,
/// Never passes through a `OneWayPlatform`
/// Never passes through a `OneWayPlatform`.
Never,
}

Expand Down Expand Up @@ -171,70 +183,70 @@ fn pass_through_one_way_platform(
}
}

/// Allows entities to pass through [`OneWayPlatform`] entities.
///
/// Passing through is achieved by removing the collisions between the [`OneWayPlatform`]
/// and the other entity if the entity should pass through.
/// If a [`PassThroughOneWayPlatform`] is present on the non-platform entity,
/// the value of the component dictates the pass-through behaviour.
///
/// Entities known to be passing through each [`OneWayPlatform`] are stored in the
/// [`OneWayPlatform`]. If an entity is known to be passing through a [`OneWayPlatform`],
/// it is allowed to continue to do so, even if [`PassThroughOneWayPlatform`] has been
/// set to disallow passing through.
///
/// > Note that this is a very simplistic implementation of one-way
/// > platforms to demonstrate filtering collisions via [`PostProcessCollisions`].
/// > You will probably want something more robust to implement one-way
/// > platforms properly, or may elect to use a sensor collider for your entities instead,
/// > which means you won't need to filter collisions at all.
///
/// #### When an entity is known to already be passing through the [`OneWayPlatform`]
///
/// Any time an entity begins passing through a [`OneWayPlatform`], it is added to the
/// [`OneWayPlatform`]'s set of currently active penetrations, and will be allowed to
/// continue to pass through the platform until it is no longer penetrating the platform.
///
/// The entity is allowed to continue to pass through the platform as long as at least
/// one contact is penetrating.
///
/// Once all of the contacts are no longer penetrating the [`OneWayPlatform`], or all contacts
/// have stopped, the entity is forgotten about and the logic falls through to the next part.
///
/// #### When an entity is NOT known to be passing through the [`OneWayPlatform`]
///
/// Depending on the setting of [`PassThroughOneWayPlatform`], the entity may be allowed to
/// pass through.
///
/// If no [`PassThroughOneWayPlatform`] is present, [`PassThroughOneWayPlatform::ByNormal`] is used.
///
/// [`PassThroughOneWayPlatform`] may be in one of three states:
/// 1. [`PassThroughOneWayPlatform::ByNormal`]
/// - This is the default state
/// - The entity may be allowed to pass through the [`OneWayPlatform`] depending on the contact normal
/// - If all contact normals are in line with the [`OneWayPlatform`]'s local-space up vector,
/// the entity is allowed to pass through
/// 2. [`PassThroughOneWayPlatform::Always`]
/// - The entity will always pass through the [`OneWayPlatform`], regardless of contact normal
/// - This is useful for allowing an entity to jump down through a platform
/// 3. [`PassThroughOneWayPlatform::Never`]
/// - The entity will never pass through the [`OneWayPlatform`], meaning the platform will act
/// as normal hard collision for this entity
///
/// Even if an entity is changed to [`PassThroughOneWayPlatform::Never`], it will be allowed to pass
/// through a [`OneWayPlatform`] if it is already penetrating the platform. Once it exits the platform,
/// it will no longer be allowed to pass through.
fn one_way_platform(
mut one_way_platforms_query: Query<&mut OneWayPlatform>,
// Define a custom `SystemParam` for our collision hooks.
// It can have read-only access to queries, resources, and other system parameters.
#[derive(SystemParam)]
struct PlatformerCollisionHooks<'w, 's> {
one_way_platforms_query: Query<'w, 's, Read<OneWayPlatform>>,
// NOTE: This precludes a `OneWayPlatform` passing through a `OneWayPlatform`.
other_colliders_query: Query<
Option<&PassThroughOneWayPlatform>,
(With<Collider>, Without<OneWayPlatform>), // NOTE: This precludes OneWayPlatform passing through a OneWayPlatform
'w,
's,
Option<Read<PassThroughOneWayPlatform>>,
(With<Collider>, Without<OneWayPlatform>),
>,
mut collisions: ResMut<Collisions>,
) {
// This assumes that Collisions contains empty entries for entities
// that were once colliding but no longer are.
collisions.retain(|contacts| {
}

// Implement the `CollisionHooks` trait for our custom system parameter.
impl CollisionHooks for PlatformerCollisionHooks<'_, '_> {
// Below is a description of the logic used for one-way platforms.

/// Allows entities to pass through [`OneWayPlatform`] entities.
///
/// Passing through is achieved by removing the collisions between the [`OneWayPlatform`]
/// and the other entity if the entity should pass through.
/// If a [`PassThroughOneWayPlatform`] is present on the non-platform entity,
/// the value of the component dictates the pass-through behaviour.
///
/// Entities known to be passing through each [`OneWayPlatform`] are stored in the
/// [`OneWayPlatform`]. If an entity is known to be passing through a [`OneWayPlatform`],
/// it is allowed to continue to do so, even if [`PassThroughOneWayPlatform`] has been
/// set to disallow passing through.
///
/// #### When an entity is known to already be passing through the [`OneWayPlatform`]
///
/// When an entity begins passing through a [`OneWayPlatform`], it is added to the
/// [`OneWayPlatform`]'s set of active penetrations, and will be allowed to continue
/// to pass through until it is no longer penetrating the platform.
///
/// #### When an entity is *not* known to be passing through the [`OneWayPlatform`]
///
/// Depending on the setting of [`PassThroughOneWayPlatform`], the entity may be allowed to
/// pass through.
///
/// If no [`PassThroughOneWayPlatform`] is present, [`PassThroughOneWayPlatform::ByNormal`] is used.
///
/// [`PassThroughOneWayPlatform`] may be in one of three states:
/// 1. [`PassThroughOneWayPlatform::ByNormal`]
/// - This is the default state
/// - The entity may be allowed to pass through the [`OneWayPlatform`] depending on the contact normal
/// - If all contact normals are in line with the [`OneWayPlatform`]'s local-space up vector,
/// the entity is allowed to pass through
/// 2. [`PassThroughOneWayPlatform::Always`]
/// - The entity will always pass through the [`OneWayPlatform`], regardless of contact normal
/// - This is useful for allowing an entity to jump down through a platform
/// 3. [`PassThroughOneWayPlatform::Never`]
/// - The entity will never pass through the [`OneWayPlatform`], meaning the platform will act
/// as normal hard collision for this entity
///
/// Even if an entity is changed to [`PassThroughOneWayPlatform::Never`], it will be allowed to pass
/// through a [`OneWayPlatform`] if it is already penetrating the platform. Once it exits the platform,
/// it will no longer be allowed to pass through.
fn modify_contacts(&self, contacts: &mut Contacts, commands: &mut Commands) -> bool {
// This is the contact modification hook, called after collision detection,
// but before constraints are created for the solver. Mutable access to the ECS
// is not allowed, but we can queue commands to perform deferred changes.

// Differentiate between which normal of the manifold we should use
enum RelevantNormal {
Normal1,
Expand All @@ -243,11 +255,22 @@ fn one_way_platform(

// First, figure out which entity is the one-way platform, and which is the other.
// Choose the appropriate normal for pass-through depending on which is which.
let (mut one_way_platform, other_entity, relevant_normal) =
if let Ok(one_way_platform) = one_way_platforms_query.get_mut(contacts.entity1) {
(one_way_platform, contacts.entity2, RelevantNormal::Normal1)
} else if let Ok(one_way_platform) = one_way_platforms_query.get_mut(contacts.entity2) {
(one_way_platform, contacts.entity1, RelevantNormal::Normal2)
let (platform_entity, one_way_platform, other_entity, relevant_normal) =
if let Ok(one_way_platform) = self.one_way_platforms_query.get(contacts.entity1) {
(
contacts.entity1,
one_way_platform,
contacts.entity2,
RelevantNormal::Normal1,
)
} else if let Ok(one_way_platform) = self.one_way_platforms_query.get(contacts.entity2)
{
(
contacts.entity2,
one_way_platform,
contacts.entity1,
RelevantNormal::Normal2,
)
} else {
// Neither is a one-way-platform, so accept the collision:
// we're done here.
Expand All @@ -268,17 +291,23 @@ fn one_way_platform(
return false;
} else {
// If it's no longer penetrating us, forget it.
one_way_platform.0.remove(&other_entity);
commands.queue(OneWayPlatformCommand::Remove {
platform_entity,
entity: other_entity,
});
}
}

match other_colliders_query.get(other_entity) {
match self.other_colliders_query.get(other_entity) {
// Pass-through is set to never, so accept the collision.
Ok(Some(PassThroughOneWayPlatform::Never)) => true,
// Pass-through is set to always, so always ignore this collision
// and register it as an entity that's currently penetrating.
Ok(Some(PassThroughOneWayPlatform::Always)) => {
one_way_platform.0.insert(other_entity);
commands.queue(OneWayPlatformCommand::Add {
platform_entity,
entity: other_entity,
});
false
}
// Default behaviour is "by normal".
Expand All @@ -297,10 +326,50 @@ fn one_way_platform(
} else {
// Otherwise, ignore the collision and register
// the other entity as one that's currently penetrating.
one_way_platform.0.insert(other_entity);
commands.queue(OneWayPlatformCommand::Add {
platform_entity,
entity: other_entity,
});
false
}
}
}
});
}
}

/// A command to add/remove entities to/from the set of entities
/// that are currently in contact with a one-way platform.
enum OneWayPlatformCommand {
Add {
platform_entity: Entity,
entity: Entity,
},
Remove {
platform_entity: Entity,
entity: Entity,
},
}

impl Command for OneWayPlatformCommand {
fn apply(self, world: &mut World) {
match self {
OneWayPlatformCommand::Add {
platform_entity,
entity,
} => {
if let Some(mut platform) = world.get_mut::<OneWayPlatform>(platform_entity) {
platform.0.insert(entity);
}
}

OneWayPlatformCommand::Remove {
platform_entity,
entity,
} => {
if let Some(mut platform) = world.get_mut::<OneWayPlatform>(platform_entity) {
platform.0.remove(&entity);
}
}
}
}
}
Loading

0 comments on commit 6424aa6

Please sign in to comment.