Algorithmcore
Impulse-based simulation
Also called Mirtich-Canny impulse-based dynamics.
Simulate all contact, including resting contact, as a series of collision impulses, with friction resolved by integrating along the impulse.
- Solves
- Rigid body simulation
- Time
- O(n^2) next_event_brute_forceO(1) one_collisionO(c n^2) total_brute_force
- Space
- O(n) total
- Where
- c = the number of collision events; n = the number of bodies
- Model
- Real RAM
- Properties
- deterministicin placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Mirtich, John Canny, 1995
Impulse-based simulation treats every contact between rigid bodies as a collision. Between collisions each body follows a ballistic path. When two bodies come within a small distance , the collision envelope, and approach, the simulator applies one impulse that resolves the collision, with Coulomb friction and Poisson's hypothesis for restitution. A body that rests on a table is then a body that makes many tiny bounces. Mirtich and Canny (1995) built the method, with a heap of time of impact bounds and with microcollisions, which keep resting bodies from creeping.
In plain words
Most simulators treat a box on a table as a special case: the box touches the table, so the simulator computes a force that holds it up. This method has no such case. The box falls a tiny distance, hits the table, bounces up a tiny distance, and falls again. Each hit is handled like any other collision.
This makes the simulator simple. It needs only two parts: a part that finds the next collision, and a part that computes what one collision does. Between collisions, nothing touches, so each body flies freely under gravity.
The collision part is careful about friction. During a hit, the touching points can slide, then stop, then stay stuck or slide the other way. The method follows these changes along the hit instead of guessing the end result.
The problem
The input is a set of rigid bodies with their masses, inertia, positions and velocities, gravity , a coefficient of restitution , a friction coefficient , the envelope and an end time. The output is the state at the end time, such that no two bodies overlap and the collisions obey the collision model below.
The collision model has three assumptions, all stated by Mirtich and Canny in Section 4.1. A collision takes no time, so positions do not change during it. Poisson's hypothesis holds: with the normal impulse up to the point of maximum compression, where the normal relative velocity is zero, the total normal impulse is . Coulomb friction holds at every instant of the collision. These are empirical models. This page works in 2D, with discs on a ground line, where the collision can be integrated exactly; Mirtich and Canny work with convex polyhedra in 3D.
Notation for one contact: is the unit normal from to , is the tangent, and is the velocity of the contact point of minus that of . The impulse acts on , and on . By the Newton-Euler equations, with the symmetric matrix , which is positive definite when at least one body moves.
The algorithm
SIMULATE(bodies, t_end)- 1
t ← 0 - 2
loop - 3
(τ, A, B) ← the earliest time from now at which a pair is within ε_c and approaching - 4
if t + τ > t_end then move all bodies on ballistic paths to t_end; return - 5
move all bodies on ballistic paths by τ; t ← t + τ - 6
build n, t, the arms r_A, r_B, the matrix K and the contact velocity u - 7
if |u_n| < v_e and q = K⁻¹(-2u) lies in the friction cone then p ← q ▷ microcollision - 8
else p ← COLLIDE(K, u, μ, e′), with e′ = 1 if |u_n| < v_e, else e′ = e - 9
apply p to A and -p to B COLLIDE(K, u, μ, e)- 10
p ← 0; target ← none - 11
repeat - 12
d ← (d_t, 1): slide d_t = -μ sgn u_t; stick d_t = -K_tn/K_tt if u_t = 0 and |K_tn| ≤ μ K_tt; else slide again d_t = -μ sgn K_tn - 13
δ ← the smallest step in p_n to the next event: u_t reaches 0, u_n reaches 0, or p_n reaches target - 14
p ← p + δ d; u ← u + δ K d - 15
if u_n reached 0 then target ← (1 + e) p_n ▷ maximum compression - 16
until p_n = target - 17
return p
The threshold is the speed that a body at rest gains when it falls through the envelope (Mirtich and Canny, eq. 12). A microcollision reverses the whole contact velocity. It is used only when that impulse lies inside the friction cone, so that friction could provide it.
COLLIDE follows Mirtich and Canny in using as the collision parameter: it starts at zero and only grows, while time inside the collision is not known. While the contact slides, the friction impulse grows at times the normal impulse against the slip. In 2D the slip direction is just a sign, so within one phase is a straight line in , and each event takes one division. In 3D the slip direction turns during the collision, and Mirtich and Canny integrate a nonlinear differential equation numerically instead of L12 to L14.
Line L8 with is a choice of this page, not of the paper: a slow contact whose reversing impulse is outside the cone slides, and keeping its normal speed makes the bounces deliver, on average, a normal impulse equal to the weight. Without it, the bounces of a sliding disc shrink geometrically and pile up in a finite time while the disc still slides.
Example
One collision. A rod of mass 1 and length 2 () hits the ground with its lower tip at the arm from its center, with . Then . The rod moves with and , so . Take and .
| phase | mode | ends at | at the end | at the end | |
|---|---|---|---|---|---|
| 1 | slide | ||||
| 2 | stick | ||||
| 3 | stick |
The test is , so the tip stays stuck after the slip stops. The kinetic energy changes by . For the same rod, Newton's law with a full stop of the slip gives the impulse and adds to the energy (see coefficient of restitution). With the test fails (), and the tip slides again in the other direction for the rest of the collision.
A disc with backspin. A disc of mass 1 and radius falls from above the envelope with and spin , with , and . At every contact the impulse acts at the contact point, so the angular momentum about that point, , does not change, and the flights do not change it either. When the slip stops, , the same rolling speed as the continuous Coulomb model. The measured runs over 2 s:
| rolling speed | events in 2 s | slip stops at | |
|---|---|---|---|
| 4 | 94 | about 0.286 s | |
| 12 | 94 | about 0.536 s |
With the disc rolls back. The continuous model with the normal force from the first contact at s predicts the stops at s and s: the impulse model stops the slip earlier because the landing impulse is much larger than the weight.
Correctness
The proof is in proofs/correctness.md. Its main steps are proved properties of the 2D model:
- COLLIDE ends after at most three phases. The slip can stop at most once; after it stops, the contact either stays stuck or slides the other way forever. The normal velocity increases in every phase except a slide phase that is about to stop, which uses that is positive definite.
- The result satisfies , , friction against the slip in every slide phase, and .
- A microcollision changes to and does no work: . Mirtich and Canny state this property in Section 4.5.
- Between events the motion is exact, and the loop finds the first time at which some pair is within and approaching.
- A single disc at rest has a bounded event rate: after the first slow event, its approach speed is fixed in , so events are at least apart, and the gap stays below .
Proof: The 2D collision integration ends after at most three phases and obeys Poisson's hypothesis and Coulomb friction, and microcollisions do no workfull
The setting is the 2D version of the page. A contact between bodies and has the unit normal from to and the tangent . The contact velocity is , the velocity of the material point of at the contact minus that of , in the frame . An impulse in this frame acts on , and acts on . Positions do not change during a collision.
Lemma 1 (linear response). There is a symmetric matrix with for every impulse applied so far, and is positive definite if at least one body is not static. In particular , and .
Proof. By the Newton-Euler equations integrated over an instant, an impulse at the arm changes by and by , so the point velocity changes by . Its component along a unit vector is , which is linear in . Summing over (impulse ) and (impulse ) gives for . For one body that is not static, this is times the identity plus the positive semidefinite rank one matrix with , so it is positive definite. A sum with a positive semidefinite term stays positive definite. The diagonal entries and the Schur complement of a positive definite matrix are positive.
In COLLIDE, the parameter is , and in each phase is constant. By Lemma 1, then changes at the constant rate , with and . The three modes are: slide, with when ; stick, with when and ; and slide again, with when and .
Lemma 2 (the normal velocity rises unless the slip is about to stop). In the stick mode and in the slide again mode, . In the slide mode, if (the slip does not decrease), then .
Proof. Stick: . Slide again: , and gives , so . Slide with : means , that is . If , then . Otherwise by multiplying the inequality by , and .
Lemma 3 (the sequence of modes). The event "u_t reaches 0" happens at most once. After it, the mode is stick for the rest of the collision, or slide again followed by slide with the same sign for the rest of the collision.
Proof. The stop event can only end a slide phase with . After it, . In the stick mode , so stays and the mode stays stick. In the slide again mode with , has the sign , so takes the sign at once, the next mode is slide with and the same , and , so no stop event follows.
Theorem 1 (termination). If and is positive definite, COLLIDE returns after at most three phases.
Proof. Each phase ends at exactly one of the events stop, max (u_n reaches 0) and end (p_n reaches the target), whichever comes first. The step to each event is nonnegative: during compression , so when ; a stop is listed only when ; and the target is at least the current . During compression the list of candidate events is never empty: if the mode is slide with , the stop is a candidate; otherwise by Lemma 2, and max is a candidate. During restitution, end is always a candidate. Stop happens at most once (Lemma 3), max exactly once (after it, the target is set and max is no longer a candidate), and end ends the procedure. So there are at most three phases.
Theorem 2 (the result obeys the model). Let be the result and the value of at the max event. Then:
- (Poisson's hypothesis), and , with when .
- , and more strongly, the impulse increment of every phase lies in the friction cone.
- In every slide phase, the friction increment opposes the slip, which has a constant sign in the phase. In a stick phase, throughout. The choice between stick and slide again at is the only one that is consistent with the Coulomb law under the rule that friction keeps the contact stuck when it can (the assumption of Routh, used by Mirtich and Canny in Section 4.4).
Proof. (1) The target is set to at the max event, and the procedure returns when reaches it. The phase in which max happens has . Every later phase comes after a stop or is the same mode continued, so by Lemma 2 and Lemma 3 it also has . Hence increases from during the whole restitution of length , so , and if (note because ).
(2) In every mode : for stick this is the test . Integrating over the phases gives .
(3) A slide phase ends when reaches , so has a constant sign in it, and is the Coulomb force direction of a sliding contact. At : if the contact stays stuck, forces , which is allowed exactly when . Otherwise the contact must slide with some sign and ; then must have the sign , which holds for and fails for , because then has the sign .
Within one phase, is an affine function of (Lemma 1 with constant ), so the event steps computed by one division are exact, and with exact rational input the procedure returns the exact solution of the piecewise linear model.
Theorem 3 (microcollisions do no work). If the impulse is applied, then , and the total kinetic energy of the two bodies does not change.
Proof. by Lemma 1. For one body and an impulse at the arm , and , whose sum is , where is the velocity of the material point at the contact. Summing over with and with gives .
Theorem 4 (the simulation loop for discs). Assume or no ground, and that every contact handled by the loop has positive definite. Then:
- The motion between events is exact, and each event time is the first time at which some pair has a gap of at most and closes it.
- For discs, and are parallel to , so , in every mode, and is the rate of change of the gap.
- After every resolved event, , so a pair that is inside the envelope is never closing after the loop has handled it at that time.
Proof. (1) Between events every body moves under gravity alone, , which the loop applies in closed form. The gap to the ground is quadratic in , and the root used is the later root of , the time at which the gap falls to . For two discs the gravity terms cancel, the relative position is linear in , and the smaller root of is the entry time, which exists only if . The loop takes the minimum over all pairs, so no earlier event is skipped.
(2) The contact point is , so and . Then and . The rotation term of the point velocity along is , so , the rate of change of the gap.
(3) A collision ends with by Theorem 2, and a microcollision with by Theorem 3.
Corollary (a single resting disc has a bounded event rate). Take one disc on the ground, , , and let the first event have an approach speed of at least . After the first event with an approach speed below , every event happens at the gap with the same approach speed , so the events are apart, and the gap stays below .
Proof. By (2), , so a collision under Poisson's hypothesis maps the approach speed to the separation speed , and the slow sliding rule of line L8 () and a microcollision map it to . A ballistic flight that starts and ends at the same gap returns with the speed it started with. So the approach speeds before the first slow event are , all at least . The first slow event has the speed with , so its speed is at least , and from then on the speed does not change. The height formula is the apex of the ballistic flight.
What is not proved. The theorems are about the model: instantaneous collisions, Poisson's hypothesis, Coulomb friction with Routh's sticking rule, and the collision envelope. Nothing here says that the model matches real impacts. The rule that a slow, sliding contact uses is a heuristic of this page. The event rate bound is only for a single disc; for stacks and for bodies other than discs, the number of collisions per unit time is not bounded by this argument and can grow without limit, which is the known weakness of the method for resting contact. In 3D the sliding direction turns during a collision, the integration is a numerical solve of a nonlinear differential equation, and Mirtich and Canny state the uniqueness of the outward sliding direction as a conjecture.
Complexity
One collision costs : at most three phases of constant work in 2D. Finding the next event by brute force costs per event, as on this page. Mirtich and Canny keep the pairs in a heap ordered by a lower bound on the time of impact, recompute bounds only for pairs that involve a body that just collided, and cut the candidate pairs with a hierarchy of spatial hash tables, so that bodies far apart are never tested. The total cost is the number of events times the cost per event, and the number of events is the weak point: it depends on the scene, and for resting contact it grows as shrinks, since one resting disc makes up to events per second. For a stack of bodies, the event rate is a measurement, not a bound.
Properties
- Every contact is a collision, so there is no list of contact states to keep and no switching between resting and colliding modes.
- Bodies never touch: collisions happen at the gap . Resting bodies hover in .
- The Coulomb law holds within each collision, including the stops and reversals of slip.
- Linear momentum is conserved in collisions between moving bodies, and angular momentum too, because both impulses act at the same point.
- With and , the kinetic energy is conserved.
- The friction result is not that of a continuous contact force with the same ; see the second example.
Variants and improvements
- 3D. The sliding direction rotates during the collision. Mirtich and Canny integrate the relative velocity numerically and solve a quartic when the slip stops and must resume; they conjecture that the outward sliding direction is unique.
- Other restitution laws. Newton's law on velocities, Poisson's law on impulses and Stronge's energetic coefficient agree without friction and differ with it. Newton's law with friction can add energy (the rod example). Stronge's energetic coefficient compares the work of the normal force in restitution with that in compression.
- Simultaneous contacts. Treating the contacts of a stack one at a time is slow and can be order dependent. Projected Gauss-Seidel with accumulated impulses solves all contacts of a step together, and shock propagation orders them from the ground up.
- Time stepping. Instead of exact event times, a fixed step can collect all contacts within the envelope and resolve them together, as in Stewart-Trinkle time stepping. That bounds the work per unit time but gives up the exact order of the collisions.
When to use it
Use it for scenes with many brief collisions and few long contacts: a pool break or parts in a vibratory feeder, two examples of Mirtich and Canny. Avoid it for tall stacks, bodies at rest in large numbers, and joints: the event rate for resting contact is high, and joints are not collisions. A penalty or constraint-based method, or a time-stepping method with a velocity solver, is the usual choice there.
Pitfalls
- Zeno behaviour. With and exact event times, a body that bounces with friction can make infinitely many collisions in a finite time. The microcollision rule and the slow sliding rule above prevent it for one disc, but a body that starts exactly at the envelope with zero velocity, or a contrived stack, can still produce events with speeds that tend to zero.
- Creep on a ramp. Without microcollisions, a block on a ramp creeps down even when is large, because it falls during every flight. Mirtich and Canny show that microcollisions stop it.
- The envelope is a tuning value. A large makes resting bodies hover visibly; a small one raises the event rate. The threshold follows from it and from .
- Sign of the normal. COLLIDE assumes at the start and the normal from to . A wrong sign gives an impulse that pulls.
- Rounding at the stop. In floating point, set to zero exactly at the stop event; otherwise the next phase may see a tiny slip of either sign.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impulse-based-simulation/. The authors are listed in prov/P8GDCY.jsonl.
"""Impulse-based simulation of discs on a ground line in 2D, after Mirtich and Canny (1995).
Every contact, also resting contact, is a collision: an impulse at one
instant. Between collisions all bodies move on ballistic paths, which this
version follows exactly. A collision is detected when the gap between two
bodies falls to the collision envelope eps_c while they approach.
The collision impulse uses Poisson's hypothesis and Coulomb friction, and it
is integrated along the collision with the normal impulse p_n as the
parameter (Mirtich and Canny, Section 4). In 2D the direction of the
friction impulse is constant within each phase, so the integration is exact:
it moves along straight lines in impulse space from one event to the next.
Conventions: y is up, gravity is (0, -g). The contact normal n points from
B to A, the tangent is t = (n_y, -n_x), and the contact velocity u = (u_t,
u_n) is the velocity of A at the contact point minus that of B. The impulse
p = (p_t, p_n), in the frame (t, n), acts on A, and -p acts on B. The matrix
K maps an impulse to the change of u; it is stored as (K_tt, K_tn, K_nn).
"""
import math
class Disc:
"""A uniform disc: center x, velocity v, angle theta, angular velocity w, mass m, radius."""
def __init__(self, x, v, w, m, radius, theta=0):
self.x = tuple(x)
self.v = tuple(v)
self.w = w
self.theta = theta
self.m = m
self.radius = radius
self.I = m * radius * radius / 2
self.inv_m = 1 / m
self.inv_I = 1 / self.I
class Ground:
"""The static half plane y <= 0."""
inv_m = 0
inv_I = 0
v = (0, 0)
w = 0
GROUND = Ground()
def cross2(a, b):
return a[0] * b[1] - a[1] * b[0]
def point_velocity(body, r):
"""v + w x r in 2D."""
return (body.v[0] - body.w * r[1], body.v[1] + body.w * r[0])
def contact_frame(n):
return (n[1], -n[0]), n
def contact_matrix(a, b, r_a, r_b, n):
"""K_de = sum over the bodies of inv_m (d . e) + inv_I (r x d)(r x e), for d, e in {t, n}."""
t, n = contact_frame(n)
ktt = a.inv_m + b.inv_m + a.inv_I * cross2(r_a, t) ** 2 + b.inv_I * cross2(r_b, t) ** 2
ktn = a.inv_I * cross2(r_a, t) * cross2(r_a, n) + b.inv_I * cross2(r_b, t) * cross2(r_b, n)
knn = a.inv_m + b.inv_m + a.inv_I * cross2(r_a, n) ** 2 + b.inv_I * cross2(r_b, n) ** 2
return ktt, ktn, knn
def contact_velocity(a, b, r_a, r_b, n):
t, n = contact_frame(n)
va, vb = point_velocity(a, r_a), point_velocity(b, r_b)
du = (va[0] - vb[0], va[1] - vb[1])
return du[0] * t[0] + du[1] * t[1], du[0] * n[0] + du[1] * n[1]
def apply_impulse(a, b, r_a, r_b, n, p):
"""Apply p_t t + p_n n to A at r_a and the opposite impulse to B at r_b."""
t, n = contact_frame(n)
imp = (p[0] * t[0] + p[1] * n[0], p[0] * t[1] + p[1] * n[1])
for body, r, s in ((a, r_a, 1), (b, r_b, -1)):
if body.inv_m == 0:
continue
body.v = (body.v[0] + s * imp[0] * body.inv_m, body.v[1] + s * imp[1] * body.inv_m)
body.w = body.w + s * body.inv_I * cross2(r, imp)
def microcollision_impulse(K, u):
"""The impulse p with K p = -2 u, which reverses the contact velocity."""
ktt, ktn, knn = K
det = ktt * knn - ktn * ktn
return (-2 * (knn * u[0] - ktn * u[1]) / det, -2 * (ktt * u[1] - ktn * u[0]) / det)
def collide(K, u, mu, e, trace=None):
"""Integrate a frictional collision with Poisson's hypothesis; return p = (p_t, p_n).
The parameter is p_n. In each phase dp/dp_n = d = (d_t, 1) is constant:
sliding uses d_t = -mu sgn(u_t), sticking uses d_t = -K_tn / K_tt, and
sliding again from rest uses d_t = -mu sgn(K_tn). A phase ends at the next
event: u_t reaches 0, u_n reaches 0 (maximum compression, which fixes the
end of the collision at p_n = (1 + e) p_mc), or p_n reaches that end.
If trace is a list, one tuple (mode, event, p_t, p_n, u_t, u_n) is added per phase.
"""
ktt, ktn, knn = K
ut, un = u
if un >= 0:
return 0 * ut, 0 * un
pt, pn = 0 * ut, 0 * un # @line L10
target = None # @line L10
for _ in range(16): # @line L11
if ut != 0: # @line L12
mode, dt = "slide", (-mu if ut > 0 else mu) # @line L12
elif abs(ktn) <= mu * ktt: # @line L12
mode, dt = "stick", -ktn / ktt # @line L12
else: # @line L12
mode, dt = "slide again", (-mu if ktn > 0 else mu) # @line L12
dut = ktt * dt + ktn
dun = ktn * dt + knn
steps = [] # @line L13
if mode == "slide" and ut * dut < 0: # @line L13
steps.append((-ut / dut, "stop")) # @line L13
if target is None: # @line L13
if dun > 0: # @line L13
steps.append((-un / dun, "max")) # @line L13
else: # @line L13
steps.append((target - pn, "end")) # @line L13
if not steps:
raise RuntimeError("no event ahead; K must be positive definite")
h, event = min(steps, key=lambda s: s[0]) # @line L13
h = max(h, 0 * h)
pt, pn = pt + dt * h, pn + h # @line L14
ut, un = ut + dut * h, un + dun * h # @line L14
if event == "stop":
ut = 0 * ut
if trace is not None:
trace.append((mode, event, pt, pn, ut, un))
if event == "max": # @line L15
un = 0 * un # @line L15
target = (1 + e) * pn # @line L15
elif event == "end": # @line L16
return pt, pn # @line L17
raise RuntimeError("too many phases")
def in_cone(p, mu):
return p[1] >= 0 and abs(p[0]) <= mu * p[1]
def contact_geometry(a, b):
"""Normal n (from B to A) and arms for the point p of A that is nearest to B."""
if b is GROUND:
n = (0, 1)
r_a = (0, -a.radius)
p = (a.x[0], a.x[1] - a.radius)
return n, r_a, p
d = (a.x[0] - b.x[0], a.x[1] - b.x[1])
length = math.hypot(d[0], d[1])
n = (d[0] / length, d[1] / length)
r_a = (-a.radius * n[0], -a.radius * n[1])
p = (a.x[0] + r_a[0], a.x[1] + r_a[1])
return n, r_a, p
def resolve(a, b, mu, e, v_e):
"""Resolve one detected contact. Return "micro", "collision" or "none"."""
n, r_a, p = contact_geometry(a, b) # @line L6
r_b = (p[0] - b.x[0], p[1] - b.x[1]) if b is not GROUND else (0, 0) # @line L6
K = contact_matrix(a, b, r_a, r_b, n) # @line L6
u = contact_velocity(a, b, r_a, r_b, n) # @line L6
if u[1] >= 0:
return "none"
e_used = e
if -u[1] < v_e: # @line L7
q = microcollision_impulse(K, u) # @line L7
if in_cone(q, mu): # @line L7
apply_impulse(a, b, r_a, r_b, n, q) # @line L9
return "micro"
# A slow contact that slides: resolve it with e = 1. This choice of the
# page keeps the normal speed, so the bounces do not pile up in finite time.
e_used = 1 # @line L8
q = collide(K, u, mu, e_used) # @line L8
apply_impulse(a, b, r_a, r_b, n, q) # @line L9
return "collision"
def ground_event_time(disc, eps_c, g):
"""First time at which the gap to the ground is at most eps_c and closing."""
h = disc.x[1] - disc.radius - eps_c
vy = disc.v[1]
if h <= 0 and vy < 0:
return 0.0
if g == 0:
return h / -vy if (vy < 0 and h > 0) else math.inf
return (vy + math.sqrt(vy * vy + 2 * g * max(h, 0))) / g
def pair_event_time(a, b, eps_c):
"""First time at which the gap between two discs is at most eps_c and closing.
Gravity acts on both, so the relative motion is a straight line."""
d = (a.x[0] - b.x[0], a.x[1] - b.x[1])
w = (a.v[0] - b.v[0], a.v[1] - b.v[1])
s = a.radius + b.radius + eps_c
qa = w[0] * w[0] + w[1] * w[1]
qb = 2 * (d[0] * w[0] + d[1] * w[1])
qc = d[0] * d[0] + d[1] * d[1] - s * s
if qb >= 0 or qa == 0:
return math.inf
if qc <= 0:
return 0.0
disc = qb * qb - 4 * qa * qc
if disc < 0:
return math.inf
return 2 * qc / (-qb + math.sqrt(disc))
def drift(discs, tau, g):
"""Move every disc on its ballistic path for the time tau."""
for d in discs:
d.x = (d.x[0] + d.v[0] * tau, d.x[1] + d.v[1] * tau - g * tau * tau / 2)
d.v = (d.v[0], d.v[1] - g * tau)
d.theta = d.theta + d.w * tau
def simulate(discs, t_end, mu, e, eps_c, g=9.81, ground=True, max_events=200000):
"""Run the simulation from t = 0 to t_end. Return the list of events (t, i, j, kind, u_n).
j is -1 for the ground. The discs are changed in place."""
v_e = math.sqrt(2 * g * eps_c)
t = 0.0 # @line L1
log = []
while True: # @line L2
best = (math.inf, None, None) # @line L3
for i, a in enumerate(discs): # @line L3
if ground: # @line L3
tau = ground_event_time(a, eps_c, g) # @line L3
if tau < best[0]: # @line L3
best = (tau, i, -1) # @line L3
for j in range(i + 1, len(discs)): # @line L3
tau = pair_event_time(a, discs[j], eps_c) # @line L3
if tau < best[0]: # @line L3
best = (tau, i, j) # @line L3
tau, i, j = best
if t + tau > t_end: # @line L4
drift(discs, t_end - t, g) # @line L4
return log # @line L4
drift(discs, tau, g) # @line L5
t += tau # @line L5
a, b = discs[i], (GROUND if j < 0 else discs[j])
n, r_a, p = contact_geometry(a, b)
r_b = (p[0] - b.x[0], p[1] - b.x[1]) if b is not GROUND else (0, 0)
un = contact_velocity(a, b, r_a, r_b, n)[1]
kind = resolve(a, b, mu, e, v_e)
log.append((t, i, j, kind, un))
if len(log) > max_events:
raise RuntimeError("too many events")
def kinetic_energy(discs):
return sum(d.m * (d.v[0] ** 2 + d.v[1] ** 2) / 2 + d.I * d.w * d.w / 2 for d in discs)
def linear_momentum(discs):
return (sum(d.m * d.v[0] for d in discs), sum(d.m * d.v[1] for d in discs))
def angular_momentum(discs, origin=(0, 0)):
total = 0
for d in discs:
r = (d.x[0] - origin[0], d.x[1] - origin[1])
total += d.m * cross2(r, d.v) + d.I * d.w
return total
test_impulse_based_simulation.py 195 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impulse-based-simulation/. The authors are listed in prov/P8GDCY.jsonl.
import math
import random
from fractions import Fraction as F
from impulse_based_simulation import (
GROUND,
Disc,
angular_momentum,
apply_impulse,
collide,
contact_matrix,
contact_velocity,
kinetic_energy,
linear_momentum,
microcollision_impulse,
simulate,
)
G = 9.81
def energy_change(K, u, p):
"""T+ - T- = p . u + p^T K p / 2 for an impulse p at the contact."""
ktt, ktn, knn = K
return p[0] * u[0] + p[1] * u[1] + (ktt * p[0] ** 2 + 2 * ktn * p[0] * p[1] + knn * p[1] ** 2) / 2
def random_spd(rng, exact):
if exact:
a, b = F(rng.randint(-8, 8), rng.randint(1, 4)), F(rng.randint(-8, 8), rng.randint(1, 4))
c = F(rng.randint(1, 8), rng.randint(1, 4))
return a * a + F(1, 5), a * b, b * b + c * c
a, b, c = rng.uniform(0.3, 1.5), rng.uniform(-1.5, 1.5), rng.uniform(0.3, 1.5)
return a * a, a * b, b * b + c * c
def test_page_example_rod():
K = (F(73, 25), F(36, 25), F(52, 25))
u = (F(-1, 2), F(-1))
trace = []
p = collide(K, u, F(1, 2), F(1), trace)
assert [(m, ev) for m, ev, *_ in trace] == [("slide", "stop"), ("stick", "max"), ("stick", "end")]
assert trace[0][2:] == (F(5, 58), F(5, 29), 0, F(-15, 29))
assert trace[1][2:4] == (F(-1, 10), F(11, 20))
assert p == (F(-271, 730), F(11, 10))
assert (u[0] + K[0] * p[0] + K[1] * p[1], u[1] + K[1] * p[0] + K[2] * p[1]) == (0, F(55, 73))
assert energy_change(K, u, p) == F(-25, 584)
trace = []
collide(K, u, F(1, 5), F(1), trace)
assert [m for m, *_ in trace] == ["slide", "slide again", "slide"]
def test_collide_poisson_cone_and_phase_bound_exact():
rng = random.Random(2)
for _ in range(300):
K = random_spd(rng, True)
u = (F(rng.randint(-12, 12), 4), F(-rng.randint(1, 12), 4))
mu, e = F(rng.randint(0, 12), 10), F(rng.randint(0, 4), 4)
trace = []
p = collide(K, u, mu, e, trace)
assert len(trace) <= 3
assert abs(p[0]) <= mu * p[1]
p_mc = [s[3] for s in trace if s[1] == "max"]
assert len(p_mc) == 1 and p[1] == (1 + e) * p_mc[0]
for mode, _, pt, pn, ut, un in trace:
assert abs(pt) <= mu * pn
if mode == "stick":
assert ut == 0
modes = [s[0] for s in trace]
if "stick" in modes:
assert modes[modes.index("stick"):] == ["stick"] * (len(modes) - modes.index("stick"))
u_end = u[0] + K[0] * p[0] + K[1] * p[1]
assert u_end == 0
def test_collide_frictionless_is_the_newton_impulse():
rng = random.Random(4)
for _ in range(100):
K = random_spd(rng, True)
u = (F(rng.randint(-12, 12), 4), F(-rng.randint(1, 12), 4))
e = F(rng.randint(0, 4), 4)
assert collide(K, u, 0, e) == (0, -(1 + e) * u[1] / K[2])
def euler_collide(K, u, mu, e, h):
"""Small fixed steps in p_n with the sign rule of Coulomb friction and no sticking logic."""
ktt, ktn, knn = K
ut, un = u
pt = pn = 0.0
target = None
while target is None or pn < target:
dt = -mu if ut > 0 else (mu if ut < 0 else 0.0)
pt, pn = pt + dt * h, pn + h
ut, un = ut + (ktt * dt + ktn) * h, un + (ktn * dt + knn) * h
if target is None and un >= 0:
target = (1 + e) * pn
return pt, pn
def test_collide_matches_fine_integration():
rng = random.Random(6)
for _ in range(12):
K = random_spd(rng, False)
u = (rng.uniform(-2, 2), rng.uniform(-1.5, -0.3))
mu, e = rng.uniform(0, 1), rng.uniform(0, 1)
p = collide(K, u, mu, e)
q = euler_collide(K, u, mu, e, 2e-4)
assert abs(p[0] - q[0]) < 5e-3 * (1 + abs(p[0])) and abs(p[1] - q[1]) < 5e-3 * (1 + p[1])
def test_microcollision_does_no_work():
rng = random.Random(8)
for _ in range(50):
a = Disc((0, F(1, 2)), (F(rng.randint(-8, 8), 8), F(-rng.randint(1, 8), 8)), F(rng.randint(-8, 8), 4),
F(rng.randint(1, 6)), F(1, 2))
b = Disc((F(rng.randint(-4, 4), 4), F(-1)), (F(rng.randint(-8, 8), 8), F(0)), F(rng.randint(-8, 8), 4),
F(rng.randint(1, 6)), F(1, 3))
for other in (GROUND, b):
n = (0, 1)
r_a = (0, -a.radius)
r_b = (0, 0) if other is GROUND else (a.x[0] - other.x[0], a.x[1] - a.radius - other.x[1])
K = contact_matrix(a, other, r_a, r_b, n)
u = contact_velocity(a, other, r_a, r_b, n)
bodies = [a] if other is GROUND else [a, other]
t0 = kinetic_energy(bodies)
apply_impulse(a, other, r_a, r_b, n, microcollision_impulse(K, u))
assert kinetic_energy(bodies) == t0
assert contact_velocity(a, other, r_a, r_b, n) == (-u[0], -u[1])
def test_drop_check_value():
eps = 1e-4
ball = Disc((0.0, 0.5 + eps + 1.0), (0.0, 0.0), 0.0, 1.0, 0.5)
log = simulate([ball], 0.6, mu=0.5, e=0.5, eps_c=eps)
assert len(log) == 1 and log[0][3] == "collision"
assert abs(log[0][0] - math.sqrt(2 / G)) < 1e-12
height = ball.x[1] - 0.5 - eps + ball.v[1] ** 2 / (2 * G)
assert abs(height - 0.25) < 1e-12
def random_gas(rng, count):
discs = []
while len(discs) < count:
x = (rng.uniform(-3, 3), rng.uniform(-3, 3))
r = rng.uniform(0.2, 0.5)
if all(math.hypot(x[0] - d.x[0], x[1] - d.x[1]) > r + d.radius + 0.1 for d in discs):
v = (-x[0] / 2 + rng.uniform(-1, 1), -x[1] / 2 + rng.uniform(-1, 1))
discs.append(Disc(x, v, rng.uniform(-2, 2), rng.uniform(0.5, 3), r))
return discs
def test_elastic_frictionless_gas_keeps_energy_and_momentum():
rng = random.Random(10)
discs = random_gas(rng, 6)
t0, p0, l0 = kinetic_energy(discs), linear_momentum(discs), angular_momentum(discs)
log = simulate(discs, 6.0, mu=0.0, e=1.0, eps_c=1e-3, g=0.0, ground=False)
assert len(log) >= 5
assert abs(kinetic_energy(discs) - t0) < 1e-9 * t0
assert all(abs(x - y) < 1e-9 for x, y in zip(linear_momentum(discs), p0))
assert abs(angular_momentum(discs) - l0) < 1e-9
def test_frictional_gas_keeps_momentum_and_loses_energy():
rng = random.Random(12)
discs = random_gas(rng, 6)
t0, p0, l0 = kinetic_energy(discs), linear_momentum(discs), angular_momentum(discs)
log = simulate(discs, 6.0, mu=0.4, e=0.7, eps_c=1e-3, g=0.0, ground=False)
assert len(log) >= 2
assert kinetic_energy(discs) < t0
assert all(abs(x - y) < 1e-9 for x, y in zip(linear_momentum(discs), p0))
assert abs(angular_momentum(discs) - l0) < 1e-9
def test_disc_with_backspin_ends_rolling_at_the_coulomb_speed():
for w0, v_final in ((4.0, 2 / 3), (12.0, -2 / 3)):
disc = Disc((0.0, 0.5 + 1e-3 + 0.1), (2.0, 0.0), w0, 1.0, 0.5)
simulate([disc], 2.0, mu=0.5, e=0.5, eps_c=1e-3)
assert abs(disc.v[0] + disc.w * disc.radius) < 1e-9
assert abs(disc.v[0] - v_final) < 1e-9
def test_resting_disc_has_a_bounded_event_rate():
eps = 1e-3
v_e = math.sqrt(2 * G * eps)
disc = Disc((0.0, 0.5 + eps + 0.05), (0.3, 0.0), 0.0, 1.0, 0.5)
log = simulate([disc], 3.0, mu=0.3, e=0.5, eps_c=eps)
late = [ev for ev in log if ev[0] >= 2.0]
assert late and all(kind == "micro" for _, _, _, kind, _ in late)
assert all(0.5 * v_e <= -un < v_e for *_, un in late)
assert len(late) <= G / (2 * 0.5 * v_e) + 1
gap = disc.x[1] - disc.radius
assert eps - 1e-12 <= gap + disc.v[1] ** 2 / (2 * G) < 2 * eps
History
Hahn (1988) and Moore and Wilhelms (1988) used impulses for collisions in computer animation, next to other methods for resting contact. Baraff's analytical methods (1989 to 1994) computed contact forces with complementarity instead. Mirtich and Canny (1995) took the other road and handled all contact with impulses. They built on the impact analysis of Routh, with Keller (1986) and Bhatt and Koechling (1994) for frictional impacts, and on the Lin-Canny closest features algorithm for distances. Stronge (1990) analyzed the coefficients of restitution for collisions with friction.
References
- Brian Mirtich and John Canny, Impulse-based simulation of rigid bodies, Proceedings of the 1995 Symposium on Interactive 3D Graphics, 181-188, Section 3 (collision heap and time of impact bounds), Section 4 (Poisson's hypothesis, the collision parameter p_z, sliding and sticking modes) and Section 4.5 (static contact and microcollisions, v_e = sqrt(2 g eps_c))
- James K. Hahn, Realistic animation of rigid bodies, SIGGRAPH 88, Computer Graphics 22(4), 299-308, 1988, impulse-based collision response, an earlier use of impulses in animation
- W. J. Stronge, Rigid body collisions with friction, Proceedings of the Royal Society of London A 431(1881), 169-181, 1990, the kinematic, kinetic and energetic coefficients of restitution for collisions with friction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag P8GDCY Edit this page History Report an error Markdown