Algorithmresearch
Affine body dynamics
Also called ABD.
Simulate stiff bodies as affine maps with a stiff orthogonality energy and the barrier contact of IPC; the paper measures large speedups over rigid IPC in its scenes.
- Time
- O(V L) iterationO(N V L) step
- Space
- Θ(V + L) step
- Where
- L = the number of obstacle lines; N = the number of Newton iterations per step; V = the number of body vertices
- Model
- Real RAM
- Properties
- not angular momentum conservingconstant mass matrixdeterministicnot exactnot friction in codemonotone objectivepenetration free with conservative ccd
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lei Lan, Danny M. Kaufman, Minchen Li, Chenfanfu Jiang, Yin Yang, 2022
Affine body dynamics (ABD) simulates stiff objects, which would normally be rigid bodies, as bodies that can only move by an affine map . A very stiff orthogonality energy keeps close to a rotation. Lan, Kaufman, Li, Jiang and Yang (2022) chose this model because every point of the body then moves on a straight line when the state moves on a straight line, and the mass matrix is constant. So the barrier contact and the continuous collision checks of incremental potential contact apply directly, with 12 unknowns per body in 3D. The paper measures speedups of about 30 to more than 1000 times over a rigid body version of IPC in its scenes; the code on this page is a 2D version with one body and fixed lines.
In plain words
A rigid body can only turn and move. Turning is awkward for a solver, because angles wrap around and the motion of a point under a turn follows a curve. ABD lets the body also stretch and shear, which makes every motion a simple linear one, and then adds a very strong spring that pushes the body back to its true shape whenever it stretches. The body stays almost rigid. Because all point motions are now straight lines, checking whether a step would make the body hit something is easy and exact. The rest of the solver is the same safe contact method as IPC.
The problem
The input is a body with rest vertices , masses , the state with and (12 numbers in 3D, 6 in 2D), its velocity , obstacles and a step . With (equation (1)), the mass matrix is constant, and the motion follows (equation (5)). The orthogonality energy (equation (6)) is
which is zero exactly when is orthogonal. The paper uses above 100 GPa. One step minimizes the incremental potential with the IPC barrier (equations (9) to (11)):
The paper adds friction (equation (12)) and handles contact between bodies. The code covers one 2D rectangle with vertices on its border and lumped masses, contact against fixed lines , no friction, up and m/s².
The algorithm
ABD-STEP(q, q̇, Δt, κ, d̂, ε_d)- 1
q̃ <- q + Δt q̇ + Δt² M⁻¹ f - 2
z <- q - 3
repeat: - 4
g <- ∇E(z); H <- M + Δt² PSD(∇²V_⊥) + Σ_k κ b''(d_k) ∇d_k ∇d_kᵀ - 5
p <- -H⁻¹ g - 6
if max_v |J_v p| / Δt < ε_d: stop - 7
α <- min(1, 0.8 · first time a vertex reaches an obstacle on z + t p) - 8
while E(z + α p) > E(z): α <- α/2 - 9
z <- z + α p - 10
q̇ <- (z - q)/Δt; q <- z
The affine state (L1). With the rest coordinates centered at the center of mass, is block diagonal: the total mass for and a second moment matrix for . It does not depend on , so there are no Coriolis or centrifugal forces, unlike the Newton and Euler equations of a rigid body (claim 1).
The Hessian (L4). is not convex, so its Hessian is projected to a positive semidefinite matrix by clamping negative eigenvalues; the code uses a Jacobi eigen decomposition of the block ( in 3D). A gap is affine in for a vertex against a fixed line, so its barrier Hessian needs no projection. The paper builds a contact aware Hessian that keeps the per body blocks small (Section 4.3).
The step bound (L7). Along every vertex moves on a straight line, . So the time when a vertex reaches a line is a linear equation, and the code solves it exactly. Section 4.1 of the paper uses the same fact for 3D collision checks between bodies.
Example
Free fall by hand. A body at rest with has , so stays , and with the rest coordinates centered the part of is . The step sets , the symplectic Euler update: after 10 steps of 0.1 s the height is m.
A spinning drop (measured). A rectangle of m with density 1000 kg/m² (80 kg) starts at height 1 m, turned by 0.3 rad, falling at 5 m/s and spinning at 10 rad/s, onto the ground with m, and s, for 1 s:
| smallest gap (m) | |||
| largest | 0.18 | ||
| most Newton iterations in a step | 10 | 12 | 15 |
| mean Newton iterations per step | 3.43 | 2.84 | 4.49 |
The gap stays positive at every iterate. With the impact deforms the body by 18%, which is no longer a stiff body; a factor of 100 in cuts the deformation by about 100.
Damping of rotation (measured). The same body spins freely at 10 rad/s with no gravity and for 1 s. A rigid body would turn by 10 rad.
| (s) | 1/30 | 1/100 | 1/300 | 1/1000 |
|---|---|---|---|---|
| angle turned (rad) | 5.32 | 7.32 | 8.73 | 9.54 |
| final rate (rad/s) | 3.62 | 5.78 | 7.75 | 9.13 |
The loss comes from the backward Euler step, which moves along the tangent of the rotation and lets the stiff energy pull it back. It shrinks at first order in .
Correctness
The claims are proved in proofs/correctness.md, in exact arithmetic.
- Affine model (proved). is the kinetic energy of the vertices, is constant, and it is block diagonal and positive definite for centered rest coordinates with three points not on one line. The test checks and the kinetic energy identity.
- Orthogonality energy (proved). with equality exactly for orthogonal , where its gradient is zero; the gradient is with . It is not convex. The test checks the gradient and Hessian against central differences, and that the projection gives a positive semidefinite matrix that equals the Hessian when it is already semidefinite.
- No crossing (proved, under a hypothesis). For a convex body against fixed lines, the step bound keeps the whole body strictly inside every half plane at every iterate and on the paths between them. In floating point this needs a conservative collision check, as in IPC. The test checks all 60 steps of the spinning drop.
- Monotone energy (proved). is positive definite, so each Newton direction goes downhill, and the line search makes decrease. The test records at every iteration and checks by sampling 300 nearby states that a converged step is a local minimum of .
- Linear momentum (proved). Without active contact a converged step changes the linear momentum by exactly . Angular momentum is not kept (measured above).
- Contact forces (proved). At a stationary point, the forces balance inertia and elasticity, and for a body at rest they sum to its weight; the test checks this to 0.1%.
The tests also check free fall against m and that the orthogonality error of a spinning body falls by a factor between 50 and 200 when grows 100 times.
Proof: The affine map gives a constant mass matrix, the orthogonality energy vanishes exactly on orthogonal maps, the projected Newton step is a descent step, and a convex body never crosses a linefull
We use the notation of the page for the 2D code. The body has vertices with rest coordinates and masses . The state is with and stored row by row, so . The world position of a vertex is
The mass matrix is , the orthogonality energy is with , and the obstacles are half planes with . The gap of vertex to line is . With , , one step minimizes
with the barrier for and for of incremental potential contact (Lemma 1 of the proof on that page): on , zero for , with on and as . All statements are for exact arithmetic.
The affine model
Lemma 1 (kinetic energy and mass). For every , , the kinetic energy of the vertices, and does not depend on . If , then with . If three of the are not on one line, is positive definite.
Proof. The velocity of a vertex is because is constant, so . The block of that couples with the entries of is in the matching places, which is zero when the weighted mean of the rest coordinates is zero. If , then for every ; three points that are not on one line span the plane affinely, so the affine map is zero, and , .
This is the 2D form of equations (1) to (4) of the paper: the mass matrix is constant, so there are no Coriolis or centrifugal terms, and the equation of motion is (equation (5)). The code places on the border of a rectangle centered at its center of mass, with equal masses, so both conditions hold.
The orthogonality energy
Lemma 2. Let . Then , and exactly when is orthogonal, that is, a rotation or a reflection. The gradient is , which is zero on orthogonal matrices, and the Hessian acts on a direction as .
Proof. is zero exactly when . With and symmetric, , using . So . Differentiating in the direction gives .
is not convex: at with the Hessian has a negative eigenvalue (the test checks ). The paper uses the same energy with above 100 GPa and reports that it is cheaper than ARAP and neo-Hookean energies (Section 3.2).
Lemma 3 (projection). project_psd returns for the eigenpairs of the Hessian of . This matrix is positive semidefinite, and it equals the Hessian when the Hessian is positive semidefinite.
Proof. The cyclic Jacobi method applies plane rotations that zero one off diagonal entry at a time; the sum of the squares of the off diagonal entries decreases strictly with each nontrivial rotation and tends to zero, and the product of the rotations is an orthogonal with diagonal in the limit. The code stops when the off diagonal part is below a relative , which the test confirms by rebuilding from the eigenpairs to . Clamping the eigenvalues gives a sum of positive semidefinite rank one matrices, and if no eigenvalue is negative nothing changes.
Contact
Lemma 4. Each gap is affine in , with constant gradient and zero Hessian. So the barrier Hessian is positive semidefinite with no projection, and along a straight path each gap is , linear in .
Proof. is constant, so is affine. The chain rule gives , and .
This linearity is why the paper can run continuous collision checks on straight vertex paths (Section 4.1): a straight path in moves every point of the body on a straight line.
Theorem 5 (no crossing). Suppose every gap is positive at and let be the value of step_bound. Then every gap is positive at for . If the rest shape is the convex hull of the , as for the rectangle of the code, then the whole body stays strictly inside every half plane, at every iterate and on the path between iterates.
Proof. By Lemma 4 the gap of is with and . If it stays positive for all . If it reaches zero at ; the code sets when , and otherwise . So in every case, and the gap is positive on . For the second claim, the affine map of a convex hull is the convex hull of the images of the vertices, and a half plane that contains all vertex images strictly contains their convex hull. The line search only shrinks the step.
The theorem covers contact against fixed lines. The paper treats contact between bodies with point and triangle and edge and edge pairs, where the same linearity of the vertex paths holds; the code does not.
The Newton iteration
Lemma 6 (descent). The matrix of the code, with the projected Hessian of placed in the block, is positive definite, so satisfies whenever , and only if .
Proof. is positive definite by Lemma 1, and the other terms are positive semidefinite by Lemmas 3 and 4. Then .
Lemma 7 (monotone). If , the halving loop ends after finitely many halvings with .
Proof. By Theorem 5, is finite and on , and by Lemma 6. So on some interval , and halving reaches it.
As in incremental potential contact, the guard accepts a point without decrease only to stop rounding loops, and the decrease test does not prove that the iterates converge to a minimizer. The test checks by sampling 300 nearby states that the result of a converged step is a local minimum.
Momentum and free fall
Theorem 8 (linear momentum). Let and let no gap be below . At a stationary point of , , so the linear momentum satisfies .
Proof. Since , . With the block form of , , since does not depend on and no barrier is active. So , where by the block form. Then .
Corollary 9 (free fall). A body at rest with and no contact falls as symplectic Euler: after 10 steps of s with is .
Proof. stays a minimizer of the part ( and ), and Theorem 8 gives the update of . Summing for gives .
Angular momentum is not kept: the backward Euler step damps rotation. The page measures this; the damping shrinks as goes to zero, at first order.
Theorem 10 (contact forces). At a stationary point, with , nonzero only for . For a body at rest on one line with normal , the rows give .
Proof. Set and divide by . At rest, and , so and the left side is . The rows of are , and has no rows, so .
Cost
Lemma 11. With vertices and lines, one Newton iteration costs for the assembly and the step bound, plus a constant for the eigen decomposition and the solve. Each halving costs . The memory is .
Proof. Each vertex and line pair adds work with matrices. The Jacobi method on a fixed matrix with a fixed sweep limit and the LU solve of a matrix take constant time.
In 3D the state has 12 numbers, the eigen problem is and the solve is per body. With many bodies the Hessian is block diagonal except for the contact pairs between bodies, which is what the paper exploits (Section 4.3).
Complexity
The code does work per Newton iteration for the assembly and the step bound, plus a constant for the eigen decomposition and the solve, and per halving of the line search. In 3D a body has 12 unknowns, so a system of bodies has unknowns however many vertices the bodies have. The cost of contact between bodies depends on the culling of pairs; the paper culls them with axis aligned bounding boxes (Section 4.2).
Properties
- Constant mass matrix. No Coriolis or centrifugal terms and no rotation parameters (claim 1).
- Straight vertex paths. A straight step in moves every vertex on a straight line, which makes collision checks simple (claim 3).
- Almost rigid. The body deforms by an amount that falls as grows; it is never exactly rigid.
- Free of intersection. With the IPC barrier and conservative collision checks, as in incremental potential contact.
- Numerical damping. The backward Euler step loses angular velocity at large (the rotation table).
- Fast in the paper's scenes. The paper reports 124 times faster than rigid IPC for a wrecking ball scene with 575 bodies (Fig. 3) and very large factors on a chain net (Fig. 4). These are measurements on its scenes and hardware, not a bound.
Variants and improvements
- Rigid IPC. Ferguson et al. (2021) kept rigid body coordinates with curved trajectories and barrier contact; ABD replaces them with affine coordinates and straight trajectories.
- Other near rigid models. Shape matching also fits a linear map to a body, and as rigid as possible deformation penalizes the distance to a rotation; ABD puts such a penalty inside an implicit step with barrier contact.
- Friction. Section 4 of the paper adds the lagged friction of IPC (equation (12)).
When to use it
Use ABD for scenes with many stiff objects in tight contact, such as stacks, chains, gears and mechanisms, when contact must be free of intersection and a rigid body solver with complementarity contact or impulses gives jitter or passes through thin parts.
Do not use it when bodies must be exactly rigid, when angular momentum must be kept over long times at large steps, or when a fast game physics loop with simple contacts is enough.
Pitfalls
- Too soft . The body visibly stretches on impact (the drop table at ). The paper's value is above 100 GPa.
- Too stiff for the step. The Newton problem becomes badly conditioned: in the code, with s reaches the cap of 100 iterations in some steps of the free spin.
- Reading off the rotation. is not exactly orthogonal; take its polar factor (in 2D, the angle ) when a rotation is needed.
- Reflections. is also zero at reflections. A body cannot reach one by continuous motion with a stiff , but a bad initial state can start there.
- Uncentered rest coordinates. Then couples and ; this is still correct, but the simple form of claim 5 needs the center of mass at the origin.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/affine-body-dynamics/. The authors are listed in prov/J2K8MW.jsonl.
"""Affine body dynamics (Lan, Kaufman, Li, Jiang and Yang 2022) for one 2D body against fixed lines.
The body has the state q = (p, A) with p in R^2 and A a 2 by 2 matrix stored
row by row, 6 numbers in 2D (12 in 3D in the paper). A point with rest
coordinates xb maps to x = A xb + p = J(xb) q (equation (1)), with
J(xb) = [[1, 0, xb0, xb1, 0, 0], [0, 1, 0, 0, xb0, xb1]].
The mass matrix M = sum_v m_v J_v^T J_v is constant. The stiff orthogonality
energy V(A) = kappa_o area ||A A^T - I||_F^2 (equation (6)) keeps A close to a
rotation. One step minimizes the incremental potential with a barrier
(equations (9) to (11), contact against fixed lines here)
E(q) = 1/2 (q - qt)^T M (q - qt) + dt^2 V(A) + kappa sum_{v, lines} b(d_v(q)),
with qt = q_n + dt qdot_n + dt^2 M^-1 f and the barrier b of incremental
potential contact. Projected Newton solves it: the 4 by 4 Hessian of V is made
positive semidefinite by a Jacobi eigen decomposition, the step length is
capped by a collision check (vertex paths are straight lines in q), and a
backtracking line search makes E decrease.
The paper treats 3D bodies, body against body contact and friction; this
code is a 2D version with one body and fixed lines.
"""
import math
from anim import solve
GRAVITY = (0.0, -9.81)
def jac(xb):
return [[1.0, 0.0, xb[0], xb[1], 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, xb[0], xb[1]]]
def world(q, xb):
"""x = A xb + p."""
return (q[0] + q[2] * xb[0] + q[3] * xb[1], q[1] + q[4] * xb[0] + q[5] * xb[1])
def barrier(d, dhat):
"""b(d), b'(d), b''(d) of incremental potential contact."""
if d >= dhat:
return 0.0, 0.0, 0.0
t = d - dhat
lg = math.log(d / dhat)
return -t * t * lg, -2.0 * t * lg - t * t / d, -2.0 * lg - 4.0 * t / d + t * t / (d * d)
def ortho_energy(q, k_area):
"""V(A) = k_area ||A A^T - I||_F^2, its gradient and its Hessian in (A00, A01, A10, A11)."""
a = [[q[2], q[3]], [q[4], q[5]]]
c = [[sum(a[i][k] * a[j][k] for k in range(2)) - (1.0 if i == j else 0.0) for j in range(2)] for i in range(2)]
e = k_area * sum(c[i][j] ** 2 for i in range(2) for j in range(2))
ca = [[sum(c[i][k] * a[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
g = [4.0 * k_area * ca[i][j] for i in range(2) for j in range(2)]
h = []
for r in range(4):
da = [[0.0, 0.0], [0.0, 0.0]]
da[r // 2][r % 2] = 1.0
dc = [[sum(da[i][k] * a[j][k] + a[i][k] * da[j][k] for k in range(2)) for j in range(2)] for i in range(2)]
col = [[sum(dc[i][k] * a[k][j] + c[i][k] * da[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
h.append([4.0 * k_area * col[i][j] for i in range(2) for j in range(2)])
return e, g, h
def jacobi_eigen(s, sweeps=50):
"""Eigenvalues and eigenvectors (columns of V) of a symmetric matrix by cyclic Jacobi rotations."""
n = len(s)
a = [list(row) for row in s]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(sweeps):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off < 1e-30 * (1.0 + sum(a[i][i] ** 2 for i in range(n))):
break
for p in range(n - 1):
for r in range(p + 1, n):
if a[p][r] == 0.0:
continue
theta = (a[r][r] - a[p][p]) / (2.0 * a[p][r])
t = (1.0 if theta >= 0.0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
akp, akr = a[k][p], a[k][r]
a[k][p], a[k][r] = c * akp - sn * akr, sn * akp + c * akr
for k in range(n):
apk, ark = a[p][k], a[r][k]
a[p][k], a[r][k] = c * apk - sn * ark, sn * apk + c * ark
for k in range(n):
vkp, vkr = v[k][p], v[k][r]
v[k][p], v[k][r] = c * vkp - sn * vkr, sn * vkp + c * vkr
return [a[i][i] for i in range(n)], v
def project_psd(h):
lam, v = jacobi_eigen(h)
n = len(h)
return [[sum(max(lam[k], 0.0) * v[i][k] * v[j][k] for k in range(n)) for j in range(n)] for i in range(n)]
class Body:
def __init__(self, points, masses, area, kappa_o, lines, dhat, kappa):
"""points are rest coordinates; lines are pairs (unit normal n, offset h) of the half planes n.x >= h."""
self.xb = [tuple(p) for p in points]
self.m = list(masses)
self.k_area = kappa_o * area
self.lines = [(tuple(n), h) for n, h in lines]
self.dhat, self.kappa = dhat, kappa
self.mass = [[0.0] * 6 for _ in range(6)]
for xb, m in zip(self.xb, self.m):
j = jac(xb)
for r in range(6):
for c in range(6):
self.mass[r][c] += m * (j[0][r] * j[0][c] + j[1][r] * j[1][c])
def gap(body, q, v, line):
n, h = line
x = world(q, body.xb[v])
return n[0] * x[0] + n[1] * x[1] - h
def min_gap(body, q):
return min((gap(body, q, v, ln) for v in range(len(body.xb)) for ln in body.lines), default=math.inf)
def energy(body, q, qt, dt):
"""E(q), or infinity if some gap is not positive."""
dq = [a - b for a, b in zip(q, qt)]
e = 0.5 * sum(dq[r] * body.mass[r][c] * dq[c] for r in range(6) for c in range(6))
e += dt * dt * ortho_energy(q, body.k_area)[0]
for v in range(len(body.xb)):
for ln in body.lines:
d = gap(body, q, v, ln)
if d <= 0.0:
return math.inf
e += body.kappa * barrier(d, body.dhat)[0]
return e
def gradient_and_hessian(body, q, qt, dt, project=True):
dq = [a - b for a, b in zip(q, qt)]
g = [sum(body.mass[r][c] * dq[c] for c in range(6)) for r in range(6)]
h = [list(row) for row in body.mass]
_, gv, hv = ortho_energy(q, body.k_area)
if project:
hv = project_psd(hv)
for r in range(4):
g[2 + r] += dt * dt * gv[r]
for c in range(4):
h[2 + r][2 + c] += dt * dt * hv[r][c]
for v, xb in enumerate(body.xb):
j = jac(xb)
for ln in body.lines:
d = gap(body, q, v, ln)
if d >= body.dhat:
continue
_, b1, b2 = barrier(d, body.dhat)
n = ln[0]
gd = [n[0] * j[0][r] + n[1] * j[1][r] for r in range(6)] # grad of d in q; d is linear in q
for r in range(6):
g[r] += body.kappa * b1 * gd[r]
for c in range(6):
h[r][c] += body.kappa * b2 * gd[r] * gd[c]
return g, h
def step_bound(body, q, p):
"""0.8 times the first t in (0, 1] at which a vertex on the path q + t p reaches a line, or 1."""
t_min = 1.0
for v in range(len(body.xb)):
for n, h in body.lines:
d = gap(body, q, v, (n, h))
w = world(p, body.xb[v]) # J_v p, the vertex displacement for the step p
rate = n[0] * w[0] + n[1] * w[1]
if rate < 0.0 and d / -rate <= 1.0 / 0.8:
t_min = min(t_min, 0.8 * d / -rate)
return t_min
def predict(body, q, qdot, dt, gravity=GRAVITY):
"""qt = q + dt qdot + dt^2 M^-1 f with f = sum_v m_v J_v^T g."""
f = [0.0] * 6
for xb, m in zip(body.xb, body.m):
j = jac(xb)
for r in range(6):
f[r] += m * (j[0][r] * gravity[0] + j[1][r] * gravity[1])
acc = solve(body.mass, f)
return [a + dt * b + dt * dt * c for a, b, c in zip(q, qdot, acc)]
def abd_step(body, q, qdot, dt, eps_d=1e-6, gravity=GRAVITY, max_iter=100, history=None):
"""One step of projected Newton on E. Return (q, qdot, iterations)."""
qt = predict(body, q, qdot, dt, gravity) # @line L1
z = list(q) # @line L2
e_prev = energy(body, z, qt, dt)
if history is not None:
history.append(e_prev)
it = 0
while it < max_iter: # @line L3
g, h = gradient_and_hessian(body, z, qt, dt) # @line L4
p = solve(h, [-c for c in g]) # @line L5
move = max(math.hypot(*world(p, xb)) for xb in body.xb)
if move / dt < eps_d: # @line L6
break
alpha = step_bound(body, z, p) # @line L7
while True:
trial = [a + alpha * b for a, b in zip(z, p)]
e = energy(body, trial, qt, dt)
if e <= e_prev or alpha < 1e-12: # @line L8
break
alpha *= 0.5
z, e_prev = trial, e # @line L9
if history is not None:
history.append(e_prev)
it += 1
qdot_new = [(a - b) / dt for a, b in zip(z, q)] # @line L10
return z, qdot_new, it
def rest_state(center=(0.0, 0.0), angle=0.0):
c, s = math.cos(angle), math.sin(angle)
return [center[0], center[1], c, -s, s, c]
def box(width, height, density, kappa_o, lines, dhat, kappa, refine=1):
"""A rectangle centered at its center of mass, with vertices on its border and lumped masses."""
pts = []
hw, hh = 0.5 * width, 0.5 * height
k = refine
for i in range(k):
t = i / k
pts += [(-hw + 2 * hw * t, -hh), (hw, -hh + 2 * hh * t), (hw - 2 * hw * t, hh), (-hw, hh - 2 * hh * t)]
area = width * height
m = density * area / len(pts)
return Body(pts, [m] * len(pts), area, kappa_o, lines, dhat, kappa)
def orthogonality_error(q):
a = [[q[2], q[3]], [q[4], q[5]]]
return math.sqrt(sum((sum(a[i][k] * a[j][k] for k in range(2)) - (1.0 if i == j else 0.0)) ** 2
for i in range(2) for j in range(2)))
def angle(q):
"""The angle of the rotation closest to A (2D polar decomposition)."""
return math.atan2(q[4] - q[3], q[2] + q[5])
anim.py 493 lines
# 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
test_affine_body_dynamics.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/affine-body-dynamics/. The authors are listed in prov/J2K8MW.jsonl.
"""Tests of affine body dynamics: the affine map, the mass matrix, the orthogonality energy, Newton and contact."""
import math
import random
from anim import num_grad
import affine_body_dynamics as ab
GROUND = [((0.0, 1.0), 0.0)]
def spin_rate(q, w):
"""qdot of a rotation at rate w: Adot = W A with W = [[0, -w], [w, 0]]."""
return [0.0, 0.0, -w * q[4], -w * q[5], w * q[2], w * q[3]]
def is_psd(h, tol):
lam, _ = ab.jacobi_eigen(h)
return min(lam) >= -tol
def test_affine_map_is_j_times_q():
rng = random.Random(1)
for _ in range(50):
q = [rng.uniform(-2, 2) for _ in range(6)]
xb = (rng.uniform(-1, 1), rng.uniform(-1, 1))
j = ab.jac(xb)
jq = [sum(j[r][c] * q[c] for c in range(6)) for r in range(2)]
x = ab.world(q, xb)
assert max(abs(a - b) for a, b in zip(jq, x)) < 1e-14
def test_kinetic_energy_identity_and_constant_mass():
rng = random.Random(2)
b = ab.box(0.4, 0.2, 1000.0, 1e5, [], 1e-3, 1.0, refine=2)
for _ in range(20):
qd = [rng.uniform(-3, 3) for _ in range(6)]
t1 = 0.5 * sum(qd[r] * b.mass[r][c] * qd[c] for r in range(6) for c in range(6))
t2 = sum(0.5 * m * sum(u * u for u in ab.world(qd, xb)) for xb, m in zip(b.xb, b.m))
assert abs(t1 - t2) < 1e-10 * t2
total = sum(b.m)
assert abs(b.mass[0][0] - total) < 1e-12 and abs(b.mass[0][2]) < 1e-12 and abs(b.mass[1][4]) < 1e-12
def test_orthogonality_energy_vanishes_on_rotations_and_matches_num_grad():
rng = random.Random(3)
for _ in range(10):
q = ab.rest_state((rng.uniform(-1, 1), rng.uniform(-1, 1)), rng.uniform(-3, 3))
e, g, _ = ab.ortho_energy(q, 7.0)
assert e < 1e-24 and max(abs(c) for c in g) < 1e-12
e, g, _ = ab.ortho_energy([0.0, 0.0, 1.0, 0.0, 0.0, -1.0], 7.0)
assert e == 0.0 and max(abs(c) for c in g) == 0.0
for _ in range(10):
q = [0.0, 0.0] + [rng.uniform(-1.5, 1.5) for _ in range(4)]
e, g, h = ab.ortho_energy(q, 3.0)
ng = num_grad(lambda a: ab.ortho_energy([0.0, 0.0] + a, 3.0)[0], q[2:])
assert max(abs(x - y) for x, y in zip(g, ng)) < 1e-5 * max(1.0, max(abs(c) for c in g))
for r in range(4):
col = num_grad(lambda a, r=r: ab.ortho_energy([0.0, 0.0] + a, 3.0)[1][r], q[2:])
assert max(abs(col[c] - h[r][c]) for c in range(4)) < 1e-4 * max(1.0, max(map(abs, h[r])))
def test_psd_projection():
rng = random.Random(4)
for _ in range(20):
q = [0.0, 0.0] + [rng.uniform(-1.0, 1.0) for _ in range(4)]
_, _, h = ab.ortho_energy(q, 1.0)
lam, v = ab.jacobi_eigen(h)
back = [[sum(lam[k] * v[i][k] * v[j][k] for k in range(4)) for j in range(4)] for i in range(4)]
assert max(abs(back[i][j] - h[i][j]) for i in range(4) for j in range(4)) < 1e-10
p = ab.project_psd(h)
assert is_psd(p, 1e-10)
if min(lam) >= 0.0:
assert max(abs(p[i][j] - h[i][j]) for i in range(4) for j in range(4)) < 1e-10
_, _, h = ab.ortho_energy([0.0, 0.0, 0.3, 0.0, 0.0, 0.3], 1.0)
assert not is_psd(h, 0.0)
def test_energy_gradient_against_num_grad_with_active_contact():
b = ab.box(0.4, 0.2, 1000.0, 1e3, GROUND, 0.01, 2.0)
q = ab.rest_state((0.0, 0.104), 0.02)
qt = [c + 0.001 for c in q]
assert ab.min_gap(b, q) < b.dhat
g, _ = ab.gradient_and_hessian(b, q, qt, 0.01)
ng = num_grad(lambda z: ab.energy(b, z, qt, 0.01), q, 1e-8)
assert max(abs(x - y) for x, y in zip(g, ng)) < 1e-5 * max(abs(c) for c in g)
def test_drop_with_spin_never_penetrates_and_energy_decreases():
b = ab.box(0.4, 0.2, 1000.0, 1e7, GROUND, 1e-3, 1.0)
q = ab.rest_state((0.0, 1.0), 0.3)
qd = spin_rate(q, 10.0)
qd[1] = -5.0
for _ in range(60):
hist = []
q, qd, _ = ab.abd_step(b, q, qd, 0.01, history=hist)
assert all(y <= x for x, y in zip(hist, hist[1:]))
assert ab.min_gap(b, q) > 0.0
assert ab.orthogonality_error(q) < 1e-2
def test_step_is_a_local_minimum_of_the_incremental_potential():
"""Brute force: no random point near the result has a lower energy."""
rng = random.Random(5)
b = ab.box(0.4, 0.2, 1000.0, 1e5, GROUND, 1e-3, 1.0)
q = ab.rest_state((0.0, 0.1012), 0.0)
qd = spin_rate(q, 3.0)
qd[1] = -1.0
qt = ab.predict(b, q, qd, 0.01)
q1, _, _ = ab.abd_step(b, q, qd, 0.01, eps_d=1e-12)
e1 = ab.energy(b, q1, qt, 0.01)
for _ in range(300):
z = [c + rng.uniform(-1e-4, 1e-4) for c in q1]
assert ab.energy(b, z, qt, 0.01) >= e1 - 1e-12 * abs(e1)
def test_linear_momentum_follows_gravity_in_free_flight():
b = ab.box(0.4, 0.2, 1000.0, 1e6, [], 1e-3, 1.0)
q = ab.rest_state((0.0, 0.0), 0.4)
qd = spin_rate(q, 6.0)
qd[0], qd[1] = 1.0, 2.0
total = sum(b.m)
for _ in range(20):
p0 = [sum(m * ab.world(qd, xb)[d] for xb, m in zip(b.xb, b.m)) for d in range(2)]
q, qd, _ = ab.abd_step(b, q, qd, 0.01, eps_d=1e-10)
p1 = [sum(m * ab.world(qd, xb)[d] for xb, m in zip(b.xb, b.m)) for d in range(2)]
assert abs(p1[0] - p0[0]) < 1e-9 * total and abs(p1[1] - p0[1] + 0.01 * 9.81 * total) < 1e-9 * total
def test_resting_contact_forces_carry_the_weight():
b = ab.box(0.4, 0.2, 1000.0, 1e7, GROUND, 1e-3, 1.0)
q, qd = ab.rest_state((0.0, 0.1005), 0.0), [0.0] * 6
dt = 0.01
for _ in range(60):
q, qd, _ = ab.abd_step(b, q, qd, dt, eps_d=1e-8)
lam = [-b.kappa / (dt * dt) * ab.barrier(ab.gap(b, q, v, GROUND[0]), b.dhat)[1] for v in range(len(b.xb))]
assert all(f >= 0.0 for f in lam)
assert abs(sum(lam) - sum(b.m) * 9.81) < 1e-3 * sum(b.m) * 9.81
def test_stiffer_orthogonality_keeps_a_spinning_body_closer_to_rigid():
"""Measured: the largest orthogonality error falls about 100 times for each factor 100 in kappa_o."""
errs = []
for ko in (1e5, 1e7):
b = ab.box(0.4, 0.2, 1000.0, ko, [], 1e-3, 1.0)
q = ab.rest_state((0.0, 0.0), 0.0)
qd = spin_rate(q, 10.0)
worst = 0.0
for _ in range(30):
q, qd, _ = ab.abd_step(b, q, qd, 0.01, gravity=(0.0, 0.0))
worst = max(worst, ab.orthogonality_error(q))
errs.append(worst)
assert 50.0 < errs[0] / errs[1] < 200.0
def test_free_fall_is_symplectic_euler():
b = ab.box(0.4, 0.2, 1000.0, 1e5, [], 1e-3, 1.0)
q, qd = ab.rest_state(), [0.0] * 6
for _ in range(10):
q, qd, _ = ab.abd_step(b, q, qd, 0.1)
assert abs(q[1] + 5.3955) < 1e-12 and abs(q[0]) < 1e-14
History
Rigid body solvers with impulses, penalties or complementarity contact have a long history in graphics. Barrier contact for rigid bodies followed the 2020 IPC paper, with curved trajectories that make collision checks expensive. Lan, Kaufman, Li, Jiang and Yang (2022) replaced rigid coordinates by affine ones with a stiff orthogonality energy and presented affine body dynamics at SIGGRAPH 2022.
References
- Lei Lan, Danny M. Kaufman, Minchen Li, Chenfanfu Jiang and Yin Yang, Affine body dynamics: fast, stable and intersection-free simulation of stiff materials, ACM Transactions on Graphics 41(4), 2022 (SIGGRAPH 2022), Section 3 (equation (1) the affine map, equations (3) to (5) the mass matrix and the equation of motion), Section 3.2 (equations (6) to (8), the orthogonality energy), Section 4 (equations (9) to (12), the incremental potential with barrier and friction), Section 4.1 (collision checks on straight paths), Section 4.3 (the Hessian), Section 5 (measurements)
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 J2K8MW Edit this page History Report an error Markdown