Techniqueresearch
Small steps in physics simulation
Also called substepping XPBD.
Split each frame into many substeps with one XPBD iteration each instead of one step with many iterations; in the paper's tests this gives a much smaller error for the same cost.
Small steps is a way to spend the work of a constraint solver. A simulation with XPBD usually takes one time step per frame and runs many Gauss-Seidel iterations over the constraints. Macklin, Storey, Lu, Terdiman, Chentanez, Jeschke and Müller (2019) split the frame instead into substeps of length and run one iteration in each. For the same number of constraint sweeps per frame, their measurements show a much smaller constraint error. A heuristic explanation is that a short substep starts closer to the solution, so one iteration is enough.
In plain words
Imagine a chain that must keep the length of each link. The solver moves the beads to fix the links, one link at a time. If you take one big step and then fix the links many times, each pass fixes one link but breaks its neighbors a little, and the errors creep slowly through the chain. If you take many tiny steps instead and fix each link once per step, the beads never move far from a good state, so there is little to fix. The work is the same in both cases, but the tiny steps give a chain that stretches much less.
When it applies
- Constraint solvers with local iterations. The idea is for position based dynamics and XPBD, where one iteration is cheap and its convergence over many iterations is slow.
- Stiff constraints and high mass ratios. Gauss-Seidel converges slowly on long chains and with heavy bodies hanging from light ones; small steps reduce this error the most (measured below and in Section 6.1 of the paper).
- Explicit prediction. Each substep starts with an explicit symplectic Euler prediction. Smaller steps make it more accurate, so the error in time falls as well.
- Cheap collision detection per frame. Section 4.2 of the paper finds contact candidates once per frame and reuses them in all substeps; this keeps the cost of the substeps close to the cost of the iterations they replace.
The template
SMALL-STEPS-FRAME(x, v, constraints, Δt, n)- 1
h <- Δt / n - 2
repeat n times: - 3
v <- v + h f_ext / m ▷ for each free particle - 4
p <- x; x <- x + h v - 5
λ <- 0 ▷ the multipliers restart in each substep - 6
one iteration over the constraints j: - 7
Δλ_j <- (-C_j(x) - α̃_j λ_j) / (∇C_j M⁻¹ ∇C_jᵀ + α̃_j), α̃_j = α_j / h² - 8
x <- x + M⁻¹ ∇C_jᵀ Δλ_j; λ_j <- λ_j + Δλ_j - 9
v <- (x - p) / h
L7 is equation (7) of the paper. With one iteration and the term is zero, so the update is the plain XPBD projection with compliance. The code runs L6 for a given number of iterations so that it can compare both ways of spending a fixed budget. It is a 2D chain of particles with the first particle pinned.
One constraint, one iteration (proved). For a single distance constraint with , one iteration of L7 and L8 sets the distance exactly to the rest length along the current direction, so more iterations change nothing; only more substeps reduce the time error. The test checks this.
Why it works (heuristic). In a substep of length the prediction moves each particle by from a state that satisfied the constraints after the last substep, so the violation that the solver has to remove is small, and one Gauss-Seidel sweep removes most of it. With many iterations in one large step the solver must instead spread a large correction through the whole chain, which takes a number of sweeps that grows with the chain length and the mass ratio.
Order (measured). Section 7 of the paper notes that the velocity is first order in . On the pendulum below, the position error after 1 s falls by 10 for each factor 10 in .
Classic examples
A heavy chain (measured). A chain of 20 particles with spacing 0.1 m hangs from its first particle, starts horizontal at rest, and falls under gravity for 60 frames of s, with . The budget is 100 constraint sweeps per frame. The table gives the largest relative stretch at the end.
| last particle mass / other masses | 100 iterations, 1 substep | 10 iterations, 10 substeps | 1 iteration, 100 substeps |
|---|---|---|---|
| 1 | |||
| 1000 | 0.77 | 0.072 | |
| 100000 | 1.89 | 1.72 | 0.80 |
With equal masses, 1 iteration in each of , and substeps gives the stretch , and : about 100 times smaller for each factor 10. The paper reports for its chain of 20 particles with the mass ratio 1:100000 an error of 322.1 m with 100 iterations and 3.2 m with 100 substeps (Section 6.1). With the mass ratio 100000 neither choice holds the chain in the code, which shows that small steps reduce but do not remove the difficulty.
A pendulum against a reference (measured). A particle on a rigid rod of length 1 m starts horizontal. A classical Runge-Kutta solve of with 200000 steps gives the reference position after 1 s. With 60 frames of s and 1 iteration, the position error is 0.23, 0.027, and m for substeps, first order in . With and 1, 10, 100 or 1000 iterations the error stays 0.23 m, because one iteration already solves the single constraint.
Rigid bodies. Müller, Macklin, Chentanez, Jeschke and Kim (2020) use the same loop for rigid bodies with joints and contacts, with one iteration per substep.
Cloth and fluids. The same loop applies to cloth simulation and to position based fluids, where each substep also re-evaluates the density constraints.
Variations
- Several iterations per substep. Any split of a budget into substeps and iterations is possible; the table shows the error between the two ends.
- Jacobi iterations. A Jacobi update of all constraints at once is easier to run in parallel than Gauss-Seidel; with small steps the slower convergence per sweep matters less.
- Damping. Equation (8) of the paper adds damping per substep.
- Collisions and friction. Section 4.2 detects contact candidates once per frame with an enlarged bound and handles them in every substep, with a clamp for depenetration (equation (10)) and friction (equations (11) and (12)).
- Other integrators. The same substep loop with Verlet integration prediction and a projection is used in older position based codes.
Pitfalls
- Floating point. Very small gives small position changes that single precision cannot represent well; Section 7 of the paper names this limit.
- Collision detection per substep. Running full collision detection in every substep removes most of the gain; detect once per frame and reuse the candidates.
- First order. Small steps make each step cheaper and better solved, but the time integration stays first order (Section 7).
- High mass ratios. At a ratio of even 100 substeps leave a large error (the table); the remaining error needs more substeps or a direct solver.
- Constraint energy. With the constraint projection removes energy at every substep; the dissipation falls with but does not vanish.
Code
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/small-steps-physics/. The authors are listed in prov/R4RWDE.jsonl.
"""Small steps (Macklin et al. 2019): split a frame into substeps with one XPBD iteration each.
A frame of length dt is split into n substeps of length h = dt / n. Each
substep predicts the positions with the external force, runs a number of
Gauss-Seidel iterations over the distance constraints with the XPBD update
dlambda = (-C - alpha~ lambda) / (w_a + w_b + alpha~), alpha~ = alpha / h^2,
(equation (7) of the paper) and sets v = (x - x_prev) / h. With the same total
number of constraint sweeps per frame, the code compares many iterations in
one step against many substeps with one iteration each. The chain is 2D and
hangs from a pinned first particle.
"""
import math
GRAVITY = (0.0, -9.81)
def chain(count, spacing, masses=None, alpha=0.0):
"""A horizontal chain from the origin; particle 0 is pinned (inverse mass 0)."""
x = [(i * spacing, 0.0) for i in range(count)]
m = list(masses) if masses is not None else [1.0] * count
w = [0.0] + [1.0 / mi for mi in m[1:]]
cons = [(i, i + 1, spacing, alpha) for i in range(count - 1)]
return x, w, cons
def solve_constraints(x, w, cons, lam, h):
"""One Gauss-Seidel sweep of XPBD distance constraints."""
for k, (a, b, rest, alpha) in enumerate(cons):
dx, dy = x[a][0] - x[b][0], x[a][1] - x[b][1]
ln = math.hypot(dx, dy)
wsum = w[a] + w[b]
at = alpha / (h * h)
if ln == 0.0 or wsum + at == 0.0:
continue
c = ln - rest
dl = (-c - at * lam[k]) / (wsum + at) # @line L7
lam[k] += dl
n = (dx / ln, dy / ln)
x[a] = (x[a][0] + w[a] * dl * n[0], x[a][1] + w[a] * dl * n[1]) # @line L8
x[b] = (x[b][0] - w[b] * dl * n[0], x[b][1] - w[b] * dl * n[1])
def frame(x, v, w, cons, dt, substeps, iterations, gravity=GRAVITY):
"""Advance one frame. Return (x, v)."""
h = dt / substeps # @line L1
x, v = list(x), list(v)
for _ in range(substeps): # @line L2
prev = list(x)
for i in range(len(x)):
if w[i] > 0.0:
v[i] = (v[i][0] + h * gravity[0], v[i][1] + h * gravity[1]) # @line L3
x[i] = (x[i][0] + h * v[i][0], x[i][1] + h * v[i][1]) # @line L4
lam = [0.0] * len(cons) # @line L5
for _ in range(iterations): # @line L6
solve_constraints(x, w, cons, lam, h)
v = [((a[0] - b[0]) / h, (a[1] - b[1]) / h) for a, b in zip(x, prev)] # @line L9
return x, v
def simulate(x, v, w, cons, dt, frames, substeps, iterations, gravity=GRAVITY):
for _ in range(frames):
x, v = frame(x, v, w, cons, dt, substeps, iterations, gravity)
return x, v
def stretch(x, cons):
"""The largest relative constraint error |l - r| / r."""
return max(abs(math.dist(x[a], x[b]) - r) / r for a, b, r, _ in cons)
def total_stretch(x, cons):
"""The sum of the length errors, in metres."""
return sum(abs(math.dist(x[a], x[b]) - r) for a, b, r, _ in cons)
def energy(x, v, w, cons, gravity=GRAVITY):
"""Kinetic plus gravitational plus compliant constraint energy of the free particles."""
e = 0.0
for p, u, wi in zip(x, v, w):
if wi > 0.0:
m = 1.0 / wi
e += 0.5 * m * (u[0] ** 2 + u[1] ** 2) - m * (gravity[0] * p[0] + gravity[1] * p[1])
for a, b, r, alpha in cons:
if alpha > 0.0:
e += 0.5 / alpha * (math.dist(x[a], x[b]) - r) ** 2
return e
test_small_steps_physics.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/small-steps-physics/. The authors are listed in prov/R4RWDE.jsonl.
"""Tests of small steps: the XPBD update, a pendulum against a reference ODE solve, and substeps against iterations."""
import math
import small_steps_physics as ss
def pendulum_reference(t_end, steps=20000):
"""Classical Runge-Kutta on theta'' = -g cos(theta) for a rod of length 1 from the +x axis, y up."""
th, om = 0.0, 0.0
h = t_end / steps
def f(t, o):
return o, -9.81 * math.cos(t)
for _ in range(steps):
k1 = f(th, om)
k2 = f(th + h / 2 * k1[0], om + h / 2 * k1[1])
k3 = f(th + h / 2 * k2[0], om + h / 2 * k2[1])
k4 = f(th + h * k3[0], om + h * k3[1])
th += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
om += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
return math.cos(th), math.sin(th)
def test_example_one_compliant_constraint():
"""Two unit masses 1.5 apart, rest 1, alpha~ = 1: dlambda = -0.5 / 3, each end moves by 1/6."""
x = [(0.0, 0.0), (1.5, 0.0)]
lam = [0.0]
ss.solve_constraints(x, [1.0, 1.0], [(0, 1, 1.0, 0.01)], lam, 0.1)
assert abs(lam[0] + 0.5 / 3.0) < 1e-15
assert abs(x[0][0] - 1.0 / 6.0) < 1e-15 and abs(x[1][0] - (1.5 - 1.0 / 6.0)) < 1e-15
def test_rigid_constraint_is_one_projection():
x = [(0.0, 0.0), (0.3, 0.4)]
ss.solve_constraints(x, [0.0, 2.0], [(0, 1, 1.0, 0.0)], [0.0], 0.01)
assert x[0] == (0.0, 0.0) and abs(math.hypot(*x[1]) - 1.0) < 1e-15
def test_pendulum_converges_to_the_reference_at_first_order():
ref = pendulum_reference(0.5)
errs = []
for n in (10, 100):
x, w, c = ss.chain(2, 1.0)
x, _ = ss.simulate(x, [(0.0, 0.0)] * 2, w, c, 1.0 / 60.0, 30, n, 1)
errs.append(math.dist(x[1], ref))
assert 7.0 < errs[0] / errs[1] < 13.0 and errs[1] < 5e-3
def test_iterations_do_not_reduce_the_error_of_one_constraint():
"""One constraint is solved exactly by one iteration, so only substeps reduce the time error."""
out = []
for k in (1, 50):
x, w, c = ss.chain(2, 1.0)
x, _ = ss.simulate(x, [(0.0, 0.0)] * 2, w, c, 1.0 / 60.0, 30, 1, k)
out.append(x[1])
assert math.dist(out[0], out[1]) < 1e-12
def test_substeps_beat_iterations_for_the_same_budget():
"""Measured on a 20 particle chain with a last particle 1000 times heavier."""
res = {}
for n, k in ((1, 100), (100, 1)):
x, w, c = ss.chain(20, 0.1, [1.0] * 19 + [1000.0])
x, _ = ss.simulate(x, [(0.0, 0.0)] * 20, w, c, 1.0 / 60.0, 30, n, k)
res[n] = ss.stretch(x, c)
assert res[100] < res[1] / 30.0
def test_stretch_falls_fast_with_more_substeps():
"""Measured: on a uniform chain, ten times more substeps cut the stretch by about 100."""
s = []
for n in (5, 50):
x, w, c = ss.chain(20, 0.1)
x, _ = ss.simulate(x, [(0.0, 0.0)] * 20, w, c, 1.0 / 60.0, 20, n, 1)
s.append(ss.stretch(x, c))
assert s[0] / s[1] > 50.0
def test_free_fall_with_substeps_is_symplectic_euler():
x, w, c = ss.chain(2, 1.0)
w = [1.0, 1.0]
x, _ = ss.simulate(x, [(0.0, 0.0)] * 2, w, [], 0.1, 10, 1, 1)
assert abs(x[0][1] + 5.3955) < 1e-12
x, _ = ss.simulate([(0.0, 0.0)], [(0.0, 0.0)], [1.0], [], 1.0, 1, 4, 1)
assert abs(x[0][1] + 9.81 * 0.0625 * 10) < 1e-12
Exercises
- For a single distance constraint with , show that one iteration of L7 and L8 makes the distance equal to the rest length.
- With one iteration and , show that L7 is the same for XPBD and for small steps with compliance .
- For a particle in free fall, compute the position after one frame of split into substeps, and show that the error against the exact value is .
- Measure the stretch of the heavy chain for the splits with and plot it against .
- Explain why the cost of the collision detection decides whether small steps pay off, and estimate the cost of a frame with detection once per frame and once per substep.
References
- Miles Macklin, Kier Storey, Michelle Lu, Pierre Terdiman, Nuttapong Chentanez, Stefan Jeschke and Matthias Müller, Small steps in physics simulation, Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2019), Algorithm 1 (the substep loop), equation (7) (the XPBD update), equation (8) (damping), Section 4.2 (collisions once per frame, equation (10), and friction, equations (11) and (12)), Section 6.1 (the chain with mass ratio 1:100000), Section 7 (limitations)
- Matthias Müller, Miles Macklin, Nuttapong Chentanez, Stefan Jeschke and Tae-Yong Kim, Detailed rigid body simulation with extended position based dynamics, Computer Graphics Forum 39(8), 2020, 101 to 112, the substep loop for rigid bodies with one iteration per substep (general locator)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag R4RWDE Edit this page History Report an error Markdown