Algorithmcore
Position based dynamics
Also called PBD.
Predict particle positions, then project them onto constraints one at a time in Gauss-Seidel sweeps, and set velocities from the change in position.
- 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 conservingdeterministicnot exactlinear momentum conservingstiffness depends on iterations
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matthias Müller, Bruno Heidelberger, Marcus Hennix, John Ratcliff, 2007
Position based dynamics (PBD) moves particles by working on their positions, not on forces. Each step predicts where the particles go with symplectic Euler, then moves the predicted positions so that they satisfy constraints such as fixed distances, one constraint at a time in Gauss-Seidel sweeps, and at the end takes each velocity as the change of position divided by . Müller, Heidelberger, Hennix and Ratcliff (2007) made it a general method for cloth, soft bodies and ropes in games. It is fast, simple and robust, but its stiffness depends on the time step and on the number of sweeps, so it is not a discretization of a fixed physical model.
In plain words
Think of a rope made of beads joined by sticks. First let every bead fly freely for one frame, as if the sticks were not there. Now the sticks have the wrong lengths. Go through the sticks one by one, and for each stick move its two beads along the stick until the length is right again. A heavy bead moves less than a light one. One pass does not fix everything, because fixing one stick spoils its neighbors, so do a few passes.
At the end, the velocity of each bead is where it ended up minus where it started, divided by the frame time. The beads never get a force that can blow up, so the rope never explodes. The price is that the rope feels softer with fewer passes or larger frames.
The problem
The input is a set of particles with positions , velocities and inverse masses ( for a pinned particle), a set of constraints or , each on a few particles, external forces , a step and a sweep count . The output is the state after one step. The aim is not to solve an equation of motion exactly. It is a motion that keeps the constraints and looks plausible at a fixed cost, as needed in games and interactive cloth simulation. The page uses 2D, up and m/s².
The algorithm
PBD-STEP(x, v, w, constraints, Δt, k)- 1
for each particle i: v_i <- v_i + Δt w_i f_ext,i ▷ the weight gives v_i + Δt g - 2
damp the velocities (optional) - 3
for each particle i: p_i <- x_i + Δt v_i ▷ prediction - 4
make a collision constraint for each particle whose path x_i -> p_i hits an obstacle - 5
repeat k times: - 6
for each constraint C_j in a fixed order: project p onto C_j - 7
for each particle i: v_i <- (p_i - x_i) / Δt - 8
for each particle i: x_i <- p_i
Projection (L6). For a constraint on the particles , PBD moves the particles along the gradients, weighted by the inverse masses (Section 3.3, equations (8) and (9) with masses):
This is the smallest correction in the mass norm that makes the linearized constraint zero, a Lagrange multiplier step. An inequality constraint is projected only when it is violated. For a distance constraint with it gives equations (10) and (11):
Stiffness. A constraint with stiffness scales its correction by , where is the sweep count, so that sweeps of a single constraint remove the fraction of its error (Section 3.3). With many coupled constraints the effective stiffness still depends on and on .
Collisions (L4). The paper tests each path against the scene with collision detection and adds an inequality constraint for each hit, kept for the current step only (Section 3.4). The code uses a horizontal ground line, . The paper also changes the velocities of colliding particles after L7 for friction and restitution; the code leaves this out.
Damping (L2). Section 3.5 blends each velocity toward the rigid motion of the whole body with the same linear and angular momentum, . This damps the deformation and keeps both momenta. The factor is a tuning value.
Order. Each projection uses the positions already moved by the earlier projections of the same sweep, as in Gauss-Seidel. The gradients are taken at the current positions . The SHAKE algorithm of molecular dynamics also corrects positions one constraint at a time, but it takes the gradients at the old positions and iterates until the constraints hold to a tolerance. Projected Gauss-Seidel for contact is also a sweep of this kind, but it works on velocities or impulses, and it solves a linear complementarity problem whose matrix does not change during the sweep, while PBD relinearizes the nonlinear constraints at every projection.
Example
One projection by hand. Particle 1 has at , particle 2 has at , and the rest length is . Then , , and , so . The corrections are and . The new distance is , and the momentum change is .
A spinning rod loses angular momentum. Two particles of mass 1 at with a rod of length 1 spin at rad/s. With s, the prediction stretches the rod to , and the projection pulls both ends back toward the center. The angular momentum goes from to , the factor per step. With the factor is . The corrections are torque-free about the predicted positions, but the step does not keep the angular momentum.
Stiffness depends on the sweeps (measured). A chain of 11 particles of 1 kg, joined by 10 rods of 0.1 m, is pinned at one end and falls from a horizontal start under gravity, with s. After 300 steps (5 s), the total length of the chain exceeds its rest length of 1 m by
| sweeps | 1 | 2 | 5 | 10 | 20 | 50 |
|---|---|---|---|---|---|---|
| stretch | 11.4% | 5.7% | 2.9% | 1.5% | 0.64% | 0.16% |
The rods have no stiffness parameter here (), but the chain behaves like an elastic rope whose stiffness grows with the number of sweeps.
Correctness
The claims are proved in proofs/correctness.md. PBD does not converge to the solution of a time integrator, so its correctness is a list of exact properties of the discrete step, with their hypotheses.
- Smallest correction (proved). With , each projection is the smallest correction in the mass norm that zeroes the linearized constraint, and a single distance constraint is satisfied exactly after one projection.
- Linear momentum (proved). If every constraint is invariant under translation, no particle is pinned and there is no ground, a step changes only by , for any number of sweeps. The test checks this to with random distance and area constraints and damping.
- Torque-free corrections (proved). If a constraint is also invariant under rotation, each projection satisfies about the positions where it acts. These are the conditions (1) and (2) of Section 3.3.
- Angular momentum is not kept (proved). The step changes by , which is not zero in general; the spinning rod above loses the factor per step. Gradients at the old positions, as in SHAKE, would keep it.
- Damping (proved). The damping of L2 keeps the linear and the angular momentum.
- Stiffness per sweep (proved for one constraint). For a single constraint whose gradient direction does not change, sweeps with leave the error . With coupled constraints the result depends on , as the table shows (measured).
The tests also check the projection against a KKT solve, the gradients against central differences, the pins and the ground, and free fall against the symplectic Euler value m after 10 steps of s.
Proof: The PBD projection is the smallest mass-weighted correction, keeps linear momentum and is torque-free, but the step does not keep angular momentumfull
We use the notation of the page. There are particles with positions and inverse masses ; a pinned particle has and is left out of all sums over masses. A constraint depends on a set of particles, and is its gradient with respect to . The projection of line L6 with the sweep stiffness is
which is equations (8) and (9) of Müller et al. (2007) with the masses put in. An inequality constraint is projected only when .
The projection is a weighted least squares step
Lemma 1. Let on the free particles. With , the correction is the unique minimizer of subject to the linearized constraint , where only free particles may move.
Proof. The objective is a strictly convex quadratic in the free unknowns, and the constraint is one affine equation that has a solution because some free is not zero. So the minimizer is unique, and it is the solution of the KKT system for free , together with the constraint. Then , and the constraint gives , so . This is the correction of line L6.
Corollary 2 (equations (10) and (11) of the paper). For , let . Then , , , and , . After the correction, keeps its direction and has the length , so one projection satisfies a single distance constraint exactly.
Momentum of one projection
Lemma 3. If does not change when all its particles move by the same vector, then , provided that all particles of are free.
Proof. Invariance under a translation by gives for every , so . Then .
Lemma 4. If does not change when all its particles turn by the same rotation about the origin, then , where and is the state before the projection. All particles of must be free.
Proof. Let be the rotation by . Invariance under the rotation by the angle gives . Since , this is . Then .
Distance and area constraints satisfy both hypotheses. The ground constraint does not, because it fixes a line in space. These two lemmas are the conditions (1) and (2) of Section 3.3 of the paper.
Momentum of one step
Theorem 5 (linear momentum). Let every constraint satisfy the hypothesis of Lemma 3, let no particle be pinned and let there be no ground. Then one call of the step, with any number of sweeps and any damping factor, gives .
Proof. Line L1 adds to the momentum. The damping of line L2 replaces by ; since and , the sum of times the change is zero. Lines L3 to L6 change by a sum of corrections, each with by Lemma 3. So with the velocities after L2, and line L7 gives .
Lemma 6 (the damping keeps angular momentum). The damping of line L2 does not change .
Proof. Write . The change of velocity is with . Its linear part sums to zero, as in Theorem 5, so the angular momentum changes by . Here , with , and . With the sum is zero.
Theorem 7 (angular momentum changes). With no external force, no damping and no pins, let be the sum of all corrections that particle gets in lines L5 and L6. Then
This is not zero in general, even when every constraint satisfies the hypotheses of Lemmas 3 and 4.
Proof. Line L7 gives , so . Line L3 and the corrections give . Then . Lemma 4 makes each correction torque-free about the point where it acts, which is and not .
For the counterexample, take two particles of mass 1 at with one distance constraint of rest length 1, spinning at the rate : and . The prediction is with the sign flipped for particle 1, at the distance . By Corollary 2 with equal masses, the projection scales both points by about the origin, and later sweeps do nothing. So , and by symmetry . Hence .
If the gradients are taken at instead of at the current , as in the SHAKE method of molecular dynamics, every correction is a multiple of , and the argument of Lemma 4 at gives , so Theorem 7 gives .
Stiffness per sweep
Lemma 8. Let one constraint have a gradient whose direction does not change under its own projection, for example a distance constraint between a pinned and a free particle. If it is projected times in a row with , its value goes from to .
Proof. By Corollary 2, one projection with moves the free particle along the fixed direction by times the full correction, so the value becomes . After projections the value is .
With several coupled constraints the error after sweeps depends on the coupling, so the effective stiffness depends on the iteration count and on (Section 3.3 of the paper says this). This is the problem that XPBD addresses.
Free motion
Lemma 9. With no constraints and no damping, one step is the symplectic Euler step , .
Proof. Lines L1 and L3 compute exactly these two updates, and line L7 gives back the same velocity, since .
Complexity
One projection costs for a constraint on a bounded number of particles, so one sweep costs . Lines L1 to L3 and L7 to L8 cost . The collision detection of L4 is a separate cost; with the ground line it is . A step costs time, and the state and the constraint list use memory. There is no matrix to build or factor. The number of sweeps that gives a usable stiffness is a measurement for each scene.
Properties
- Robust, not accurate. The particles end where the projections put them, so a large correction cannot feed back as a large force. The paper argues that the method is unconditionally stable; this is an argument, not a theorem, and a stable answer can still be far from the motion of the physical model.
- Stiffness is not a material constant. The behavior depends on , the sweep count and the constraint order. Two scenes with the same but different settings look different.
- Order dependence. Gauss-Seidel sweeps depend on the constraint order. A Jacobi version projects all constraints from the same positions and averages, which is parallel but slower to converge.
- Exact conservation. Linear momentum is kept for translation invariant constraints. Angular momentum is not kept exactly (claim 4).
- Energy. There is no energy that the step decreases or keeps; the damping is a mix of the method itself and the tuning factor .
Variants and improvements
- XPBD. Extended position based dynamics adds a compliance and a Lagrange multiplier to each constraint, which removes the dependence on the sweep count and makes the method an approximate backward Euler solver.
- Substeps. Small steps use many substeps with one sweep each instead of one step with many sweeps, which reduces the error of XPBD for the same cost.
- Shape matching. Meshless shape matching pulls particles toward the best rigid fit of the rest shape, which is a position based method without a mesh.
- Fluids. Position based fluids project a density constraint per particle with the same machinery.
- Strain limiting. Provot strain limiting is an older position correction that shortens over-stretched springs after a force based step.
- Jacobi and graph coloring. On a GPU, constraints are projected in parallel either by averaging (Jacobi) or by graph coloring, so that constraints of one color share no particle.
When to use it
Use PBD for interactive scenes where robustness and a fixed cost per frame matter more than a material that behaves the same at every step size: cloth, ropes, hair and soft objects in games, and controllers that move particles directly. It handles pins, collisions and other position goals easily, because they are all constraints.
Do not use plain PBD when the stiffness must match a material or stay the same when or the sweep count changes. Use XPBD then, or an implicit solver such as projective dynamics or optimization time integration.
Pitfalls
- Stiffness changes with settings. Raising the sweep count makes cloth stiffer and changing the step changes the look. Tune with the final settings, or use XPBD.
- Velocities from positions. Line L7 must use the position at the start of the step, , not the position after the external force. A collision projection that moves a particle far also gives it a large velocity; the paper corrects the velocities of colliding particles after L7.
- Zero gradients. A distance constraint between two particles at the same point has no direction. Skip it, as the code does, instead of dividing by zero.
- Pinned pairs. If all particles of a constraint are pinned, the denominator of is zero. Skip such constraints.
- Angular momentum drift. A fast spinning body slows down by the factor of claim 4 per step. Use smaller steps or the SHAKE choice of gradients if this matters.
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
position_based_dynamics.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-dynamics/. The authors are listed in prov/AGQN60.jsonl.
"""Position based dynamics (Mueller, Heidelberger, Hennix and Ratcliff 2007), in 2D.
A step predicts the positions with symplectic Euler, projects them onto the
constraints one at a time for a fixed number of Gauss-Seidel sweeps, and then
sets each velocity from the change in position (Section 3.1 of the paper).
A constraint has a value C(p) and one gradient for each of its particles. An
equality constraint is projected always; an inequality constraint C(p) >= 0
is projected only when C(p) < 0. The projection of one constraint is
s = C(p) / sum_j w_j |grad_j C(p)|^2, dp_i = -k' s w_i grad_i C(p),
with the inverse masses w_i (Section 3.3, equations (8) and (9) with masses)
and the stiffness per sweep k' = 1 - (1 - k)^(1 / n_s), so that n_s sweeps of
a linear constraint remove the part k of its error. A particle with w_i = 0 does
not move.
The cost of one sweep is Theta(c) for c constraints with a bounded number of
particles each; a step costs O(n + n_s c) time and O(n + c) memory.
"""
import math
GRAVITY = (0.0, -9.81)
class Distance:
"""C(p) = |p_i - p_j| - rest = 0 (equations (10) and (11) of the paper)."""
equality = True
def __init__(self, i, j, rest, stiffness=1.0):
self.i, self.j, self.rest, self.stiffness = i, j, rest, stiffness
def value(self, p):
a, b = p[self.i], p[self.j]
return math.hypot(a[0] - b[0], a[1] - b[1]) - self.rest
def gradients(self, p):
a, b = p[self.i], p[self.j]
dx, dy = a[0] - b[0], a[1] - b[1]
ln = math.hypot(dx, dy)
if ln == 0.0:
return [(self.i, (0.0, 0.0)), (self.j, (0.0, 0.0))]
n = (dx / ln, dy / ln)
return [(self.i, n), (self.j, (-n[0], -n[1]))]
class Area:
"""C(p) = signed area of the triangle (i, j, l) - rest = 0."""
equality = True
def __init__(self, i, j, l, rest, stiffness=1.0):
self.i, self.j, self.l, self.rest, self.stiffness = i, j, l, rest, stiffness
def value(self, p):
a, b, c = p[self.i], p[self.j], p[self.l]
return 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) - self.rest
def gradients(self, p):
a, b, c = p[self.i], p[self.j], p[self.l]
return [
(self.i, (0.5 * (b[1] - c[1]), 0.5 * (c[0] - b[0]))),
(self.j, (0.5 * (c[1] - a[1]), 0.5 * (a[0] - c[0]))),
(self.l, (0.5 * (a[1] - b[1]), 0.5 * (b[0] - a[0]))),
]
class Ground:
"""C(p) = p_i,y - height >= 0, a collision constraint with a horizontal ground line."""
equality = False
stiffness = 1.0
def __init__(self, i, height=0.0):
self.i, self.height = i, height
def value(self, p):
return p[self.i][1] - self.height
def gradients(self, p):
return [(self.i, (0.0, 1.0))]
def sweep_stiffness(k, iterations):
"""k' = 1 - (1 - k)^(1 / n_s) (Section 3.3)."""
if k >= 1.0:
return 1.0
return 1.0 - (1.0 - k) ** (1.0 / iterations)
def project(constraint, p, w, k_sweep):
"""Project p (a list of points, changed in place) onto one constraint. Return the correction per particle."""
c = constraint.value(p)
if not constraint.equality and c >= 0.0:
return []
grads = constraint.gradients(p)
denom = sum(w[i] * (g[0] * g[0] + g[1] * g[1]) for i, g in grads)
if denom == 0.0:
return []
s = c / denom
out = []
for i, g in grads:
d = (-k_sweep * s * w[i] * g[0], -k_sweep * s * w[i] * g[1])
p[i] = (p[i][0] + d[0], p[i][1] + d[1])
out.append((i, d))
return out
def damp_velocities(x, v, w, k_damping):
"""The damping of Section 3.5 in 2D: blend each velocity toward the rigid motion with the same momenta."""
idx = [i for i in range(len(x)) if w[i] > 0.0]
if not idx or k_damping == 0.0:
return list(v)
m = {i: 1.0 / w[i] for i in idx}
mt = sum(m.values())
xc = (sum(m[i] * x[i][0] for i in idx) / mt, sum(m[i] * x[i][1] for i in idx) / mt)
vc = (sum(m[i] * v[i][0] for i in idx) / mt, sum(m[i] * v[i][1] for i in idx) / mt)
big_l = 0.0
inertia = 0.0
for i in idx:
r = (x[i][0] - xc[0], x[i][1] - xc[1])
big_l += m[i] * (r[0] * v[i][1] - r[1] * v[i][0])
inertia += m[i] * (r[0] * r[0] + r[1] * r[1])
om = big_l / inertia if inertia > 0.0 else 0.0
out = list(v)
for i in idx:
r = (x[i][0] - xc[0], x[i][1] - xc[1])
dv = (vc[0] - om * r[1] - v[i][0], vc[1] + om * r[0] - v[i][1])
out[i] = (v[i][0] + k_damping * dv[0], v[i][1] + k_damping * dv[1])
return out
def pbd_step(x, v, w, constraints, dt, iterations, gravity=GRAVITY, k_damping=0.0, ground=None):
"""One step of position based dynamics.
x, v: lists of 2D points and velocities. w: inverse masses (0 for a pinned
particle). constraints: objects with value, gradients, equality and
stiffness. The external force is the weight m g. If ground is a number,
a Ground constraint is made for each particle whose prediction is below it.
Return the new (x, v) as lists of tuples.
"""
n = len(x)
v = [(v[i][0] + dt * gravity[0], v[i][1] + dt * gravity[1]) if w[i] > 0.0 else tuple(v[i])
for i in range(n)] # @line L1
v = damp_velocities(x, v, w, k_damping) # @line L2
p = [(x[i][0] + dt * v[i][0], x[i][1] + dt * v[i][1]) for i in range(n)] # @line L3
coll = [Ground(i, ground) for i in range(n) if ground is not None and p[i][1] < ground] # @line L4
work = list(constraints) + coll
ks = [sweep_stiffness(c.stiffness, iterations) for c in work]
for _ in range(iterations): # @line L5
for c, k in zip(work, ks):
project(c, p, w, k) # @line L6
v_new = [((p[i][0] - x[i][0]) / dt, (p[i][1] - x[i][1]) / dt) for i in range(n)] # @line L7
return p, v_new # @line L8
def chain(count, spacing, mass=1.0, pin_first=True):
"""A horizontal chain of particles joined by distance constraints. Return (x, v, w, constraints)."""
x = [(i * spacing, 0.0) for i in range(count)]
v = [(0.0, 0.0)] * count
w = [1.0 / mass] * count
if pin_first:
w[0] = 0.0
cons = [Distance(i, i + 1, spacing) for i in range(count - 1)]
return x, v, w, cons
def momentum(x, v, w):
"""Linear and angular momentum (about the origin) of the particles with w > 0."""
px = py = big_l = 0.0
for xi, vi, wi in zip(x, v, w):
if wi > 0.0:
m = 1.0 / wi
px += m * vi[0]
py += m * vi[1]
big_l += m * (xi[0] * vi[1] - xi[1] * vi[0])
return px, py, big_l
test_position_based_dynamics.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-dynamics/. The authors are listed in prov/AGQN60.jsonl.
"""Tests of position based dynamics against closed forms, a KKT solve and conservation laws."""
import math
import random
from anim import num_grad, solve
import position_based_dynamics as pbd
def test_example_two_particles():
p = [(0.0, 0.0), (1.5, 0.0)]
w = [1.0, 1.0 / 3.0]
out = dict(pbd.project(pbd.Distance(0, 1, 1.0), p, w, 1.0))
assert abs(out[0][0] - 0.375) < 1e-15 and abs(out[1][0] + 0.125) < 1e-15
assert abs(1.0 * out[0][0] + 3.0 * out[1][0]) < 1e-15
assert abs(math.dist(p[0], p[1]) - 1.0) < 1e-15
def test_distance_projection_closed_form():
"""Equations (10) and (11): dp1 = -w1 / (w1 + w2) (|p12| - d) n, dp2 = +w2 / (w1 + w2) (|p12| - d) n."""
rng = random.Random(3)
for _ in range(200):
p = [(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)
dx, dy = p[0][0] - p[1][0], p[0][1] - p[1][1]
ln = math.hypot(dx, dy)
n = (dx / ln, dy / ln)
e = ln - d
want0 = (-w[0] / (w[0] + w[1]) * e * n[0], -w[0] / (w[0] + w[1]) * e * n[1])
want1 = (w[1] / (w[0] + w[1]) * e * n[0], w[1] / (w[0] + w[1]) * e * n[1])
got = dict(pbd.project(pbd.Distance(0, 1, d), p, w, 1.0))
assert max(abs(got[0][k] - want0[k]) for k in range(2)) < 1e-14
assert max(abs(got[1][k] - want1[k]) for k in range(2)) < 1e-14
def test_projection_equals_kkt_solve():
"""The correction is the smallest in the mass norm that zeroes the linearized constraint."""
rng = random.Random(4)
for _ in range(100):
p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
w = [rng.uniform(0.2, 2.0) for _ in range(3)]
c = pbd.Area(0, 1, 2, rng.uniform(-0.3, 0.3))
cv = c.value(p)
g = dict(c.gradients(p))
# KKT: M dp - grad^T lam = 0, grad dp = -C, unknowns (dp in R^6, lam)
a = [[0.0] * 7 for _ in range(7)]
b = [0.0] * 7
for i in range(3):
for k in range(2):
r = 2 * i + k
a[r][r] = 1.0 / w[i]
a[r][6] = -g[i][k]
a[6][r] = g[i][k]
b[6] = -cv
sol = solve(a, b)
q = list(p)
got = dict(pbd.project(c, q, w, 1.0))
for i in range(3):
for k in range(2):
assert abs(got[i][k] - sol[2 * i + k]) < 1e-11
def test_gradients_against_num_grad():
rng = random.Random(5)
for _ in range(30):
p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
for c in (pbd.Distance(0, 2, 0.5), pbd.Area(0, 1, 2, 0.1), pbd.Ground(1, 0.2)):
flat = [u for q in p for u in q]
def f(z, c=c):
return c.value([(z[0], z[1]), (z[2], z[3]), (z[4], z[5])])
ng = num_grad(f, flat)
g = dict(c.gradients(p))
for i in range(3):
gi = g.get(i, (0.0, 0.0))
for k in range(2):
assert abs(gi[k] - ng[2 * i + k]) <= 1e-6 * max(1.0, abs(ng[2 * i + k]))
def test_torque_free_corrections():
"""Each projection keeps sum m dp = 0 and sum m p x dp = 0 at the positions where it acts (equations (1) and (2))."""
rng = random.Random(6)
for _ in range(100):
p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
w = [rng.uniform(0.2, 2.0) for _ in range(3)]
for c in (pbd.Distance(0, 1, 0.3), pbd.Area(0, 1, 2, 0.05)):
q = list(p)
corr = pbd.project(c, q, w, 1.0)
lin = [sum(d[k] / w[i] for i, d in corr) for k in range(2)]
ang = sum((p[i][0] * d[1] - p[i][1] * d[0]) / w[i] for i, d in corr)
assert max(abs(lin[0]), abs(lin[1]), abs(ang)) < 1e-14
def test_linear_momentum_is_conserved():
rng = random.Random(7)
x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(12)]
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(12)]
w = [rng.uniform(0.5, 2.0) for _ in range(12)]
cons = [pbd.Distance(i, j, 0.8 * math.dist(x[i], x[j])) for i in range(12) for j in range(i + 1, 12) if (i + j) % 3 == 0]
cons += [pbd.Area(i, i + 1, i + 2, 0.0) for i in range(0, 9, 3)]
p0 = pbd.momentum(x, v, w)
for _ in range(50):
x, v = pbd.pbd_step(x, v, w, cons, 0.01, 4, gravity=(0.0, 0.0), k_damping=0.1)
p1 = pbd.momentum(x, v, w)
scale = sum(math.hypot(*vi) / wi for vi, wi in zip(v, w))
assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale
def test_spinning_dumbbell_loses_angular_momentum():
"""One step of a rigid rod spinning at omega multiplies L by 1 / sqrt(1 + (omega dt)^2)."""
for omega, dt in ((1.0, 0.1), (1.0, 1.0), (3.0, 0.05)):
x = [(-0.5, 0.0), (0.5, 0.0)]
v = [(0.0, -0.5 * omega), (0.0, 0.5 * omega)]
w = [1.0, 1.0]
l0 = pbd.momentum(x, v, w)[2]
x1, v1 = pbd.pbd_step(x, v, w, [pbd.Distance(0, 1, 1.0)], dt, 3, gravity=(0.0, 0.0))
l1 = pbd.momentum(x1, v1, w)[2]
assert abs(l1 / l0 - 1.0 / math.sqrt(1.0 + (omega * dt) ** 2)) < 1e-14
def test_damping_keeps_momenta():
rng = random.Random(8)
x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(8)]
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(8)]
w = [rng.uniform(0.5, 2.0) for _ in range(8)]
vd = pbd.damp_velocities(x, v, w, 0.7)
a, b = pbd.momentum(x, v, w), pbd.momentum(x, vd, w)
assert max(abs(a[k] - b[k]) for k in range(3)) < 1e-12
vr = pbd.damp_velocities(x, v, w, 1.0)
# k_damping = 1 leaves a rigid motion: every pair keeps its distance to first order
for i in range(8):
for j in range(8):
dx = (x[i][0] - x[j][0], x[i][1] - x[j][1])
dv = (vr[i][0] - vr[j][0], vr[i][1] - vr[j][1])
assert abs(dx[0] * dv[0] + dx[1] * dv[1]) < 1e-12
def test_sweep_stiffness_gives_k_after_n_sweeps():
"""For one particle on a pinned rod along x, n_s sweeps leave the error (1 - k) e."""
for k in (0.1, 0.5, 0.9):
for ns in (1, 3, 10):
p = [(0.0, 0.0), (1.5, 0.0)]
c = pbd.Distance(0, 1, 1.0, stiffness=k)
kp = pbd.sweep_stiffness(k, ns)
for _ in range(ns):
pbd.project(c, p, [0.0, 1.0], kp)
assert abs(c.value(p) - (1.0 - k) * 0.5) < 1e-12
def test_pinned_particle_and_ground():
x, v, w, cons = pbd.chain(6, 0.2)
for _ in range(200):
x, v = pbd.pbd_step(x, v, w, cons, 1.0 / 60.0, 10, ground=-0.5)
assert x[0] == (0.0, 0.0)
assert min(p[1] for p in x) >= -0.5 - 1e-12
def test_residual_decreases_with_iterations():
"""The stretch of a falling chain depends on the iteration count: the reason for XPBD."""
stretch = []
for it in (1, 5, 50):
x, v, w, cons = pbd.chain(11, 0.1)
for _ in range(300):
x, v = pbd.pbd_step(x, v, w, cons, 1.0 / 60.0, it)
stretch.append(sum(math.dist(x[i], x[i + 1]) for i in range(10)) - 1.0)
assert stretch[0] > stretch[1] > stretch[2] > 0.0
assert stretch[0] > 0.1 and stretch[2] < 0.002
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 = pbd.pbd_step(x, v, w, [], 0.1, 1)
assert abs(x[0][1] + 5.3955) < 1e-12
History
Jakobsen (2001) described a position based approach with Verlet integration and sticks projected one at a time for the characters of the game Hitman, at the Game Developers Conference. Müller, Heidelberger, Hennix and Ratcliff generalized it to arbitrary constraints with mass weighting, stiffness, collisions and damping, first at VRIPHYS 2006 and then in the Journal of Visual Communication and Image Representation in 2007. Macklin, Müller and Chentanez added compliance in 2016 with XPBD, and Macklin, Storey, Lu, Terdiman, Chentanez, Jeschke and Müller showed in 2019 that small substeps work better than many sweeps.
References
- Matthias Müller, Bruno Heidelberger, Marcus Hennix and John Ratcliff, Position based dynamics, Journal of Visual Communication and Image Representation 18(2), 109-118, 2007, Section 3.1 (the algorithm, lines (1) to (17)), Section 3.2 (the solver), Section 3.3 (constraint projection, equations (1) to (11) and the stiffness per iteration), Section 3.4 (collisions), Section 3.5 (damping), Section 3.6 (attachments)
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 AGQN60 Edit this page History Report an error Markdown