Algorithmcore
Baraff-Witkin implicit cloth
Also called large steps in cloth simulation.
Simulate triangle cloth with one linearized implicit Euler step per time step, solved by a conjugate gradient method that filters constraints, with energies built from triangle conditions.
- Solves
- Cloth simulation
- Time
- Θ(n + t + e) assembly · iterationΘ(k (n + t + e)) step
- Space
- Θ(n + t + e) matrix
- Where
- e = the number of interior edges; k = the number of conjugate gradient iterations in a step; n = the number of particles; t = the number of triangles
- Model
- Real RAM
- Properties
- constraints exactdeterministicnot exactimplicit
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Baraff, Andrew Witkin, 1998
Baraff and Witkin (1998) made cloth simulation fast by taking large steps. Cloth resists stretch much more than it resists bending, so the equations of motion are stiff, and an explicit integrator needs many tiny steps per frame. Their simulator takes one step of backward Euler, linearized at the start of the step, so each step is one sparse linear solve. The forces come from simple conditions on each triangle and edge: stretch, shear and bend. The linear system is solved by a conjugate gradient method that also keeps particle constraints exactly, for example a particle that is pinned or that slides on a floor.
In plain words
Cloth is easy to bend and very hard to stretch. If you simulate it by small pushes forward in time, the hard-to-stretch part forces you to take thousands of tiny steps every second, or the cloth explodes.
Baraff and Witkin instead ask, at each step: "what velocities at the end of the step are consistent with the forces at the end of the step?" They answer an approximate form of this question with one large but sparse system of equations, so the step can be as long as a frame of animation.
The forces come from three simple measurements on the cloth: how much each triangle is stretched, how much it is sheared, and how much two neighbouring triangles are folded. A particle that is held, or that rests on a surface, is handled inside the solver so that it stays exactly where it must.
The problem
Given a triangle mesh with rest coordinates for each vertex, positions , velocities , masses , external forces and a step , find and of one backward Euler step,
with some particles constrained: the change of particle has a given value in zero, one, two or three directions. This is one way to solve cloth simulation.
The algorithm
Masses (Section 2.2). Each triangle gives one third of its mass to each of its vertices.
Conditions and forces (Section 4). A condition , zero at rest, with stiffness has the energy , the force (equation (7)) and the Jacobian (equation (8)). For a triangle, the map from to the world has the derivatives (equation (9)), which are linear in the three vertex positions. With the rest area of the triangle:
- stretch, , two conditions, with for no stretch at rest (equation (10));
- shear, ;
- bend, , the angle between the normals of the two triangles at an interior edge.
Damping (Section 4.5). Each condition also has a damping force (equation (11)), with the rate of change of .
The step (Sections 3 and 5). Linearize the forces at the start of the step. Then backward Euler becomes one linear system (equations (15) and (16)), which is solved by modified-pcg. The filter of a particle removes the constrained directions: for a free particle, for a particle that cannot move along , for two such directions, and for a pinned particle (equation (13)). applies to each block . is the diagonal matrix with the entries .
BARAFF-WITKIN-STEP(x0, v0, h, {(S_i, z_i)})- 1
f, df/dx, df/dv <- sums over the stretch, shear and bend conditions, with damping - 2
A <- M - h df/dv - h^2 df/dx ; b <- h (f + f_ext + h (df/dx) v0) - 3
dv <- z ▷ constrained parts are right from the start - 4
delta0 <- filter(b)^T Q filter(b) ; r <- filter(b - A dv) - 5
c <- filter(Q r) ; delta_new <- r^T c - 6
while delta_new > eps^2 delta0: - 7
q <- filter(A c) ; alpha <- delta_new / (c^T q) - 8
dv <- dv + alpha c ; r <- r - alpha q - 9
s <- Q r ; delta_old <- delta_new ; delta_new <- r^T s - 10
c <- filter(s + (delta_new / delta_old) c) - 11
v1 <- v0 + dv ; x1 <- x0 + h v1
Lines L3 to L10 are the procedure modified-pcg of Section 5.3. Without constraints it is the standard preconditioned conjugate gradient method. The filter keeps every search direction in the free directions, so the constrained components of stay equal to at every iteration.
Damping Jacobian (Section 4.5). has a term that is not symmetric. The paper drops it so that stays symmetric; the code does the same. The paper says that dropping all of equation (12) causes serious problems.
Choices of this code. The bend Jacobian keeps only . That is exact where and keeps the bend part of positive semidefinite. The bend force itself is exact, with the angle gradient of Bridson, Marino and Fedkiw. The paper writes and then uses in but in , which read literally puts the two in different norms. The code uses the one diagonal matrix in all three places, which is the standard diagonal preconditioner. The code has no collisions, and the caller gives the constraints.
Example
A particle on a floor, by hand. One particle of kg rests on a floor with the normal , so and . It feels gravity and a side force of N, and s. With no elastic forces, and . Line L4 gives , line L5 gives and . One iteration gives , and , so the loop stops. The particle slides sideways and does not sink. The residual is times the force that the floor must supply, N upward. Section 5.3 of the paper uses this residual to find contact forces.
A stiff hanging sheet, measured. A 5 by 5 sheet with spacing m (32 triangles, 40 interior edges), density kg/m², stretch stiffness , shear stiffness and bend stiffness , no damping, hangs from two pinned corners with s and . The solve has 69 unknowns.
| step | 1 | 2 | 5 | 10 | 20 |
|---|---|---|---|---|---|
| modified-pcg iterations | 42 | 43 | 39 | 42 | 43 |
| largest speed (m/s) | 0.009 | 4.2e-4 | 3.7e-6 | 4.6e-10 | 4.1e-15 |
The sheet comes to rest in about ten steps although there is no damping force: this is the numerical damping of backward Euler, so the step is stable, and stable is not accurate. Explicit Euler with the same forces and step gives the elastic energies , and J after steps 2, 3 and 4.
Timings, measured by the authors. Baraff and Witkin (Section 8) report , , and seconds per frame for cloths of 500, 899, 2,602 and 7,359 particles on an SGI Octane R10000 at 195 MHz, slightly better than . They also report 50 to 100 iterations for a 6,000 node cloth (Section 1.1) and usually two to three steps per frame at 30 Hz.
Correctness
The claims are proved in proofs/correctness.md.
- Forces (proved). Each condition force is minus the gradient of , and is symmetric. The stretch and shear Jacobians of the code are exact; the bend Jacobian is exact where .
- Rest and rigid motion (proved). All internal forces are zero at rest and after a rigid motion, and they sum to zero.
- modified-pcg (proved). If is symmetric positive definite, modified-pcg is the standard preconditioned conjugate gradient method on the free directions. The constrained components equal after any number of iterations, and in exact arithmetic it reaches the solution of equation (14) in at most as many iterations as free directions.
- Momentum (proved). Without constraints, the change of linear momentum differs from by the sum of the residual blocks, so an exact solve keeps momentum exactly.
- Positive definiteness (model). The paper calls positive definite. That is true near rest, but compressed or sheared triangles add terms of either sign, so it is an assumption, not a theorem.
- Large steps (measured). The step is one Newton iteration of backward Euler. For nonlinear cloth this page claims no stability theorem; the bounded run above and in the tests is a measurement.
The tests check the bend gradient and the forces against central differences, zero force at rest and after a rotation, the stretch and shear Jacobians and their symmetry, the bend Jacobian at , both damping Jacobians, the dissipation of damping, modified-pcg against a dense solve with and without constraints, the constrained components after 0, 1, 2 and 5 iterations, the momentum to relative, and the stiff sheet against explicit Euler.
Proof: The condition forces are exact gradients, modified-pcg is preconditioned CG on the free directions, and the step keeps momentum up to the residualfull
We use the notation of the page. The state has particles in 3D. A condition with stiffness has the energy (Baraff and Witkin 1998, Section 4.1). , and the other state vectors have entries, in blocks of 3 per particle.
Forces and Jacobians
Lemma 1 (equations (7) and (8)). , and . The matrix is symmetric.
Proof. The chain rule for gives the force, and the product rule gives . Both terms of change into those of when and change places, because second derivatives commute.
The stretch condition. For a triangle with vertices and rest coordinates , equation (9) of the paper is with . With , this is and , with , , , and for both. The coefficients do not depend on , so . For , with ,
because the derivative of is . The same holds for with .
The shear condition. For (Section 4.3), and .
The bend condition. , the signed angle of the code. Its gradient is the formula of Bridson, Marino and Fedkiw; this note does not prove it, and the tests check it against central differences at ten random configurations. The code uses only the term of the bend Jacobian. The dropped term has the factor , so it is zero at every configuration with , and the Jacobian is exact there.
Lemma 2 (invariance). Every condition of the page has and for each . Hence the internal forces sum to zero and every block column of and of the damping Jacobians sums to zero. Every condition is zero at the rest state (, ) and keeps its value under a rigid motion, so all internal forces are zero there.
Proof. A translation of all particles by does not change , (the coefficients sum to zero) or . So for all , and the derivative in is . Differentiating this identity in gives the second claim. A rotation maps to and keeps lengths, dot products and the angle between normals. At rest, and , so the stretch and shear conditions are zero, and the sheet is flat, so . Each force is a multiple of or of , and when .
Damping
Lemma 3. For with (equation (11)): (a) , which is symmetric; (b) (equation (12)), and the code keeps only the second term, as the paper does; (c) .
Proof. is linear in with the gradient , which gives (a). The product rule gives (b). For (c), .
The term that the code drops makes asymmetric. Without it the matrix below is symmetric. The paper calls the omission "not physically justifiable" and reports no ill effects; this is a model choice, not a theorem. The test checks that the code's plus the dropped term equals central differences of .
The linear system
Linearize at and put into backward Euler . This gives equation (15):
By Lemmas 1 and 3, is symmetric. The paper calls positive definite. That holds when is positive semidefinite, for example near the rest state, but a compressed stretch condition or a sheared triangle adds terms of either sign, and a large can then make indefinite. This note assumes that is positive definite, as the paper does (model assumption).
modified-pcg
Let be the filter of particle (equation (13)): , , with orthonormal , or . Each is an orthogonal projection. Let be the block diagonal matrix of the , so . Choose a matrix with orthonormal columns that span the range of ; then and . The value lies in the range of , so .
The code applies one diagonal matrix , with for each of the components, wherever the paper writes or . The paper defines , uses in and in the products ; read literally, and would then be in different norms. Using in all three places is the standard preconditioned conjugate gradient method with the preconditioner . The value only sets the scale of the stopping test, so this choice does not change the iterates.
Theorem 4. Let , and . If is symmetric positive definite, then and are symmetric positive definite, and the iterates of modified-pcg are , and , where , and are the iterates of the standard preconditioned conjugate gradient method for with the preconditioner , started at . The scalars and of the two methods are equal.
Proof. is symmetric, and for , , so . The same argument works for , since is diagonal with positive entries ( for a positive definite ). Induction on . At the start (lines L3 to L5), , , so . Then , and , using . At an iteration (lines L7 to L10), , and , so is the same. The updates of and are the images under of the updates of and . The vector is not filtered, but it enters only through and through . These are the formulas of the standard method.
Corollary 5. (a) After any number of iterations, for every constrained particle. (b) In exact arithmetic, the method stops after at most iterations with the unique solution of with , which is equation (14) of the paper. (c) Without constraints this is the standard preconditioned conjugate gradient method for .
Proof. (a) , because and . (b) The standard method on an SPD system of dimension reaches the exact solution in at most steps, and is , which is . (c) Take , and .
The tests check (a) after 0, 1, 2 and 5 iterations, and the final against a dense solve of the reduced system , with two pinned particles and two particles on planes.
Momentum
Theorem 6. With no constraints, , the sum of the blocks of the residual. So the exact solve changes the linear momentum by exactly, and an inexact solve is off by the sum of its residual blocks.
Proof. By Lemma 2, every block column of and sums to zero, so . Also by Lemma 2, and , so . Subtract.
The test runs five steps with the tolerance and checks the momentum to relative.
Stable is not accurate
For a linear force , the linearization is exact, and one step is backward Euler. For one mass on one spring, the energy is then multiplied by at each step (the same computation as in the proof of the fast mass-spring page). So the step damps stiff motion strongly. For the nonlinear conditions of cloth, the page claims no stability theorem: the step is one Newton iteration of backward Euler, and the bounded run at a large step is a measurement.
Complexity
Each condition touches 3 or 4 particles, so assembling the forces and costs , and has nonzero blocks. One iteration of modified-pcg is one product with , a few vector operations and the filter, so it costs . A step with iterations costs . For a mesh, and are . The number depends on the conditioning of ; Baraff and Witkin measured a total cost close to per frame, which they relate to the usual behaviour of the conjugate gradient method on such systems.
Properties
- Large steps. In practice the step can be close to a frame long, because stiff stretch does not limit as it does for explicit methods (measured, not proved for the nonlinear case).
- Exact constraints. A pinned or sliding particle has its constrained velocity change exactly, whatever the number of iterations (proved).
- Damped. Backward Euler removes energy from fast motion, so large steps look calm. This is numerical damping, not a material property.
- Not exact. One linearized step is not the solution of the nonlinear backward Euler equations, and the conjugate gradient method stops at a tolerance.
- Anisotropic material. The stretch condition measures warp and weft separately through and , so the cloth can be stiffer in one direction.
Variants and improvements
- Adaptive step size (Section 7). The simulator rejects a step when the stretch changes too much and retries with a smaller step.
- Collisions (Section 6). Cloth-solid contact becomes a constraint in the filter, with chosen to push the particle out. Cloth-cloth contact uses stiff damped springs.
- Other energies. Later work replaces the conditions by finite elements, such as corotational FEM or the St. Venant-Kirchhoff model, and the bend condition by discrete shells or the quadratic bending model.
- Full Newton. Several Newton iterations with a line search solve the nonlinear step, as in optimization time integration.
- Constant matrix. Fast mass-spring and projective dynamics change the splitting so that the matrix stays the same over all steps.
- Robust collisions. Robust cloth collision handles cloth-cloth contact after each step, without stiff springs in the solve.
When to use it
Use it for cloth and other thin sheets where stretch is much stiffer than bending and steps of a frame or so are wanted: film and offline animation, and interactive tools with a few thousand particles.
Do not use it when you need accurate dynamics of fast motion with large steps, because backward Euler damps it. If the matrix can become indefinite, as under strong compression, use a Newton method with a definiteness fix. For real-time use with fixed topology, a constant-matrix method such as fast mass-spring can be cheaper.
Pitfalls
- Indefinite A. Compression of stretch conditions and shear add terms of either sign to . With a large step the conjugate gradient method can fail. A common fix is to drop or clamp these terms.
- Stopping test. comes from . If it is zero, the loop does not run, which is right only when the free part of is zero.
- Constraint values. Each must lie in the constrained directions, the range of . A component in the free directions is changed by the iterations.
- Dropping too much. Dropping the whole damping Jacobian is not the same as dropping its asymmetric term; the paper reports serious problems with it.
- Area scaling. The stretch and shear conditions are multiplied by the rest area , so the energy scales with , and stiffness values do not carry over between meshes of different resolution.
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
baraff_witkin_cloth.py 292 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-witkin-cloth/. The authors are listed in prov/7F3XVP.jsonl.
"""Large steps in cloth simulation (Baraff and Witkin 1998), in 3D.
The cloth is a triangle mesh with rest coordinates (u, v) for each vertex.
Each triangle has a stretch condition C = a (|w_u| - b_u, |w_v| - b_v) and a
shear condition C = a w_u . w_v, where (w_u w_v) = (dx1 dx2) [[du1, du2], [dv1, dv2]]^-1
and a is the rest area. Each interior edge has a bend condition C = theta, the
signed angle between the normals of its two triangles. A condition with
stiffness k has the energy k/2 C^2, the force f_i = -k dC/dx_i C and the
force Jacobian K_ij = -k (dC/dx_i dC/dx_j^T + d2C/dx_i dx_j C)
(equations (7) and (8) of the paper). The damping force is
d_i = -k_d dC/dx_i Cdot (equation (11)).
One step solves the linearized backward Euler system
(M - h df/dv - h^2 df/dx) dv = h (f0 + h df/dx v0) (equation (15)) with the
modified preconditioned conjugate gradient method of Section 5.3, which keeps
the constrained velocity components of each particle at the values z_i.
Simplifications of this code, not of the paper:
- The bend Jacobian keeps only the term -k dC/dx_i dC/dx_j^T (Gauss-Newton).
It is exact where theta = 0. The bend force itself is exact.
- No collisions. Constraints are given by the caller as {i: (S_i, z_i)}.
"""
import math
from anim import add, cross, dot, norm, scale, sub
GRAVITY = (0.0, -9.81, 0.0)
IDENTITY = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
ZERO3 = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
# ---------------------------------------------------------------- 3 by 3 blocks
def outer(a, b, s=1.0):
return [[s * a[r] * b[c] for c in range(3)] for r in range(3)]
def block_vec(m, x):
return (m[0][0] * x[0] + m[0][1] * x[1] + m[0][2] * x[2],
m[1][0] * x[0] + m[1][1] * x[1] + m[1][2] * x[2],
m[2][0] * x[0] + m[2][1] * x[1] + m[2][2] * x[2])
def add_block(mat, i, j, blk, s=1.0):
"""mat[i][j] += s blk for a sparse block matrix stored as {i: {j: 3 by 3}}."""
row = mat.setdefault(i, {})
cur = row.get(j)
if cur is None:
cur = [[0.0] * 3 for _ in range(3)]
row[j] = cur
for r in range(3):
for c in range(3):
cur[r][c] += s * blk[r][c]
def sparse_matvec(mat, x):
out = []
for i in range(len(x)):
s0 = s1 = s2 = 0.0
for j, m in mat.get(i, {}).items():
xj = x[j]
s0 += m[0][0] * xj[0] + m[0][1] * xj[1] + m[0][2] * xj[2]
s1 += m[1][0] * xj[0] + m[1][1] * xj[1] + m[1][2] * xj[2]
s2 += m[2][0] * xj[0] + m[2][1] * xj[1] + m[2][2] * xj[2]
out.append((s0, s1, s2))
return out
def vdot(a, b):
"""Dot product of two lists of 3-vectors."""
return sum(p[0] * q[0] + p[1] * q[1] + p[2] * q[2] for p, q in zip(a, b))
# ---------------------------------------------------------------- the cloth
class Cloth:
def __init__(self, uv, triangles, density=1.0, k_stretch=1.0, k_shear=1.0, k_bend=0.0,
kd_stretch=0.0, kd_shear=0.0, kd_bend=0.0, b_u=1.0, b_v=1.0, gravity=GRAVITY):
self.n = len(uv)
self.triangles = [tuple(t) for t in triangles]
self.k_stretch, self.k_shear, self.k_bend = k_stretch, k_shear, k_bend
self.kd_stretch, self.kd_shear, self.kd_bend = kd_stretch, kd_shear, kd_bend
self.b_u, self.b_v = b_u, b_v
self.rest = [] # per triangle: (area, cu, cv) with w_u = sum cu_i x_i and w_v = sum cv_i x_i
self.mass = [0.0] * self.n
for t in self.triangles:
p0, p1, p2 = (uv[i] for i in t)
du1, dv1 = p1[0] - p0[0], p1[1] - p0[1]
du2, dv2 = p2[0] - p0[0], p2[1] - p0[1]
det = du1 * dv2 - du2 * dv1
if det == 0.0:
raise ValueError("degenerate triangle in (u, v)")
cu1, cu2 = dv2 / det, -dv1 / det
cv1, cv2 = -du2 / det, du1 / det
area = 0.5 * abs(det)
self.rest.append((area, (-cu1 - cu2, cu1, cu2), (-cv1 - cv2, cv1, cv2)))
for i in t:
self.mass[i] += density * area / 3.0 # one third of each incident triangle
self.f_ext = [scale(gravity, m) for m in self.mass]
# bend edges (x1, x2, x3, x4): x3 -> x4 is the shared edge as it runs in the first
# triangle, x1 is opposite in that triangle and x2 is opposite in the other one
first = {}
self.edges = []
for t in self.triangles:
for e in range(3):
a, b, c = t[e], t[(e + 1) % 3], t[(e + 2) % 3]
if (b, a) in first:
self.edges.append((first.pop((b, a)), c, b, a))
else:
first[(a, b)] = c
# ------------------------------------------------------------ conditions
def conditions(self, x):
"""Return (indices, C, gradients, s, B, k, k_d) for every scalar condition.
The second derivative of C is d2C/dx_i dx_j = s[i][j] B, or s is None if
the code does not use it.
"""
out = []
for t, (area, cu, cv) in zip(self.triangles, self.rest):
xs = [x[i] for i in t]
wu = add(add(scale(xs[0], cu[0]), scale(xs[1], cu[1])), scale(xs[2], cu[2]))
wv = add(add(scale(xs[0], cv[0]), scale(xs[1], cv[1])), scale(xs[2], cv[2]))
for w, coef, b in ((wu, cu, self.b_u), (wv, cv, self.b_v)):
length = norm(w)
wh = scale(w, 1.0 / length)
grads = [scale(wh, area * coef[i]) for i in range(3)]
s = [[area * coef[i] * coef[j] / length for j in range(3)] for i in range(3)]
proj = [[(1.0 if r == c else 0.0) - wh[r] * wh[c] for c in range(3)] for r in range(3)]
out.append((t, area * (length - b), grads, s, proj, self.k_stretch, self.kd_stretch))
grads = [add(scale(wv, area * cu[i]), scale(wu, area * cv[i])) for i in range(3)]
s = [[area * (cu[i] * cv[j] + cv[i] * cu[j]) for j in range(3)] for i in range(3)]
out.append((t, area * dot(wu, wv), grads, s, IDENTITY, self.k_shear, self.kd_shear))
if self.k_bend != 0.0 or self.kd_bend != 0.0:
for e in self.edges:
theta, grads = bend_angle(*(x[i] for i in e))
out.append((e, theta, grads, None, None, self.k_bend, self.kd_bend))
return out
def energy(self, x):
return sum(0.5 * k * c * c for _, c, _, _, _, k, _ in self.conditions(x))
def forces(self, x, v):
"""Return (f, K, D): internal forces (elastic and damping), df/dx and df/dv as block matrices."""
f = [[0.0, 0.0, 0.0] for _ in range(self.n)]
kmat, dmat = {}, {}
for idx, c, grads, s, base, k, kd in self.conditions(x):
cdot = sum(dot(g, v[i]) for g, i in zip(grads, idx))
for a, i in enumerate(idx):
fi = f[i]
coef = -k * c - kd * cdot # equations (7) and (11)
for r in range(3):
fi[r] += coef * grads[a][r]
for b, j in enumerate(idx):
gg = outer(grads[a], grads[b])
add_block(kmat, i, j, gg, -k) # equation (8), first term
if s is not None:
# equation (8), second term, and equation (12) without its asymmetric term
add_block(kmat, i, j, base, -(k * c + kd * cdot) * s[a][b])
if kd != 0.0:
add_block(dmat, i, j, gg, -kd) # dd/dv
return [tuple(fi) for fi in f], kmat, dmat
# ------------------------------------------------------------ one step
def system(self, x, v, h):
"""Return the block matrix A = M - h df/dv - h^2 df/dx and b = h (f0 + h df/dx v0)."""
f, kmat, dmat = self.forces(x, v) # @line L1
amat = {}
for i in range(self.n):
add_block(amat, i, i, IDENTITY, self.mass[i])
for src, w in ((kmat, -h * h), (dmat, -h)):
for i, row in src.items():
for j, blk in row.items():
add_block(amat, i, j, blk, w)
kv = sparse_matvec(kmat, v)
b = [scale(add(add(f[i], self.f_ext[i]), scale(kv[i], h)), h) for i in range(self.n)] # @line L2
return amat, b
def step(self, x, v, h, constraints=None, eps=1e-8, max_iter=2000):
"""One step. Return (x, v, iterations of modified-pcg)."""
amat, b = self.system(x, v, h)
dv, iters = modified_pcg(amat, b, constraints or {}, eps, max_iter)
new_v = [add(v[i], dv[i]) for i in range(self.n)]
new_x = [add(x[i], scale(new_v[i], h)) for i in range(self.n)] # @line L11
return new_x, new_v, iters
def bend_angle(x1, x2, x3, x4):
"""Signed angle theta between the triangles (x3, x4, x1) and (x4, x3, x2), and d theta/dx.
theta = atan2((n2 x n1) . e, n1 . n2) with the unit edge e from x3 to x4 and
n1 = (x1 - x3) x (x1 - x4), n2 = (x2 - x4) x (x2 - x3). The gradient is the
formula of Bridson, Marino and Fedkiw (2003). The tests check it against
central differences of theta.
"""
e = sub(x4, x3)
n1 = cross(sub(x1, x3), sub(x1, x4))
n2 = cross(sub(x2, x4), sub(x2, x3))
le = norm(e)
q1, q2 = dot(n1, n1), dot(n2, n2)
theta = math.atan2(dot(cross(n2, n1), e) / le, dot(n1, n2))
a1, a2 = scale(n1, 1.0 / q1), scale(n2, 1.0 / q2)
u1 = scale(a1, le)
u2 = scale(a2, le)
u3 = add(scale(a1, dot(sub(x1, x4), e) / le), scale(a2, dot(sub(x2, x4), e) / le))
u4 = scale(add(scale(a1, dot(sub(x1, x3), e) / le), scale(a2, dot(sub(x2, x3), e) / le)), -1.0)
return theta, [u1, u2, u3, u4]
# ---------------------------------------------------------------- modified-pcg
def modified_pcg(amat, b, constraints, eps=1e-8, max_iter=2000):
"""Solve A dv = b with the components of particle i in the range of I - S_i fixed at z_i.
constraints maps a particle i to (S_i, z_i), with S_i one of the filters of
equation (13) and z_i in the range of I - S_i. The preconditioner is the
diagonal of A, so applying P^-1 divides each component by A_ii.
Return (dv, iterations).
"""
n = len(b)
def filt(a):
return [block_vec(constraints[i][0], a[i]) if i in constraints else a[i] for i in range(n)]
inv_diag = [tuple(1.0 / amat[i][i][r][r] for r in range(3)) for i in range(n)]
def precond(a):
return [(p[0] * q[0], p[1] * q[1], p[2] * q[2]) for p, q in zip(inv_diag, a)]
dv = [tuple(constraints[i][1]) if i in constraints else (0.0, 0.0, 0.0) for i in range(n)] # @line L3
fb = filt(b)
delta0 = vdot(fb, precond(fb))
av = sparse_matvec(amat, dv)
r = filt([sub(b[i], av[i]) for i in range(n)]) # @line L4
c = filt(precond(r))
delta_new = vdot(r, c) # @line L5
iters = 0
while delta_new > eps * eps * delta0 and iters < max_iter: # @line L6
q = filt(sparse_matvec(amat, c))
alpha = delta_new / vdot(c, q) # @line L7
dv = [add(dv[i], scale(c[i], alpha)) for i in range(n)]
r = [sub(r[i], scale(q[i], alpha)) for i in range(n)] # @line L8
s = precond(r)
delta_old, delta_new = delta_new, vdot(r, s) # @line L9
beta = delta_new / delta_old
c = filt([add(s[i], scale(c[i], beta)) for i in range(n)]) # @line L10
iters += 1
return dv, iters
def constraint_force(amat, b, dv):
"""e = A dv - b. For a constrained particle, e_i is the force that kept the constraint (Section 5.3)."""
av = sparse_matvec(amat, dv)
return [sub(av[i], b[i]) for i in range(len(b))]
# ---------------------------------------------------------------- filters and meshes
def pin(z=(0.0, 0.0, 0.0)):
"""A filter that fixes all three components of dv at z."""
return (ZERO3, tuple(z))
def plane(p, z_along):
"""A filter that fixes the dv component along the unit vector p at z_along."""
s = [[(1.0 if r == c else 0.0) - p[r] * p[c] for c in range(3)] for r in range(3)]
return (s, scale(p, z_along))
def grid(nx, ny, spacing):
"""A grid cloth in the plane z = 0. Return (uv, triangles, x) with x = (u, -v, 0)."""
def idx(i, j):
return j * nx + i
uv = [(i * spacing, j * spacing) for j in range(ny) for i in range(nx)]
tris = []
for j in range(ny - 1):
for i in range(nx - 1):
tris.append((idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)))
tris.append((idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)))
x = [(u, -w, 0.0) for u, w in uv]
return uv, tris, x
test_baraff_witkin_cloth.py 236 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/baraff-witkin-cloth/. The authors are listed in prov/7F3XVP.jsonl.
"""Tests of Baraff-Witkin cloth against central differences, a dense solve and exact identities."""
import math
import random
from anim import num_grad, q_from_axis_angle, q_rotate, solve
import baraff_witkin_cloth as bw
def flat(xs):
return [c for p in xs for c in p]
def unflat(f):
return [tuple(f[3 * i:3 * i + 3]) for i in range(len(f) // 3)]
def jiggle(rng, x, a):
return [tuple(c + rng.uniform(-a, a) for c in p) for p in x]
def dense(mat, n):
out = [[0.0] * (3 * n) for _ in range(3 * n)]
for i, row in mat.items():
for j, blk in row.items():
for r in range(3):
for c in range(3):
out[3 * i + r][3 * j + c] = blk[r][c]
return out
def numeric_jacobian(fun, x):
"""Central differences of a list-of-3-vectors function, as a dense 3n by 3n matrix."""
n = len(x)
flat_x = flat(x)
cols = []
for k in range(3 * n):
def comp(t, k=k):
y = list(flat_x)
y[k] += t
return flat(fun(unflat(y)))
p, m = comp(1e-6), comp(-1e-6)
cols.append([(a - b) / 2e-6 for a, b in zip(p, m)])
return [list(row) for row in zip(*cols)]
def test_bend_gradient_against_num_grad():
rng = random.Random(1)
for _ in range(10):
pts = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
_, g = bw.bend_angle(*pts)
ng = num_grad(lambda f: bw.bend_angle(*unflat(f))[0], flat(pts))
assert max(abs(a - b) for a, b in zip(flat(g), ng)) <= 1e-6 * max(abs(c) for c in ng)
def test_forces_against_num_grad_rest_and_rotation():
rng = random.Random(2)
uv, tris, x = bw.grid(4, 4, 0.1)
cl = bw.Cloth(uv, tris, density=0.5, k_stretch=100.0, k_shear=10.0, k_bend=0.01)
y = jiggle(rng, x, 0.02)
f, _, _ = cl.forces(y, [(0.0, 0.0, 0.0)] * len(y))
ng = num_grad(lambda fl: cl.energy(unflat(fl)), flat(y))
assert max(abs(a + b) for a, b in zip(flat(f), ng)) <= 1e-6 * max(abs(c) for c in ng)
# zero force at rest and after a rigid motion
q = q_from_axis_angle((0.3, -1.0, 0.5), 0.9)
for z in (x, [tuple(c + d for c, d in zip(q_rotate(q, p), (0.2, -0.4, 1.0))) for p in x]):
f, _, _ = cl.forces(z, [(0.0, 0.0, 0.0)] * len(z))
assert max(abs(c) for fi in f for c in fi) < 1e-10
def test_stretch_and_shear_jacobian_against_central_differences():
rng = random.Random(3)
uv, tris, x = bw.grid(3, 3, 0.1)
cl = bw.Cloth(uv, tris, k_stretch=200.0, k_shear=30.0)
y = jiggle(rng, x, 0.03)
zero = [(0.0, 0.0, 0.0)] * len(y)
_, kmat, _ = cl.forces(y, zero)
got = dense(kmat, len(y))
want = numeric_jacobian(lambda z: cl.forces(z, zero)[0], y)
scale = max(abs(c) for row in want for c in row)
for i in range(len(got)):
for j in range(len(got)):
assert abs(got[i][j] - want[i][j]) <= 1e-6 * scale
assert got[i][j] == got[j][i] or abs(got[i][j] - got[j][i]) <= 1e-12 * scale
def test_bend_jacobian_is_exact_where_theta_is_zero():
"""The code keeps only -k dC dC^T of the bend Jacobian, which is exact at theta = 0."""
rng = random.Random(4)
uv, tris, x = bw.grid(3, 3, 0.1)
cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, k_bend=0.5)
# a stretched flat sheet: every theta is zero
y = [(1.3 * p[0] + rng.uniform(-0.01, 0.01), 0.8 * p[1] + rng.uniform(-0.01, 0.01), 0.0) for p in x]
zero = [(0.0, 0.0, 0.0)] * len(y)
got = dense(cl.forces(y, zero)[1], len(y))
want = numeric_jacobian(lambda z: cl.forces(z, zero)[0], y)
scale = max(abs(c) for row in want for c in row)
assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale
def test_damping_velocity_jacobian_and_dissipation():
rng = random.Random(5)
uv, tris, x = bw.grid(3, 3, 0.1)
cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, k_bend=0.0, kd_stretch=2.0, kd_shear=1.0, kd_bend=0.3)
y = jiggle(rng, x, 0.03)
v = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in y]
f, _, dmat = cl.forces(y, v)
got = dense(dmat, len(y))
want = numeric_jacobian(lambda w: cl.forces(y, w)[0], v)
scale = max(abs(c) for row in want for c in row)
assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale
# d . v = -sum k_d Cdot^2 <= 0, and the damping forces sum to zero
assert sum(a * b for a, b in zip(flat(f), flat(v))) < 0.0
for c in range(3):
assert abs(sum(fi[c] for fi in f)) < 1e-12
def test_damping_position_jacobian_drops_only_the_asymmetric_term():
"""Equation (12) minus the term dC/dx_i (dCdot/dx_j)^T equals the code's dd/dx."""
rng = random.Random(6)
uv, tris, x = bw.grid(3, 3, 0.1)
cl = bw.Cloth(uv, tris, k_stretch=0.0, k_shear=0.0, kd_stretch=2.0, kd_shear=1.0)
y = jiggle(rng, x, 0.03)
v = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in y]
n = len(y)
got = dense(cl.forces(y, v)[1], n)
for idx, c, grads, s, base, k, kd in cl.conditions(y):
for b, j in enumerate(idx):
# dCdot/dx_j = sum_l s[l][j] B v_l
dcd = [sum(s[l][b] * sum(base[r][t] * v[idx[l]][t] for t in range(3)) for l in range(3))
for r in range(3)]
for a, i in enumerate(idx):
for r in range(3):
for t in range(3):
got[3 * i + r][3 * j + t] -= kd * grads[a][r] * dcd[t]
want = numeric_jacobian(lambda z: cl.forces(z, v)[0], y)
scale = max(abs(c) for row in want for c in row)
assert max(abs(a - b) for ra, rb in zip(got, want) for a, b in zip(ra, rb)) <= 1e-6 * scale
def scene(rng, nx=4):
uv, tris, x = bw.grid(nx, nx, 0.1)
cl = bw.Cloth(uv, tris, density=0.4, k_stretch=500.0, k_shear=50.0, k_bend=1e-3,
kd_stretch=0.5, kd_shear=0.1, kd_bend=1e-4)
y = jiggle(rng, x, 0.02)
v = [tuple(rng.uniform(-0.5, 0.5) for _ in range(3)) for _ in y]
return cl, y, v
def test_modified_pcg_without_constraints_matches_a_dense_solve():
cl, y, v = scene(random.Random(7))
amat, b = cl.system(y, v, 0.02)
dv, iters = bw.modified_pcg(amat, b, {}, eps=1e-13)
want = solve(dense(amat, cl.n), flat(b))
assert max(abs(p - q) for p, q in zip(flat(dv), want)) <= 1e-9 * max(abs(q) for q in want)
assert iters <= 3 * cl.n * 2
def test_modified_pcg_with_constraints_matches_the_reduced_solve():
cl, y, v = scene(random.Random(8))
amat, b = cl.system(y, v, 0.02)
p = (0.0, 0.6, 0.8)
cons = {0: bw.pin((0.1, -0.2, 0.3)), 3: bw.pin(), 6: bw.plane(p, -0.25),
9: bw.plane((1.0, 0.0, 0.0), 0.0)}
# the basis B of the free directions, dv = z + B alpha
basis = []
other = {6: [(1.0, 0.0, 0.0), (0.0, 0.8, -0.6)], 9: [(0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]}
for i in range(cl.n):
if i in other:
dirs = other[i]
elif i in cons:
dirs = []
else:
dirs = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]
for d in dirs:
col = [0.0] * (3 * cl.n)
col[3 * i:3 * i + 3] = d
basis.append(col)
a = dense(amat, cl.n)
z = [0.0] * (3 * cl.n)
for i, (_, zi) in cons.items():
z[3 * i:3 * i + 3] = zi
az = [sum(a[r][c] * z[c] for c in range(3 * cl.n)) for r in range(3 * cl.n)]
rhs = [sum(col[r] * (flat(b)[r] - az[r]) for r in range(3 * cl.n)) for col in basis]
ab = [[sum(a[r][c] * col[c] for c in range(3 * cl.n)) for r in range(3 * cl.n)] for col in basis]
red = [[sum(ci[r] * abj[r] for r in range(3 * cl.n)) for abj in ab] for ci in basis]
alpha = solve(red, rhs)
want = [z[r] + sum(al * col[r] for al, col in zip(alpha, basis)) for r in range(3 * cl.n)]
dv, _ = bw.modified_pcg(amat, b, cons, eps=1e-13)
assert max(abs(p - q) for p, q in zip(flat(dv), want)) <= 1e-9 * max(abs(q) for q in want)
# the constrained components equal z after any number of iterations
for it in (0, 1, 2, 5):
dv, _ = bw.modified_pcg(amat, b, cons, eps=0.0, max_iter=it)
for i, (s, zi) in cons.items():
fixed = [dv[i][r] - sum(s[r][c] * dv[i][c] for c in range(3)) for r in range(3)]
assert max(abs(fc - zc) for fc, zc in zip(fixed, zi)) < 1e-15
def test_momentum_of_one_step_without_constraints():
rng = random.Random(9)
cl, y, v = scene(rng)
total = sum(cl.mass)
p0 = [sum(m * vi[c] for m, vi in zip(cl.mass, v)) for c in range(3)]
h = 0.02
for k in range(1, 6):
y, v, _ = cl.step(y, v, h, eps=1e-14, max_iter=400)
for c in range(3):
want = p0[c] + k * h * total * bw.GRAVITY[c]
got = sum(m * vi[c] for m, vi in zip(cl.mass, v))
assert abs(got - want) <= 1e-10 * max(1.0, abs(p0[c]), abs(want))
def test_large_step_stays_bounded_where_explicit_euler_fails():
nx = 5
uv, tris, x0 = bw.grid(nx, nx, 0.1)
cl = bw.Cloth(uv, tris, density=0.4, k_stretch=1e6, k_shear=1e5, k_bend=1e-4)
cons = {0: bw.pin(), nx - 1: bw.pin()}
h = 1.0 / 30.0
x, v = list(x0), [(0.0, 0.0, 0.0)] * len(x0)
for _ in range(20):
x, v, _ = cl.step(x, v, h, cons, eps=1e-6)
assert cl.energy(x) < 1e-3 and max(math.sqrt(sum(c * c for c in vi)) for vi in v) < 1.0
assert x[0] == x0[0] and x[nx - 1] == x0[nx - 1]
# explicit Euler with the same step and forces
x, v = list(x0), [(0.0, 0.0, 0.0)] * len(x0)
for _ in range(6):
f, _, _ = cl.forces(x, v)
nv = [(0.0, 0.0, 0.0) if i in cons else
tuple(v[i][c] + h * (f[i][c] + cl.f_ext[i][c]) / cl.mass[i] for c in range(3))
for i in range(len(x))]
x = [tuple(x[i][c] + h * v[i][c] for c in range(3)) for i in range(len(x))]
v = nv
assert cl.energy(x) > 1e6
History
David Baraff and Andrew Witkin presented the method at SIGGRAPH 1998. Earlier cloth simulators, such as the particle model of Breen, House and Wozny and the spring model of Provot, used explicit steps, and the paper reports running times of several minutes per frame for garments of about a thousand nodes in earlier work. The combination of implicit steps, conditions on triangles and the filtered conjugate gradient method cut this to seconds per frame on the hardware of 1998. Bridson, Fedkiw and Anderson (2002) wrote that it "generated convincing results despite dropping nonsymmetric terms from their matrix".
References
- David Baraff and Andrew Witkin, Large steps in cloth simulation, Proceedings of SIGGRAPH 98, pages 43 to 54, 1998, Section 2.2 (masses), Section 3, equations (4) to (6) (the implicit step), Section 4, equations (7) to (12) (conditions, forces, Jacobians and damping), Section 5, equations (13) to (16) and the procedure modified-pcg (constraints), Section 6 (collisions), Section 7 (adaptive steps), Section 8 (timings)
- Robert Bridson, Sebastian Marino and Ronald Fedkiw, Simulation of clothing with folds and wrinkles, ACM SIGGRAPH 2005 Courses (first published at the Symposium on Computer Animation 2003), the gradient of the dihedral angle used by the bend condition of the code
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 7F3XVP Edit this page History Report an error Markdown