Skip to main content

Advanced collision-detection

Collision-detection is a two-steps process. First the BroadPhase detects pairs of colliders that are potentially in contact or intersecting. Second, the NarrowPhase processes all these pairs in order to compute contacts points and generate collision events. Based on these points, the constraints solver computes forces that may generate contact force events.

All the pairs detected by the broad-phase are stored into two graph structures:

  • The contact graph stores all the potential contact pairs (between two non-sensor colliders) as well as the contact points generated by the narrow-phase.
  • The intersection graph stores all the potential intersection pairs (between a sensor collider and another collider) as well as the result of the boolean intersection test executed by the narrow-phase.

These two graphs are part of the NarrowPhase structure and are automatically updated by the PhysicsPipeline or the CollisionPipeline. Each node of these graph contains a ColliderHandle and there is one graph edge per pair detected by the broad-phase. The NarrowPhase of a physics world is given by its PhysicsWorld.narrow_phase property.

Collision and contact force events​

The narrow-phase can generate collision events between two colliders. Each collision event is given optional flags:

  • CollisionEventFlags.SENSOR is set if at least one of the colliders involved in the collision is a sensor.
  • CollisionEventFlags.REMOVED is set if a collision stopped because at least one of the colliders involved in the collision was removed from the physics scene.

In addition, after forces are computed by the constraints solver, contact force events may be generated between two colliders subject to non-zero contact forces. Generally, the user isn’t interested in contact force events unless the force magnitudes exceed some threshold. In order to skip low-force events, the engine will compute the sum of the magnitude of all the contacts between the two colliders and only trigger a contact force event if that magnitude is larger than the threshold set with ColliderBuilder.contact_force_event_threshold or the Collider.contact_force_event_threshold property (defaults to 0) for any of the two colliders with the ActiveEvents.CONTACT_FORCE_EVENTS flag enabled.

warning

Collision events (resp. contact force events) are only generated between two colliders if at least one of them has the ActiveEvents.COLLISION_EVENTS flag (resp. ActiveEvents.CONTACT_FORCE_EVENTS flags) in its active events.

In order to handle these events, it is necessary to collect them with an event handler assigned to the PhysicsWorld.event_handler property. One such event handler provided by Rapier is the ChannelEventCollector. It contains one queue per kind of event (the collision events, the contact force events, and the tear events of the soft-bodies), which are populated with events during each call to PhysicsWorld.step. Its drain_collision_events, drain_contact_force_events, and drain_soft_body_tear_events methods give the list of the events of their kind and empty the corresponding queue. Note that the events accumulate from one step to the next until they are drained (or until ChannelEventCollector.clear is called):

# Initialize the event collector.
event_handler = rp.ChannelEventCollector()
world.event_handler = event_handler

world.step()

for collision_event in event_handler.drain_collision_events():
# Handle the collision event.
print("Received collision event:", collision_event)

for contact_force_event in event_handler.drain_contact_force_events():
# Handle the contact force event.
print("Received contact force event:", contact_force_event)

for tear_event in event_handler.drain_soft_body_tear_events():
# Handle the soft-body tear event.
print("Received soft-body tear event:", tear_event)

Each CollisionEvent indicates whether the collision started or stopped, and its flags combine the CollisionEventFlags.SENSOR and CollisionEventFlags.REMOVED bits described above (also given by its sensor and removed properties). Each ContactForceEvent gives the sum of the contact forces applied between the two colliders (total_force) and its magnitude (total_force_magnitude), as well as the magnitude and the direction of the largest contact force (max_force_magnitude and max_force_direction).

