Algorithmadvanced
Extended position based dynamics
Also called XPBD.
Position based dynamics with a compliance and a Lagrange multiplier per constraint, so that the converged stiffness does not depend on the time step or on the sweep count.
- Solves
- Cloth simulation
- Time
- O(n + k c) stepΘ(c) sweep
- Space
- O(n + c) step
- Where
- c = the number of constraints, each on a bounded number of particles; k = the number of solver sweeps per step; n = the number of particles
- Model
- Real RAM
- Properties
- not angular momentum conservingbackward euler for linear constraintsdeterministicnot exactlinear momentum conserving
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Miles Macklin, Matthias Müller, Nuttapong Chentanez, 2016
Extended position based dynamics (XPBD) is position based dynamics with two additions: each constraint gets a compliance , the inverse of a stiffness, and a Lagrange multiplier that collects its total correction during the step. Macklin, Müller and Chentanez (2016) derived the update as a Gauss-Seidel solve of a simplified Newton system of backward Euler. When the sweeps converge, a spring of compliance has the stiffness for any and any sweep count, and with the method is PBD with hard constraints.
In plain words
PBD fixes each stick of a rope fully, every time it visits it. So more visits make the rope stiffer, even if nothing else changes. XPBD gives each stick a softness number and a running total of how hard it has already pulled in this frame. On each visit the stick asks: given my softness and how hard I already pull, how much more should I pull? The answer gets smaller on every visit, and it settles at the same rope for any number of visits. A soft stick ends up a little longer than its rest length, by the amount its pull and its softness agree on. A stick with softness zero is a rigid stick, as in PBD.
The problem
The input is a set of particles with positions , velocities and inverse masses ( for a pinned particle), constraints with compliances , a step and a sweep count . The elastic potential of the constraints is
so a distance constraint is a spring of stiffness . The aim is the backward Euler step for and gravity. With it is a stationary point of , the variational form of backward Euler that this site also uses for optimization time integration, projective dynamics, vertex block descent, incremental potential contact and affine body dynamics. XPBD gives an approximation of it at the cost of PBD. The page uses 2D, up and m/s².
The algorithm
XPBD-STEP(x, v, w, constraints, Δt, k)- 1
for each free particle i: x~_i <- x_i + Δt v_i + Δt² g ▷ prediction - 2
for each constraint j: λ_j <- 0 - 3
p <- x~ - 4
repeat k times: - 5
for each constraint C_j in a fixed order, with α~_j = α_j / Δt²: - 6
Δλ <- (-C_j(p) - α~_j λ_j) / (Σ_i w_i |∇_i C_j(p)|² + α~_j) - 7
for each particle i of C_j: p_i <- p_i + w_i ∇_i C_j(p) Δλ - 8
λ_j <- λ_j + Δλ - 9
for each particle i: v_i <- (p_i - x_i) / Δt; x_i <- p_i
Where L6 comes from. Write . Then the backward Euler step is the pair of equations and with (equations (4) to (9) of the paper). Newton's method on these equations solves a block system with the matrix (equation (12)). XPBD makes two simplifications. It replaces by , which drops the geometric stiffness and gives a quasi-Newton method. It also assumes that the first equation holds at every iterate. What remains is the system , and line L6 is one Gauss-Seidel update of its row , with the gradient taken at the current positions (equation (18)). For a distance constraint, and the denominator is .
The multiplier. The term in L6 is what PBD lacks. It makes repeated visits to the same constraint converge to instead of to , so a soft constraint is not made stiffer by more sweeps. The force of the constraint is , a value that PBD does not give.
Damping. Equation (26) of the paper adds Rayleigh damping with a coefficient : with and , the update becomes . The code leaves damping out.
Example
One spring by hand. A free particle of mass 1 sits at at rest, joined to a pin at the origin by a spring of rest length 1 and compliance (stiffness 100). There is no gravity and , so and the prediction is . Line L6 gives , and L7 moves the particle by to , with the velocity . A second sweep gives . Backward Euler for this spring gives , the same value. PBD with the stiffness would give after one sweep, which depends on how is tuned and not on the step.
Stretch against sweeps (measured). A chain of 11 particles of 1 kg, joined by 10 constraints of 0.1 m, is pinned at one end and falls from a horizontal start, with s. After 300 steps (5 s) the total length exceeds 1 m by
| compliance | 2 | 5 | 10 | 20 | 50 | |
|---|---|---|---|---|---|---|
| 0 (PBD) | 11.4% | 5.7% | 2.9% | 1.5% | 0.64% | 0.16% |
| 12.5% | 6.1% | 3.3% | 1.9% | 1.13% | 0.76% | |
| 24.6% | 7.6% | 6.0% | 5.6% | 5.53% | 5.52% |
With (stiffness N/m per link) the stretch settles near 5.5% from about 10 sweeps on. A chain of these springs hanging at rest would stretch by m, or 5.4%; the chain here still swings. With the stretch keeps falling with more sweeps, which is the PBD behavior, and the row is the same as the table on the PBD page.
Distance from backward Euler (measured). A chain of 6 particles with swings for 6 steps, then one step is taken from the same state with 500 sweeps and compared with a Newton solve of the backward Euler equations. The largest distance between the two answers is
| 1/30 | 1/60 | 1/120 | 1/240 | 1/480 | |
|---|---|---|---|---|---|
| distance (m) | |||||
| motion in the step (m) | 0.045 | 0.020 | 0.0090 | 0.0043 | 0.0021 |
The gap comes from the second simplification: the gradients turn while the chain swings, so the converged answer is not exactly the backward Euler step. In this run the gap shrinks about 16 times when is halved. For a chain that only moves along its own line the gradients do not turn, and the gap is zero (claim 3 below).
Correctness
The claims are proved in proofs/correctness.md.
- Gauss-Seidel on a simplified Newton system (proved). Lines L6 to L8 are one Gauss-Seidel update of the Newton system of backward Euler with replaced by and the first residual set to zero.
- Fixed points (proved). If the sweeps converge, the limit satisfies for every . The other backward Euler equation holds up to a residual that is a sum of gradient changes times multiplier updates, so it is zero when the gradients do not turn.
- Exact for linear constraints (proved). If every constraint is affine on the region of the iterates and every , the sweeps converge for any order to the backward Euler step, because they are Gauss-Seidel for a symmetric positive definite system. The test runs a vertical chain against a Newton solve and reaches after 200 sweeps, with the error falling at every count.
- One spring (proved). For one spring on a pinned particle, one sweep gives the backward Euler step with for every . The test checks 200 random cases across four step sizes.
- Zero compliance is PBD (proved). With , L6 is the PBD projection with the sweep stiffness 1.
- Linear momentum (proved). With translation invariant constraints, no pins and no gravity, the step keeps . Angular momentum is not kept in general, for the same reason as in PBD.
The tests also check the gradient of the backward Euler objective against central differences, that the constraint forces sum to zero, that the swinging chain of the table is within 1% of the motion from backward Euler and closer at the smaller step, and free fall against the symplectic Euler value m after 10 steps of s.
Proof: XPBD is Gauss-Seidel on a simplified Newton system of backward Euler, and it is exact for linear constraintsfull
We use the notation of the page. There are particles with positions , a diagonal mass matrix and inverse masses ; a pinned particle has and is left out of all sums over masses. There are constraints with compliances , and . The matrix has the rows , and . The prediction of line L1 is on the free particles. Lines L6 and L7 apply to the constraint
which is equation (18) of Macklin et al. (2016). For a distance constraint , so the denominator is .
The backward Euler step and its Newton system
Lemma 1. Let for all . The backward Euler step for the potential is a stationary point of
With , the condition is equivalent to the two equations
Proof. Backward Euler is with , that is , and this is . Now by the definition of , and that definition is the second equation.
The function is the residual of the paper; we write to keep for gravity. One Newton step on the two equations at solves
which is equation (12) of the paper.
Lemma 2. Replace by and by . Then the system becomes with . One Gauss-Seidel update of the row of this system, with evaluated at the current , is lines L6 to L8.
Proof. The first block row gives . Put this into the second row: . The diagonal entry of row is . A Gauss-Seidel update solves row for with the other unknowns at their current values. Since each earlier update has already been applied to and , the right side of row is and the off-diagonal terms are already used up, so the update is the of line L6. The matching change of is , which is line L7.
Dropping the term (the geometric stiffness) makes this a quasi-Newton method. It changes the path to the solution but not the equations that a fixed point must satisfy. Setting is a different matter, as the next lemma shows.
Fixed points
Lemma 3. Suppose the sweeps converge, so that for every and , . Then . Also
where the sum runs over all updates of lines L6 and L7, is the state at which update was computed, and the gradients are stacked into .
Proof. The first claim is line L6 with and a finite denominator. For the second, line L3 sets and line L2 sets . Each update adds to and to . Summing, and . Subtract.
So a converged XPBD step is a backward Euler step exactly when the residual of Lemma 3 is zero, and the size of depends on how much the constraint gradients turn during the step. This is a property of the method, not of the number of sweeps.
Theorem 4 (linear constraints). Let every be affine on a region that holds all iterates, , let for all and let every constraint touch at least one free particle. Then the XPBD sweeps converge for any number of constraints and any order, and the limit is the backward Euler step of Lemma 1.
Proof. The gradients are constant, so the invariant of Lemma 3 reads at all times, where now is constant. Hence with and , and line L6 is . This is the Gauss-Seidel method for . The matrix is symmetric, and it is positive definite because for (here acts on the free particles only). Gauss-Seidel converges for every symmetric positive definite matrix and every start, so with , and . Then by the invariant, and by Lemma 3. By Lemma 1, is the backward Euler step.
A distance constraint is affine on every region where the direction of does not change, for example a vertical chain that only moves vertically.
Corollary 5 (one spring). Take a pinned particle at the origin and a free particle of mass on the axis, joined by one distance constraint of rest length and compliance , with and no gravity. Let be the prediction. One sweep gives
the backward Euler step of the linear spring of stiffness , for every .
Proof. With one constraint, Gauss-Seidel solves the system in one update. Directly: with , and , which is the formula. The backward Euler equation has the same solution.
In particular the stiffness of a spring in XPBD is for every and every number of sweeps once the sweeps have converged. With few sweeps the result is softer, since the sweeps stop early.
Zero compliance and momentum
Lemma 6. If , line L6 is the PBD projection with the sweep stiffness .
Proof. With the term vanishes and , which is in the notation of the PBD page. Then .
Theorem 7 (linear momentum). Let every be invariant under a common translation of its particles, let no particle be pinned and let . Then .
Proof. Translation invariance gives , so each update changes by . Hence at the end of the sweeps, and line L9 gives the claim.
Angular momentum is not kept in general. Each update is torque-free about the current , as in Lemma 4 of the PBD proof, but the velocity of line L9 is measured from . The two-particle counterexample of Theorem 7 there applies without change when .
Lemma 8. With no constraints, one step is the symplectic Euler step , .
Proof. Line L1 computes , nothing changes it, and line L9 returns .
Cost
Lemma 9. A step with sweeps over distance constraints on particles costs time and memory.
Proof. Lines L1, L3 and L9 touch each particle once. Each constraint update in lines L6 to L8 does a constant amount of work for a constraint on two particles. The state is , the velocities and one multiplier per constraint.
Complexity
Each update of L6 to L8 costs for a constraint on a bounded number of particles, so a sweep costs and a step . The extra memory over PBD is one multiplier per constraint, so the memory is . No matrix is built or factored. The number of sweeps needed for a given error is a property of the scene: Gauss-Seidel converges slowly on long chains and on stiff, well connected meshes.
Properties
- Stiffness is a material constant when converged. A converged step gives the spring stiffness independent of and (claims 3 and 4). With few sweeps the material is softer than , as the table shows.
- Approximate backward Euler. The method inherits the numerical damping of backward Euler, and it adds the gap of the second simplification when constraints turn.
- Hard constraints. is allowed and gives rigid constraints, as in PBD. Then the system has no compliance term; with redundant constraints its matrix is only positive semidefinite, and the convergence proof of claim 3 does not apply.
- Order dependence. As in PBD, the result of a finite number of sweeps depends on the constraint order.
- Momentum. Linear momentum is kept exactly for translation invariant constraints; angular momentum is not.
Variants and improvements
- Small steps. Small steps use and divide the frame into many substeps. Macklin et al. (2019) measured lower error for the same cost on chains and cloth.
- Rigid bodies. Müller, Macklin, Chentanez, Jeschke and Kim (2020) extended XPBD to rigid bodies with positional and angular constraints, joints and friction (Computer Graphics Forum 39(8)).
- Jacobi and coloring. For a GPU, constraints are updated in parallel by averaging or by graph coloring, as in PBD.
- Other solvers for the same step. Projective dynamics solves the same kind of backward Euler step by local projections and a constant global matrix, and vertex block descent does block coordinate descent over vertices. Optimization time integration uses Newton's method with a line search, which keeps the geometric stiffness.
- Mass-spring view. Fast mass-spring solves the same backward Euler step for springs with a constant matrix.
When to use it
Use XPBD when you want the robustness and simple code of PBD, but the stiffness must be set in physical units and must not change with the step or the sweep count, for example cloth, ropes and soft bodies in games and tools. Use for rigid constraints such as inextensible links and pins. It also gives constraint forces, which PBD does not.
Do not expect a converged backward Euler solution for very stiff, well connected meshes with few sweeps; use substeps or a Newton based solver then.
Pitfalls
- Forgetting to reset . The multipliers start at zero in every step (L2). Keeping them from the last step changes the method.
- Units. is in units of the inverse of the stiffness, for example m/N for a distance constraint. Divide by to get ; using directly makes the material depend on again.
- Few sweeps on stiff materials. With a small and few sweeps the material is soft, as the table shows. More sweeps or substeps are needed.
- Mixed compliances. Very different compliances in one system slow Gauss-Seidel down. Small steps help here.
- Zero gradients and pinned pairs. Skip a constraint with a zero gradient or with only pinned particles, as in PBD.
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
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
extended_position_based_dynamics.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-position-based-dynamics/. The authors are listed in prov/553NT7.jsonl.
"""Extended position based dynamics (Macklin, Mueller and Chentanez 2016), in 2D.
Each constraint C_j has a compliance alpha_j (the inverse of a stiffness) and a
Lagrange multiplier lambda_j that starts at zero in every step. With
alpha~ = alpha / dt^2, one Gauss-Seidel sweep visits each constraint and
applies (equation (18) of the paper)
dlambda = (-C_j(x) - alpha~ lambda_j) / (sum_i w_i |grad_i C_j(x)|^2 + alpha~),
x_i <- x_i + w_i grad_i C_j(x) dlambda, lambda_j <- lambda_j + dlambda.
This is a Gauss-Seidel solve of the Newton system of backward Euler for the
energy U = sum 1/(2 alpha_j) C_j^2, with the geometric stiffness dropped
(K ~ M) and the residual g = M (x - x~) - grad C^T lambda taken as zero.
With alpha_j = 0 the update is the PBD projection with stiffness 1.
The particles are lists of 2D points, w are inverse masses (0 for a pinned
particle) and a constraint is a tuple (i, j, rest, alpha) for the distance
constraint C = |x_i - x_j| - rest. One sweep costs Theta(c) for c
constraints, a step O(n + k c) for k sweeps, and the memory is O(n + c).
"""
import math
GRAVITY = (0.0, -9.81)
def distance_value_and_gradient(x, i, j, rest):
"""C = |x_i - x_j| - rest and the unit vector n = grad_i C = -grad_j C."""
dx, dy = x[i][0] - x[j][0], x[i][1] - x[j][1]
ln = math.hypot(dx, dy)
if ln == 0.0:
return -rest, (0.0, 0.0)
return ln - rest, (dx / ln, dy / ln)
def xpbd_step(x, v, w, constraints, dt, iterations, gravity=GRAVITY):
"""One XPBD step. Return (x, v, lam) with the final multipliers."""
n = len(x)
xn = [tuple(p) for p in x]
xt = [(xn[i][0] + dt * v[i][0] + dt * dt * gravity[0], xn[i][1] + dt * v[i][1] + dt * dt * gravity[1])
if w[i] > 0.0 else xn[i] for i in range(n)] # @line L1
lam = [0.0] * len(constraints) # @line L2
p = list(xt) # @line L3
for _ in range(iterations): # @line L4
for k, (i, j, rest, alpha) in enumerate(constraints): # @line L5
at = alpha / (dt * dt)
c, nrm = distance_value_and_gradient(p, i, j, rest)
denom = w[i] + w[j] + at
if denom == 0.0 or nrm == (0.0, 0.0):
continue
dl = (-c - at * lam[k]) / denom # @line L6
p[i] = (p[i][0] + w[i] * nrm[0] * dl, p[i][1] + w[i] * nrm[1] * dl) # @line L7
p[j] = (p[j][0] - w[j] * nrm[0] * dl, p[j][1] - w[j] * nrm[1] * dl)
lam[k] += dl # @line L8
v_new = [((p[i][0] - xn[i][0]) / dt, (p[i][1] - xn[i][1]) / dt) for i in range(n)] # @line L9
return p, v_new, lam
def energy_objective(x, xt, w, constraints, dt):
"""The backward Euler objective 1/2 |x - x~|_M^2 + dt^2 sum 1/(2 alpha) C^2 (free particles only)."""
g = 0.0
for i, (p, q) in enumerate(zip(x, xt)):
if w[i] > 0.0:
g += 0.5 / w[i] * ((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
for i, j, rest, alpha in constraints:
c = math.dist(x[i], x[j]) - rest
g += dt * dt * 0.5 / alpha * c * c
return g
def constraint_force(x, constraints, lam, dt):
"""The force of each constraint: grad C^T lambda / dt^2, per particle."""
f = [[0.0, 0.0] for _ in x]
for k, (i, j, rest, alpha) in enumerate(constraints):
_, nrm = distance_value_and_gradient(x, i, j, rest)
s = lam[k] / (dt * dt)
f[i][0] += s * nrm[0]
f[i][1] += s * nrm[1]
f[j][0] -= s * nrm[0]
f[j][1] -= s * nrm[1]
return [tuple(u) for u in f]
def chain(count, spacing, alpha, mass=1.0, vertical=False):
"""A chain pinned at particle 0, horizontal or hanging along -y. Return (x, v, w, constraints)."""
if vertical:
x = [(0.0, -i * spacing) for i in range(count)]
else:
x = [(i * spacing, 0.0) for i in range(count)]
v = [(0.0, 0.0)] * count
w = [0.0] + [1.0 / mass] * (count - 1)
cons = [(i, i + 1, spacing, alpha) for i in range(count - 1)]
return x, v, w, cons
test_extended_position_based_dynamics.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-position-based-dynamics/. The authors are listed in prov/553NT7.jsonl.
"""Tests of XPBD against closed forms, a Newton solve of backward Euler and conservation laws."""
import math
import random
from anim import num_grad, solve
import extended_position_based_dynamics as xpbd
def predict(x, v, w, dt, g):
return [(p[0] + dt * u[0] + dt * dt * g[0], p[1] + dt * u[1] + dt * dt * g[1]) if wi > 0.0 else tuple(p)
for p, u, wi in zip(x, v, w)]
def newton_backward_euler(xt, w, cons, dt, tol=1e-13):
"""Minimize 1/2 |x - x~|_M^2 + dt^2 sum C^2 / (2 alpha) by Newton's method with backtracking."""
free = [i for i in range(len(xt)) if w[i] > 0.0]
col = {i: k for k, i in enumerate(free)}
x = [tuple(p) for p in xt]
for _ in range(100):
nf = 2 * len(free)
grad = [0.0] * nf
hess = [[0.0] * nf for _ in range(nf)]
for i in free:
for d in range(2):
r = 2 * col[i] + d
grad[r] += (x[i][d] - xt[i][d]) / w[i]
hess[r][r] += 1.0 / w[i]
for i, j, rest, alpha in cons:
c, n = xpbd.distance_value_and_gradient(x, i, j, rest)
ln = c + rest
s = dt * dt / alpha
blk = [[s * (n[a] * n[b] + c * ((1.0 if a == b else 0.0) - n[a] * n[b]) / ln) for b in range(2)]
for a in range(2)]
for p, sp in ((i, 1.0), (j, -1.0)):
if p not in col:
continue
for a in range(2):
grad[2 * col[p] + a] += s * c * sp * n[a]
for q, sq in ((i, 1.0), (j, -1.0)):
if q not in col:
continue
for a in range(2):
for b in range(2):
hess[2 * col[p] + a][2 * col[q] + b] += sp * sq * blk[a][b]
if max(abs(gv) for gv in grad) < tol:
break
step = solve(hess, [-gv for gv in grad])
f0 = xpbd.energy_objective(x, xt, w, cons, dt)
t = 1.0
while True:
y = list(x)
for i in free:
y[i] = (x[i][0] + t * step[2 * col[i]], x[i][1] + t * step[2 * col[i] + 1])
if xpbd.energy_objective(y, xt, w, cons, dt) <= f0 or t < 1e-12:
break
t *= 0.5
x = y
return x
def test_example_one_spring_is_backward_euler():
x = [(0.0, 0.0), (1.5, 0.0)]
v = [(0.0, 0.0), (0.0, 0.0)]
w = [0.0, 1.0]
x1, v1, lam = xpbd.xpbd_step(x, v, w, [(0, 1, 1.0, 0.01)], 0.1, 1, gravity=(0.0, 0.0))
assert abs(lam[0] + 0.25) < 1e-15
assert abs(x1[1][0] - 1.25) < 1e-15 and abs(v1[1][0] + 2.5) < 1e-13
def test_one_linear_spring_matches_backward_euler_for_any_step():
"""x = (m y + dt^2 k r) / (m + dt^2 k) with k = 1 / alpha, in one sweep."""
rng = random.Random(11)
for _ in range(200):
dt = rng.choice([1e-3, 1e-2, 0.1, 1.0])
alpha = 10 ** rng.uniform(-6, 0)
m = rng.uniform(0.1, 3.0)
r = rng.uniform(0.5, 2.0)
x0 = rng.uniform(0.6, 3.0)
v0 = rng.uniform(-1.0, 1.0)
y = x0 + dt * v0
x1, _, _ = xpbd.xpbd_step([(0.0, 0.0), (x0, 0.0)], [(0.0, 0.0), (v0, 0.0)], [0.0, 1.0 / m],
[(0, 1, r, alpha)], dt, 1, gravity=(0.0, 0.0))
k = 1.0 / alpha
want = (m * y + dt * dt * k * r) / (m + dt * dt * k)
assert abs(x1[1][0] - want) < 1e-9 * max(1.0, abs(want))
def test_zero_compliance_is_the_pbd_projection():
rng = random.Random(12)
for _ in range(200):
x = [(rng.uniform(-1, 1), rng.uniform(-1, 1)), (rng.uniform(-1, 1), rng.uniform(-1, 1))]
w = [rng.uniform(0.1, 2.0), rng.uniform(0.1, 2.0)]
d = rng.uniform(0.1, 1.0)
c, n = xpbd.distance_value_and_gradient(x, 0, 1, d)
want0 = (x[0][0] - w[0] / (w[0] + w[1]) * c * n[0], x[0][1] - w[0] / (w[0] + w[1]) * c * n[1])
want1 = (x[1][0] + w[1] / (w[0] + w[1]) * c * n[0], x[1][1] + w[1] / (w[0] + w[1]) * c * n[1])
x1, _, _ = xpbd.xpbd_step(x, [(0.0, 0.0)] * 2, w, [(0, 1, d, 0.0)], 1.0, 1, gravity=(0.0, 0.0))
assert max(abs(x1[0][k] - want0[k]) for k in range(2)) < 1e-14
assert max(abs(x1[1][k] - want1[k]) for k in range(2)) < 1e-14
def test_collinear_chain_converges_to_backward_euler():
"""Linear constraints: the dropped terms are zero, and the sweeps converge to the Newton solution."""
dt = 1.0 / 30.0
x, v, w, cons = xpbd.chain(8, 0.1, 1e-3, vertical=True)
xt = predict(x, v, w, dt, xpbd.GRAVITY)
ref = newton_backward_euler(xt, w, cons, dt)
errs = []
for it in (1, 2, 5, 10, 200):
x1, _, lam = xpbd.xpbd_step(x, v, w, cons, dt, it)
errs.append(max(abs(a[1] - b[1]) for a, b in zip(x1, ref)))
assert errs[0] > errs[1] > errs[2] > errs[3] > 0.0
assert errs[0] > 1e-4 and errs[4] < 1e-12
for k, (i, j, rest, alpha) in enumerate(cons):
assert abs(math.dist(x1[i], x1[j]) - rest + alpha / dt ** 2 * lam[k]) < 1e-12
def test_nonlinear_chain_is_close_to_backward_euler():
"""A swinging chain: the converged XPBD step differs from backward Euler by the residual g (measured)."""
x, v, w, cons = xpbd.chain(6, 0.1, 1e-4)
for _ in range(6):
x, v, _ = xpbd.xpbd_step(x, v, w, cons, 1.0 / 60.0, 50)
errs = []
for dt in (1.0 / 60.0, 1.0 / 120.0):
xt = predict(x, v, w, dt, xpbd.GRAVITY)
ref = newton_backward_euler(xt, w, cons, dt)
x1, _, _ = xpbd.xpbd_step(x, v, w, cons, dt, 500)
err = max(math.dist(a, b) for a, b in zip(x1, ref))
move = max(math.dist(a, b) for a, b in zip(ref, x))
assert 0.0 < err < 1e-2 * move
errs.append(err)
assert errs[1] < errs[0] / 4.0
def test_linear_momentum_is_conserved():
rng = random.Random(13)
x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(10)]
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
w = [rng.uniform(0.5, 2.0) for _ in range(10)]
cons = [(i, j, 0.9 * math.dist(x[i], x[j]), rng.choice([0.0, 1e-4, 1e-2]))
for i in range(10) for j in range(i + 1, 10) if (i * j) % 4 == 1]
p0 = [sum(u[k] / wi for u, wi in zip(v, w)) for k in range(2)]
for _ in range(40):
x, v, _ = xpbd.xpbd_step(x, v, w, cons, 0.01, 3, gravity=(0.0, 0.0))
p1 = [sum(u[k] / wi for u, wi in zip(v, w)) for k in range(2)]
scale = sum(math.hypot(*u) / wi for u, wi in zip(v, w))
assert max(abs(p1[k] - p0[k]) for k in range(2)) < 1e-10 * scale
def test_objective_gradient_against_num_grad():
"""The gradient of the backward Euler objective, and the constraint forces sum to zero."""
rng = random.Random(14)
x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(4)]
xt = [(p[0] + 0.01, p[1] - 0.02) for p in x]
w = [0.5, 1.0, 2.0, 1.0]
cons = [(0, 1, 0.3, 1e-2), (1, 2, 0.4, 1e-3), (2, 3, 0.2, 1e-1)]
dt = 0.05
lam = [rng.uniform(-1e-3, 1e-3) for _ in cons]
flat = [u for p in x for u in p]
def f(z):
return xpbd.energy_objective([(z[2 * i], z[2 * i + 1]) for i in range(4)], xt, w, cons, dt)
ng = num_grad(f, flat)
for i in range(4):
for k in range(2):
want = (x[i][k] - xt[i][k]) / w[i]
for j, (a, b, rest, alpha) in enumerate(cons):
c, n = xpbd.distance_value_and_gradient(x, a, b, rest)
if i == a:
want += dt * dt / alpha * c * n[k]
if i == b:
want -= dt * dt / alpha * c * n[k]
assert abs(ng[2 * i + k] - want) <= 1e-6 * max(1.0, abs(want))
f_lam = xpbd.constraint_force(x, cons, lam, dt)
assert abs(sum(u[0] for u in f_lam)) < 1e-12 and abs(sum(u[1] for u in f_lam)) < 1e-12
def test_free_fall_is_symplectic_euler():
x, v, w = [(0.0, 0.0)], [(0.0, 0.0)], [1.0]
for _ in range(10):
x, v, _ = xpbd.xpbd_step(x, v, w, [], 0.1, 1)
assert abs(x[0][1] + 5.3955) < 1e-12
History
Position based dynamics (Müller, Heidelberger, Hennix and Ratcliff, 2007) had stiffness that changed with the sweep count and the step. Macklin, Müller and Chentanez added the compliance and the multiplier at Motion in Games 2016, and showed results for a spring, a chain, a beam and cloth. Macklin and coauthors then showed in 2019 that substeps with one sweep each reduce the error further, and Müller and coauthors extended the method to rigid bodies in 2020.
References
- Miles Macklin, Matthias Müller and Nuttapong Chentanez, XPBD: position-based simulation of compliant constrained dynamics, Proceedings of the 9th International Conference on Motion in Games (MIG 2016), 49-54, 2016, equations (4) to (12) (the implicit step and its Newton system), equation (18) (the multiplier update), equation (26) (damping), Section 6 (the spring, chain, beam and cloth results)
- 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), 101-112, 2020, the whole paper (rigid bodies, joints and friction in XPBD)
Where this leads
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 553NT7 Edit this page History Report an error Markdown