These events only identify the colliders involved. The contact geometry can be read from the contact graph afterwards, but there are some cases when the contact information is no longer available at the end of the timestep (e.g. when running multi-step CCD and the contact start during one substep and stops at a substep right after). If you need to access the contact information at the exact time a contact event happens, you may assign your own event handler instead: any object with the methods of the EventHandler protocol (the kinds of events whose method isn't implemented are ignored). These methods are called during the step, with a copy of the contact pair involved. They are also given the rigid-body and collider sets of the world (bodies and colliders), which can be read but not modified (a modification raises a RuntimeError). Since these methods may be called from the worker threads of the step, read the world through these arguments rather than through the PhysicsWorld itself. Finally, an exception raised by one of these methods is raised again by PhysicsWorld.step once the step is complete (see PhysicsWorld.event_error_policy):

class MyEventHandler:
def handle_collision_event(self, bodies, colliders, event, contact_pair):
# The contact pair is a copy of the contacts at the time of the event
# (it is `None` if one of the colliders is a sensor).
if event.started and contact_pair is not None:
deepest_contact = contact_pair.find_deepest_contact()
print("Collision started with the contact:", deepest_contact)
# The sets of the world can be read (but not modified) from the event handler.
parent1 = colliders[event.collider1].parent
print("The first collider is attached to the rigid-body:", parent1)

def handle_contact_force_event(self, dt, bodies, colliders, contact_pair, total_force_magnitude):
print(
f"Contact force {total_force_magnitude} between",
contact_pair.collider1,
"and",
contact_pair.collider2,
)

def handle_soft_body_tear_event(self, soft_bodies, event):
# This method is optional.
print("Soft-body torn:", event)


world.event_handler = MyEventHandler()
world.step()
info

Collision events identify the involved colliders by their handle. It is possible to retrieve the handle of the rigid-body a collider is attached to: world.colliders[collider_handle].parent.

The contact graph​

The contact graph can be read in order to determine whether two specific non-sensor colliders are in contact, or to determine all the non-sensor colliders in contact with one particular non-sensor collider. Contact points and contact normals will also be provided when a contact exists.

The contact geometry (contact points, contact normal, penetration depth, etc.) can be read from the contact manifolds stored in a contact pair:

  1. Each contact pair may contain multiple contact manifolds. Each contact manifold represents a set of contacts sharing the same contact normal.
  2. Each contact manifold contains the list of geometric contacts detected by the narrow-phase.
  3. Each contact manifold also contains a list of contacts that were processed by the constraints solver for force calculation (aka. the solver contacts). These solver contacts are a subset of the contacts detected by the narrow-phase, expressed in a way that is more efficient for the constraints solver to process. These solver contacts can be modified or deleted by the user using contact modification.

All the geometric contact data are expressed in the local-space of the colliders. The solver contacts hold one anchor per body surface, expressed in the local-space of the body that surface belongs to (so they ride rigidly with it); ContactManifoldData.solver_contact_world_points resolves them back to world-space through the bodies' current poses. Inside a contact-modification hook they are world-space instead, since the hook runs before they are localized.

info

Because the solver contacts can be modified by the user, they are transients by nature: they are recomputed at each frame from the geometric contacts. Because of their transient nature, the constraint solver will store the forces it computes inside of the geometric contacts (the impulse property of ContactData) instead of the solver contacts themselves.

Keep in mind that the contact graph contains one graph edge per pair detected by the broad-phase. So the fact that a contact pair can be found in the graph doesn't mean that the corresponding colliders are actually in contact (they may just be very close to one another, without touching). It is necessary to check either:

  • the ContactPair.has_any_active_contact property if you need to know if there exist at least one solver contact between the colliders.
  • the length of ContactManifold.points for each manifold in ContactPair.manifolds to determine if the colliders are really geometrically touching (independently from contact-modification).
info

There will always be only up to one contact manifold between two colliders with convex primitive shapes. If one collider has a shape composed of several pieces (trimesh, polyline, heightfield, or compound shape) then there will be multiple contact manifolds, one for each piece that may result in an actual contact.

The contact pair between two colliders is given by NarrowPhase.contact_pair, which returns None if the pair doesn't exist. The contact pairs involving one particular collider are given by NarrowPhase.contact_pairs_with, and all the contact pairs of the world by NarrowPhase.contact_pairs. Keep in mind that these methods give copies of the contact pairs: they are not updated by the next timesteps. In addition to has_any_active_contact, a ContactPair gives a summary of the contact impulses applied between the two colliders during the last step (total_impulse and total_impulse_magnitude), and its deepest geometric contact (find_deepest_contact). Each element of ContactPair.manifolds is a ContactManifold whose points are its geometric contacts (each one being a ContactData), and whose data (a ContactManifoldData) contains its world-space contact normal as well as its solver contacts:

# Find the contact pair, if it exists, between two colliders.
contact_pair = world.narrow_phase.contact_pair(collider_handle1, collider_handle2)
if contact_pair is not None:
# The contact pair exists meaning that the broad-phase identified a potential contact.
if contact_pair.has_any_active_contact:
# The contact pair has active contacts, meaning that it
# contains contacts for which contact forces were computed.
pass

# We may also read the contact manifolds to access the contact geometry.
for manifold in contact_pair.manifolds:
print("Local-space contact normal:", manifold.local_n1)
print("Local-space contact normal:", manifold.local_n2)
print("World-space contact normal:", manifold.data.normal)

# Read the geometric contacts.
for contact_point in manifold.points:
# Keep in mind that all the geometric contact data are expressed in the local-space of the colliders.
print("Found local contact point 1:", contact_point.local_p1)
print("Found contact distance:", contact_point.dist) # Negative if there is a penetration.
print("Found contact impulse:", contact_point.impulse)
print("Found friction impulse:", contact_point.tangent_impulse)

# Read the solver contacts.
for solver_contact in manifold.data.solver_contacts:
# Solver contacts are anchored in the local-space of the body they touch, so
# they ride rigidly with it. Resolve them through the bodies' current poses to
# get the world-space contact point on each body's surface.
point1, point2 = manifold.data.solver_contact_world_points(solver_contact, world.rigid_bodies)
print("Found solver contact points:", point1, point2)
# The solver contact distance is negative if there is a penetration.
print("Found solver contact distance:", solver_contact.dist)
# Iterate through all the contact pairs involving a specific collider.
for contact_pair in world.narrow_phase.contact_pairs_with(collider_handle1):
if contact_pair.collider1 == collider_handle1:
other_collider = contact_pair.collider2
else:
other_collider = contact_pair.collider1

# Process the contact pair in a way similar to what we did in
# the previous example.

Finally, keep in mind that the contacts and contact manifolds field names frequently end with a digit 1 or 2. For example contact_pair.manifolds[0].local_n1 and contact_pair.manifolds[0].local_n2. Fields ending with the digit 1 relate to the collider identified by contact_pair.collider1. Fields ending with the digit 2 relate to the collider identified by contact_pair.collider2.

In other words local_n1 is the contact normal expressed in the local space of the collider collider_pair.collider1, it points towards the exterior of the shape of collider_pair.collider1. On the other hand, local_n2 is expressed in the local space of the collider collider_pair.collider2 and points towards the exterior of the shape of collider_pair.collider2.

warning

The contact pair returned by narrow_phase.contact_pair(handle1, handle2) does not necessarily have contact_pair.collider1 == handle1 and contact_pair.collider2 == handle2. It could be swapped: contact_pair.collider1 == handle2 and contact_pair.collider2 == handle1.

So keep that in mind when reading the contact information because it's contact_pair.collider1 and contact_pair.collider2 that determine to what collider the digits 1 and 2 relate in the contacts and contact manifolds fields.

The intersection graph​

The intersection graph can be read in order to determine whether two specific colliders (assuming at least one of them is a sensor) are intersecting, or to determine all the colliders intersecting one particular collider (assuming at least one collider of each pair is a sensor). The intersection graph contains one graph edge for each pair of colliders such that:

  1. At least one of the collider is a sensor.
  2. And they are close enough so the broad-phase considers they have a chance to be intersecting.

Each such edge contains one boolean indicating if the colliders are actually intersecting or not:

The boolean of the edge between two colliders is given by NarrowPhase.intersection_pair, which returns None if that pair doesn't exist. The intersection pairs involving one particular collider are given by NarrowPhase.intersection_pairs_with, and all the intersection pairs of the world by NarrowPhase.intersection_pairs, each one as a (collider1, collider2, intersecting) tuple:

# Find the intersection pair, if it exists, between two colliders.
if world.narrow_phase.intersection_pair(collider_handle1, collider_handle2):
print(f"The colliders {collider_handle1} and {collider_handle2} are intersecting!")
# Iterate through all the intersection pairs involving a specific collider.
for collider1, collider2, intersecting in world.narrow_phase.intersection_pairs_with(collider_handle1):
if intersecting:
print(f"The colliders {collider1} and {collider2} are intersecting!")
warning

Keep in mind that intersection tests are performed between two colliders only if at least one of the colliders is a sensor. If they are both non-sensor colliders then they will be involved in the contact graph instead of the intersection graph.

Physics hooks​

Physics hooks are user-defined callbacks used to change the behavior of the physics simulation. In particular, they can be used to filter contacts (in a more flexible way than collision groups and solver groups) and to modify contacts before they are processed by the constraints solver.

Physics hooks are given to the physics world by assigning them to its PhysicsWorld.physics_hooks property. They can be any object with the methods of the PhysicsHooks protocol, which defines one method per kind of hook. Only the methods of the hooks enabled in the active hooks of the colliders are called, and a method that isn't implemented keeps the default behavior of Rapier, so the hooks you don't need can be omitted. These methods are called during the step, and are given a context (a PairFilterContext or a ContactModificationContext) which identifies the colliders involved (collider1 and collider2) and their rigid-bodies (rigid_body1 and rigid_body2, which are None for a collider without parent), and gives a read-only access to the colliders and rigid-bodies of the world (colliders and bodies, a modification raising a RuntimeError). This context is only valid until the method returns. Since the hooks may be called from the worker threads of the step, read the world through this context rather than through the PhysicsWorld itself. Finally, an exception raised by one of these methods is raised again by PhysicsWorld.step once the step is complete (see PhysicsWorld.event_error_policy).

info

If no physics hooks are needed by your simulation, the PhysicsWorld.physics_hooks property can be left to None, its default value.

Contact and intersection filtering​

Sometimes, collision groups and solver groups are not flexible enough to achieve the desired behavior. In that case, the contact filtering hooks let you apply custom rules to filter contact pairs and intersection pairs:

  • For each potential contact pair (between two non-sensor colliders) detected by the broad-phase, if at least one of the colliders involved in the pair has the bit ActiveHooks.FILTER_CONTACT_PAIRS enabled in its active hooks, then PhysicsHooks.filter_contact_pair will be called. If this filter returns None then no contact computation will happen for this pair of colliders. If it returns solver flags (a SolverFlags) then the narrow-phase will compute contact points.
  • For each potential intersection pair (between a sensor colliders and another collider) detected by the broad-phase, if at least one of the colliders involved in the pair has the bit ActiveHooks.FILTER_INTERSECTION_PAIR enabled in its active hooks, then PhysicsHooks.filter_intersection_pair will be called. If this filter returns False then no intersection computation will happen for this pair of colliders. If it returns True then the narrow-phase will test whether or not they are intersecting.

When PhysicsHooks.filter_contact_pair doesn't return None, the solver flags it returns indicate what happen with the contacts of this contact pair afterwards:

  • If the returned flags contain the SolverFlags.COMPUTE_RIGID_IMPULSES bit, then the constraints solver will compute forces for these contacts. If this bit is not included in the returned flags (e.g. with SolverFlags.empty()), then no contact force will be computed for this pair of colliders.
note

Right now there is no solver flags other than SolverFlags.COMPUTE_RIGID_IMPULSES. Other flags may be added in the future.

class MyPhysicsHooks:
def filter_contact_pair(self, context):
# This is a silly example of contact pair filter that:
# - Enables contact and force computation if both colliders have even user-data.
# - Enables contact computation but not force computation if both colliders have equal user-data.
# - Disables contact computation otherwise.
user_data1 = context.colliders[context.collider1].user_data
user_data2 = context.colliders[context.collider2].user_data

if user_data1 % 2 == 0 and user_data2 % 2 == 0:
return rp.SolverFlags.COMPUTE_RIGID_IMPULSES
elif user_data1 == user_data2:
return rp.SolverFlags.empty()
else:
return None

def filter_intersection_pair(self, context):
# This is a silly example of intersection pair filter that
# enables the intersection test if both colliders have odd
# user-data.
user_data1 = context.colliders[context.collider1].user_data
user_data2 = context.colliders[context.collider2].user_data

return user_data1 % 2 == 1 and user_data2 % 2 == 1


world.physics_hooks = MyPhysicsHooks()

Keep in mind that these filters don't replace the built-in filtering of Rapier: they are only called for the pairs that passed it. The pairs of colliders attached to the same rigid-body, or to rigid-bodies linked by a joint with contacts disabled, are discarded first, then the pairs rejected by the active collision types of both colliders (e.g. between two non-dynamic rigid-bodies by default), then the pairs rejected by their collision groups. The solver groups are applied to the solver flags returned by filter_contact_pair afterwards.

Contact modification​

It is possible to modify contacts after they have been computed by the narrow-phase. Contact-modification can have multiple advanced usages, for example:

  • The simulation of conveyor belts by modifying the tangent_velocity of solver contacts.
  • The simulation of one-way-platforms by deleting some contacts depending on the contact normal.
  • The simulation of colliders whose friction or restitution depends on where they are touched, by setting the coefficients from the contact points' location.

The PhysicsHooks.modify_solver_contacts method is called on each contact manifold between two colliders where at least one of them has the ActiveHooks.MODIFY_SOLVER_CONTACTS flag enabled in its active hooks.

warning

Contact modification can be used to remove some (or all) solver contacts from a contact manifold. However, it cannot be used to add new contacts manually. If this is something that could useful to you, please consider opening an issue to let us know about your use-case so we can see if this is worth adding.

Contact-modification lets you change most characteristics of a contact: the contact normal, the contact points and their penetration depth, and the tangent velocity. The friction and restitution coefficients are combined once per manifold, so they are set for the whole manifold (context.friction / context.restitution) rather than per contact. None of these modifications are persistent (they are overwritten during the next timestep). There is one exception though: you can modify a user_data associated to each ContactManifold. This user_data will persist throughout timesteps as long as the ContactManifold remains alive (i.e. as long as some contacts exist between the touching parts of the colliders shapes). This can be useful to apply modification rules that depend on previous states of the contact (like whether or not this contact manifold existed during previous timesteps).

The ContactModificationContext given to PhysicsHooks.modify_solver_contacts exposes the contact manifold being modified through its properties: its world-space contact normal, its friction and restitution coefficients, and its persistent user_data can be read and modified, whereas local_n1 and local_n2 give its contact normal in the local-space of each collider. Its solver contacts are given by solver_contacts (a list of copies of the SolverContact) and counted by num_solver_contacts. They can be modified one by one with set_solver_contact (given the index of the solver contact, and the new values of its point, point2, dist, or tangent_velocity as keyword arguments), removed one by one with remove_solver_contact, or all removed at once with clear_solver_contacts. set_tangent_velocity sets the tangent velocity of every solver contact of the manifold at once (e.g. for conveyor belts): it is the velocity of the surface of the second collider relative to the surface of the first one, so a belt dragging objects along a direction v sets v if it is collider1, and -v if it is collider2. Inside the hook, the contact points of a SolverContact (point and point2) are expressed in world-space. Note that this hook isn't called for the contacts between two soft surfaces, which are contact candidates rather than a contact manifold:

class MyPhysicsHooks:
def modify_solver_contacts(self, context):
# This is a silly example of contact modifier that does silly things
# for illustration purpose:
# - Flip all the contact normals.
# - Delete the first contact.
# - Set the friction coefficient to 0.3
# - Set the restitution coefficient to 0.4
# - Set the tangent velocities to X * 10.0
context.normal = -context.normal

if context.num_solver_contacts() > 0:
context.remove_solver_contact(0)

# Friction and restitution are combined once per manifold, so they are set
# for the whole manifold rather than per solver contact.
context.friction = 0.3
context.restitution = 0.4

for i in range(context.num_solver_contacts()):
context.set_solver_contact(i, tangent_velocity=(10.0, 0.0, 0.0))

# Use the persistent user-data to count the number of times
# contact modification was called for this contact manifold
# since its creation.
context.user_data += 1
print(f"Contact manifold has been modified {context.user_data} times since its creation.")


world.physics_hooks = MyPhysicsHooks()

Finally, ContactModificationContext.update_as_oneway_platform implements the removal of the contacts required for one-way-platforms (it relies on the user_data of the manifold). It only keeps the contacts whose normal, in the local-space of the first collider of the pair, is within the given angle of the given direction:

class OneWayPlatformHooks:
def __init__(self, platform):
self.platform = platform

def modify_solver_contacts(self, context):
# The allowed normal is expressed in the local-space of the first collider of the pair:
# it points upward if the platform is that first collider, and downward otherwise.
if context.collider1 == self.platform:
allowed_local_n1 = (0.0, 1.0, 0.0)
else:
allowed_local_n1 = (0.0, -1.0, 0.0)

# Remove the contacts unless the normal is within 45 degrees of the allowed one, so
# that the colliders can pass through the platform from below.
context.update_as_oneway_platform(allowed_local_n1, math.pi / 4.0)


platform_handle = world.add_collider(
rp.Collider.cuboid(2.0, 0.1, 2.0)
.translation((0.0, 3.0, 0.0))
.active_hooks(rp.ActiveHooks.MODIFY_SOLVER_CONTACTS)
)
world.physics_hooks = OneWayPlatformHooks(platform_handle)

Continuous Collision Detection​

Continuous Collision Detection (CCD) is used to make sure that fast-moving objects don't miss any contacts (a problem usually called tunneling). See the rigid-body CCD section for details.