Algorithmcore
Provot's strain limiting
Also called inverse dynamic constraints.
After each step, shorten springs stretched beyond a limit such as ten percent by moving their end points, to avoid the super-elastic look of soft springs.
- Solves
- Cloth simulation
- Time
- Θ(k m) correctionΘ(n + k m) stepΘ(m) sweep
- Space
- Θ(n) extra
- Where
- k = the number of sweeps; m = the number of limited springs; n = the number of particles
- Model
- Real RAM
- Properties
- converges when feasibledeterministicnot exactorder dependent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Xavier Provot, 1995
Provot's strain limiting is a correction that runs after each step of a mass-spring cloth. The springs are kept soft so that an explicit step stays stable. A soft spring stretches too much under load, so after the step every spring that is longer than times its rest length, with about 10%, is shortened by moving its end points along the spring. Provot (1995) called this an inverse dynamic procedure and used it to make cloth that looks stiff with springs that are not. The same idea, a projection of positions onto constraints, is at the core of later position-based dynamics.
In plain words
Real cloth hardly stretches. A spring model of cloth needs very stiff springs to match that, and stiff springs force tiny time steps. With softer springs the steps can be larger, but a hanging cloth then stretches like rubber near the points that hold it.
Provot's fix is to let the soft springs move the cloth as usual, and then check every spring. If a spring is more than 10% longer than its rest length, its two ends are pulled toward each other until it is exactly 10% longer. If one end is pinned, only the other end moves. If both ends are pinned, nothing can be done.
Fixing one spring can stretch its neighbour again, so one pass over the springs does not fix all of them. Repeating the pass helps, and it settles down whenever the limits can all hold at once.
The problem
Given particle positions after an explicit step of a mass-spring system, a list of springs and a limit , move the free particles so that every spring has the length , with small moves. This is a step inside cloth simulation. The force model, the stiffness and the time step stay as they were; the correction only changes positions (and then the velocities that follow from them).
The algorithm
PROVOT-STRAIN-LIMIT(x, springs, tau)- 1
repeat for the given number of sweeps (or until no spring is longer than (1 + tau) L) - 2
for each spring (a, b, L) in the list order: - 3
d <- x_b - x_a, l <- |d|, r <- (1 + tau)(1 - sigma) L - 4
if l <= r or both a and b are fixed: skip the spring - 5
e <- (l - r) d / l ▷ the excess, as a vector - 6
if a and b are free: x_a <- x_a + s_a e, x_b <- x_b - s_b e ▷ s_a = s_b = 1/2 - 7
else if a is free: x_a <- x_a + e - 8
else: x_b <- x_b - e PROVOT-STEP(x, v, dt)- 9
x* <- the positions after one explicit step of the spring system - 10
x_new <- PROVOT-STRAIN-LIMIT(x*, springs, tau) - 11
v_new <- (x_new - x) / dt
The correction (L3 to L8). These are Provot's three rules from Section 5 of the paper. If both ends are free, both move toward the middle by half of the excess. If one end is fixed, the free end takes the whole excess. If both are fixed, the spring is left alone. Each correction uses the positions left by the corrections before it, so the result depends on the order of the springs, which Provot did not consider. The code also has a mass split with inverse masses , which keeps the centre of mass; Provot's cloth had equal masses, where the two splits agree.
The slack . Provot's rule has . The code accepts a small , for example , which aims a little below the limit. Then repeated sweeps stop after a finite number of sweeps with every spring inside the limit (Corollary 5 of the proof page). The value is a tuning constant of this code, not of the paper.
Which springs. Provot used on the structural springs, and in a second version on the structural and shear springs (Section 6). The code takes the list of springs to correct as a parameter.
Velocities (L11). The code sets each velocity to the straight move from the old to the new position, so the next step does not undo the correction. This is a choice of this code.
Example
One sweep by hand. Three free particles lie on a line at , and , joined by two springs of rest length 1, with , so the limit is .
| first spring | second spring | ||||
|---|---|---|---|---|---|
| start | 0 | 1.5 | 3.5 | 1.5 | 2.0 |
| after the first spring | 0.2 | 1.3 | 3.5 | 1.1 | 2.2 |
| after the second spring | 0.2 | 1.85 | 2.95 | 1.65 | 1.1 |
The first correction moves both ends by . The second spring is now longer, , and its correction moves its ends by each. That stretches the first spring to , a strain of 65%. Repeated sweeps with stop after 6 sweeps, with both springs inside the limit.
A hanging cloth, measured. A 9 by 9 grid with a spacing of m, particles of kg, structural and shear springs of N/m and a damping of N s/m along each spring hangs from its two top corners under gravity. It runs for 1000 steps of s with symplectic Euler. The table gives the largest strain of a structural spring over the run, with the correction on the structural springs and .
| correction | largest structural strain |
|---|---|
| none | 72.5% |
| one sweep per step | 12.8% |
| two sweeps per step | 11.2% |
| sweeps until done, | 10.0% (never above the limit) |
Without the correction the cloth near the corners stretches like rubber. With one sweep it stays close to the limit but above it. Two sweeps are better, as Provot also observed (Section 6), and repeated sweeps meet the limit.
Correctness
The claims are about the positions; they are proved in proofs/correctness.md.
- One correction (proved). After lines L5 to L8 the spring has the length and the same direction. The equal split keeps the midpoint of the pair; the mass split keeps its centre of mass.
- A projection (proved). One correction moves the free positions to the closest point of the set , in the plain norm for the equal split and in the mass norm for the mass split. That set is convex.
- Repeated sweeps converge when the limits can hold (proved). If some placement of the free particles meets every limit, the sweeps are cyclic projections onto closed convex sets with a common point, and they converge to a point that meets every limit. Provot (Section 6) wrote that the repeated procedure seemed to converge; this is the reason. With they stop after finitely many sweeps. Pins at their rest positions are enough, because the rest shape meets every limit.
- They cannot converge otherwise (proved). If the pins force a stretch, no placement meets the limits. A chain of springs between pins at the distance always has a spring at least 30% too long. Bridson, Fedkiw and Anderson (2002, Section 4) name this case.
- One sweep gives no bound (proved by the example). A later correction can undo an earlier one.
The tests check one correction against hand values, the projection against a brute force search over random allowed points, the centre of mass to relative, the hand example, the finite end of the sweeps with pins at rest, the case that cannot converge, and the hanging cloth.
Proof: Each correction is a projection, and repeated sweeps converge when the limits can holdfull
We use the notation of the page. A spring has the limit , where is the slack ( in Provot's rule). The variables are the positions of the free particles; a fixed particle is a constant. Write for the vector of all free positions, and give it the norm , with for Provot's equal split and for the mass split. For a spring with at least one free end let
The vector is an affine function of , and a ball is convex, so is a closed convex set.
One correction
Lemma 1. Let with and , as in line L5. After lines L6 to L8 the spring has the length and the same direction. In the equal split the midpoint of the two particles stays; in the mass split their centre of mass stays.
Proof. Both ends free: the new separation is , because . One end free: the new separation is as well. Now , which has the length and the direction of . The change of is , which is zero for . For the mass split, , so the change of is zero.
Lemma 2. Lines L3 to L8 map to the closest point of in the norm .
Proof. If , then and line L4 keeps it, which is the closest point. Let . Only the free ends of appear in the constraint, so the closest point changes only those.
Both ends free. Write and for the moves and for the new separation. For a fixed , minimize subject to . The minimum is at and , with the value . So the best is the point of the ball closest to , which is . Then and . For the factors are , which is line L6 in the equal split. For , , which is line L6 in the mass split.
One end free, say . The new separation is , and the closest point of the ball to is , so , which is line L7. Line L8 is the same with the roles exchanged.
A spring with two fixed ends has no variables; line L4 skips it.
Repeated sweeps
Let be the map of Lemma 2. One sweep (line L2) is the composition of the in the order of the list. Let be the input and the state after sweeps.
Lemma 3. For a closed convex set , its projection and any , .
Proof. The projection is characterized by for all . Expand , and the last term is at least zero.
Theorem 4. If the sets have a common point, the states converge to a common point of all .
Proof. Let be a common point. By Lemma 3 each single correction does not increase the distance to , and the sum of the squared lengths of all moves over all sweeps is at most . So the states are bounded, and the total move in sweep tends to zero, since a sweep has a fixed number of moves. Take a subsequence . Inside sweep , the state right after the correction of spring lies in and is within of . As these states tend to , and is closed, so for every . Now apply the first sentence with : the distance never increases, and it tends to zero along the subsequence, so it tends to zero.
This answers the remark of Provot (1995, Section 6) that the repeated procedure seems to converge: it does, whenever the limits can hold at the same time. The theorem says nothing about one sweep, and the limit may be reached only in the limit of infinitely many sweeps.
Corollary 5. Let , and let the sets with the shortened limits have a common point. Then after a finite number of sweeps no spring is longer than , and the loop of line L1 stops.
Proof. By Theorem 4 the states converge to a point where every spring has length at most . The lengths are continuous in , and there are finitely many springs, so there is a ball around where every spring is shorter than . The states enter the ball after finitely many sweeps.
A sufficient condition. If every fixed particle is at its rest position and , the rest shape is a common point, because there every spring has the length . The test with pins at the rest positions uses this.
When the limits cannot hold. If the fixed particles force a stretch, no common point exists and the loop cannot stop. For a chain of springs of rest length between two fixed particles at the distance , the triangle inequality gives , so some spring has . For some spring is at least 30% too long after any number of sweeps. This is the case that Bridson, Fedkiw and Anderson (2002, Section 4) name.
One sweep is not enough. Take three free particles at , and on a line, two springs of rest length 1 and . The first correction moves the first two particles to and . The second spring then has the length , and its correction moves the last two particles to and . Now the first spring has the length , a strain of 65%. A later correction can stretch a spring that an earlier one fixed, so a single sweep gives no bound on the strain.
The step
Lines L9 to L11 call the explicit step, then the sweeps, then set . So the positions at the end of the step obey the statements above, and the velocity is the one of the straight move from the old to the new positions. For a fixed particle, and the velocity is zero.
Complexity
One correction costs , so a sweep costs for limited springs, and sweeps cost on top of the explicit step of . The extra space is for the new positions. Provot measured the cost of the correction at about 15% above the plain spring model (Section 6); that is a measurement on his scenes. The number of sweeps until the end in Corollary 5 has no useful bound in general: the convergence of cyclic projections can be slow.
Properties
- Explicit and simple. No linear system, no stiffness matrix. Each correction is a few lines.
- Order dependent. The Gauss-Seidel order changes the result and can bias the cloth toward the springs visited last.
- Not momentum conserving with pins. A pinned particle does not move, so the free end takes the whole correction. Away from the pins, the mass split keeps the linear momentum of each pair.
- Only stretch. The rule shortens long springs and leaves short springs alone, so compression is not limited.
- A heuristic, not a force law. The correction moves positions without a force, so no law of motion controls its effect on the energy. It is a heuristic for the look of stiff cloth, and the limit is a tuning value.
Variants and improvements
- Velocity filter. Bridson, Fedkiw and Anderson (2002, Section 4) apply momentum-conserving impulses to the velocities so that no spring is deformed by more than 10% at the end of the step, and also limit the change of strain per step. They use Jacobi iteration to avoid the bias of Gauss-Seidel order; convergence is not guaranteed, but they report one or two iterations per step.
- Strain limiting on triangles. Later work limits the principal stretches of each triangle instead of spring lengths.
- Position-based dynamics. Position-based dynamics and extended position-based dynamics use the same projection for every constraint and drop the soft forces altogether.
- Exact inextensibility. Fast projection methods solve for the positions that meet all length constraints at once, with a Newton-like step on the constraints, instead of one spring at a time.
When to use it
Use it with an explicit mass-spring cloth whose springs must stay soft for a stable step, to keep the stretch inside a few percent. It is cheap and easy to add after any integrator. Pair it with repeated sweeps when the scene is pinned near its rest shape.
Do not rely on it when pins or obstacles force a stretch: the sweeps then cannot meet the limits and the cloth may jitter. For stiff cloth with large steps, an implicit method such as Baraff-Witkin cloth or fast mass-spring simulation is the usual choice.
Pitfalls
- Forgetting the velocities. If only the positions are corrected, the velocity still carries the stretch, and the next step stretches the cloth again.
- One sweep and a hard limit. A single sweep leaves springs above the limit, as the example shows. Code that assumes all springs are inside the limit after one sweep is wrong.
- Infeasible pins. Pins that are moved apart by an animator can make the limits impossible. Cap the number of sweeps.
- Floating point. With a corrected spring has the length only up to rounding; the hand example gives a strain of . A strict check needs a small slack.
- Mixing with collision handling. The correction can push particles into an obstacle. Run collision handling after it, or include the contacts in the same sweeps.
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
provot_strain_limiting.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/provot-strain-limiting/. The authors are listed in prov/SR6S3F.jsonl.
"""Provot's strain limiting on a 2D mass-spring system.
After an explicit step, each spring longer than (1 + tau) L is shortened by
moving its ends along the spring (Provot 1995, Section 5). Both ends free: both
move, by half the excess each in Provot's rule. One end fixed: only the free end
moves. Both ends fixed: nothing changes. The springs are visited in order and
each correction uses the positions that the earlier corrections left
(Gauss-Seidel). A sweep can be repeated.
A spring (a, b, rest, k) is a tuple. A particle with inverse mass 0 is fixed.
Positions are (x, y) in metres with y up.
"""
import math
GRAVITY = (0.0, -9.81)
def strain(x, spring):
"""(l - L) / L for one spring."""
a, b, rest = spring[0], spring[1], spring[2]
return (math.dist(x[a], x[b]) - rest) / rest
def max_strain(x, springs):
return max(strain(x, s) for s in springs)
def correct_spring(x, inv_mass, spring, target, weights="equal"):
"""Shorten one spring to the length target if it is longer. Change x in place.
weights="equal" is Provot's rule: half of the excess at each free end.
weights="mass" splits the excess by inverse mass, which keeps the centre of
mass of the two particles. Return True if a particle moved.
"""
a, b = spring[0], spring[1]
dx = x[b][0] - x[a][0]
dy = x[b][1] - x[a][1]
length = math.hypot(dx, dy) # @line L3
wa, wb = inv_mass[a], inv_mass[b]
if length <= target or (wa == 0.0 and wb == 0.0): # @line L4
return False
k = (length - target) / length
ex, ey = k * dx, k * dy # @line L5
if wa > 0.0 and wb > 0.0:
if weights == "equal":
sa = sb = 0.5
else:
sa = wa / (wa + wb)
sb = wb / (wa + wb)
x[a] = (x[a][0] + sa * ex, x[a][1] + sa * ey) # @line L6
x[b] = (x[b][0] - sb * ex, x[b][1] - sb * ey)
elif wa > 0.0:
x[a] = (x[a][0] + ex, x[a][1] + ey) # @line L7
else:
x[b] = (x[b][0] - ex, x[b][1] - ey) # @line L8
return True
def limit_strain(x, inv_mass, springs, tau, sweeps=1, slack=0.0, weights="equal"):
"""Run Provot's correction over the springs. Return (new positions, sweeps run).
Each sweep visits the springs in the given order. With sweeps=None the
sweeps repeat until no spring is longer than (1 + tau) L, or until 10000
sweeps have run. A spring longer than its target (1 + tau)(1 - slack) L is
shortened to the target. slack = 0 is Provot's rule; a small slack > 0
makes the repeated sweeps stop after a finite number of sweeps whenever the
shortened limits can all hold at once (see the proof page).
"""
x = [tuple(p) for p in x]
limit = [(1.0 + tau) * s[2] for s in springs]
target = [(1.0 + tau) * (1.0 - slack) * s[2] for s in springs]
cap = 10000 if sweeps is None else sweeps
done = 0
while done < cap: # @line L1
if sweeps is None and all(math.dist(x[s[0]], x[s[1]]) <= lim for s, lim in zip(springs, limit)):
break
for s, t in zip(springs, target): # @line L2
correct_spring(x, inv_mass, s, t, weights)
done += 1
return x, done
def spring_forces(x, v, mass, springs, damping=0.0, gravity=GRAVITY):
"""Gravity plus damped Hooke forces along each spring."""
f = [[m * gravity[0], m * gravity[1]] for m in mass]
for a, b, rest, k in springs:
dx = x[b][0] - x[a][0]
dy = x[b][1] - x[a][1]
length = math.hypot(dx, dy)
ux, uy = dx / length, dy / length
rel = (v[b][0] - v[a][0]) * ux + (v[b][1] - v[a][1]) * uy
s = k * (length - rest) + damping * rel
f[a][0] += s * ux
f[a][1] += s * uy
f[b][0] -= s * ux
f[b][1] -= s * uy
return f
def step(x, v, mass, inv_mass, springs, dt, tau=0.1, sweeps=1, limited=None,
damping=0.0, gravity=GRAVITY, slack=0.0, weights="equal"):
"""One step: symplectic Euler, then strain limiting, then new velocities.
limited is the list of springs to correct (Provot used the structural
springs, then the structural and shear springs); the default is all springs.
The velocity is set to (x_new - x_old) / dt so that it matches the
corrected motion; this is a choice of this code.
"""
f = spring_forces(x, v, mass, springs, damping, gravity)
pred = []
for i in range(len(x)):
w = inv_mass[i]
vi = (v[i][0] + dt * w * f[i][0], v[i][1] + dt * w * f[i][1])
pred.append((x[i][0] + dt * vi[0], x[i][1] + dt * vi[1])) # @line L9
new_x, _ = limit_strain(pred, inv_mass, springs if limited is None else limited,
tau, sweeps, slack, weights) # @line L10
new_v = [((nx_ - ox) / dt, (ny_ - oy) / dt) for (nx_, ny_), (ox, oy) in zip(new_x, x)] # @line L11
return new_x, new_v
def grid(nx, ny, spacing, k_struct, k_shear=0.0):
"""A hanging grid: row j = 0 at the top, y = -j spacing. Springs (a, b, rest, k)."""
def idx(i, j):
return j * nx + i
x = [(i * spacing, -j * spacing) for j in range(ny) for i in range(nx)]
structural, shear = [], []
for j in range(ny):
for i in range(nx):
if i + 1 < nx:
structural.append((idx(i, j), idx(i + 1, j), spacing, k_struct))
if j + 1 < ny:
structural.append((idx(i, j), idx(i, j + 1), spacing, k_struct))
if k_shear > 0.0 and i + 1 < nx and j + 1 < ny:
d = spacing * math.sqrt(2.0)
shear.append((idx(i, j), idx(i + 1, j + 1), d, k_shear))
shear.append((idx(i + 1, j), idx(i, j + 1), d, k_shear))
return x, structural, shear
test_provot_strain_limiting.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/provot-strain-limiting/. The authors are listed in prov/SR6S3F.jsonl.
"""Tests of Provot's strain limiting: one correction, the projection property, sweeps and a hanging cloth."""
import math
import random
import provot_strain_limiting as p
def test_one_spring_both_free_and_one_fixed():
x = [(0.0, 0.0), (1.5, 0.0)]
s = (0, 1, 1.0, 1.0)
y, _ = p.limit_strain(x, [1.0, 1.0], [s], 0.1)
assert abs(math.dist(y[0], y[1]) - 1.1) < 1e-15
assert abs((y[0][0] + y[1][0]) / 2 - 0.75) < 1e-15 # the midpoint stays
y, _ = p.limit_strain(x, [0.0, 1.0], [s], 0.1)
assert y[0] == (0.0, 0.0) and abs(y[1][0] - 1.1) < 1e-15
y, _ = p.limit_strain(x, [0.0, 0.0], [s], 0.1)
assert y == x
# a short spring is not touched: the method limits stretch only
y, _ = p.limit_strain([(0.0, 0.0), (0.5, 0.0)], [1.0, 1.0], [s], 0.1)
assert y == [(0.0, 0.0), (0.5, 0.0)]
def test_correction_is_the_closest_point():
"""Against brute force: no random point of the allowed set is closer."""
rng = random.Random(3)
for weights, inv in (("equal", [1.0, 1.0]), ("mass", [2.0, 0.5]), ("equal", [0.0, 1.0])):
a = (rng.uniform(-1, 1), rng.uniform(-1, 1))
b = (a[0] + 2.0, a[1] + 0.7)
y, _ = p.limit_strain([a, b], inv, [(0, 1, 1.0, 1.0)], 0.1, weights=weights)
free = [i for i in range(2) if inv[i] > 0.0]
# the metric is sum |dx_i|^2 / w_i over the free particles (w = 1 for Provot's rule)
wt = [1.0 / inv[i] if weights == "mass" else 1.0 for i in range(2)]
def cost(q):
return sum(wt[i] * math.dist(q[i], [a, b][i]) ** 2 for i in free)
best = cost(y)
for _ in range(4000):
q = [a, b]
q = [(c[0] + rng.uniform(-1, 1), c[1] + rng.uniform(-1, 1)) if i in free else c for i, c in enumerate(q)]
if math.dist(q[0], q[1]) <= 1.1:
assert cost(q) >= best - 1e-12
def test_mass_weights_keep_the_centre_of_mass():
rng = random.Random(5)
x, st, sh = p.grid(6, 6, 0.1, 1.0, 1.0)
x = [(c[0] * rng.uniform(1.0, 1.6), c[1] * rng.uniform(1.0, 1.6)) for c in x]
mass = [rng.uniform(0.5, 2.0) for _ in x]
inv = [1.0 / m for m in mass]
y, _ = p.limit_strain(x, inv, st + sh, 0.1, sweeps=5, weights="mass")
for d in range(2):
before = sum(m * c[d] for m, c in zip(mass, x))
after = sum(m * c[d] for m, c in zip(mass, y))
assert abs(before - after) <= 1e-10 * sum(m * abs(c[d]) for m, c in zip(mass, x))
def test_one_sweep_is_not_enough():
# a - b - c with both springs too long: the second correction stretches the first spring again
x = [(0.0, 0.0), (1.5, 0.0), (3.5, 0.0)]
springs = [(0, 1, 1.0, 1.0), (1, 2, 1.0, 1.0)]
y, _ = p.limit_strain(x, [1.0, 1.0, 1.0], springs, 0.1, sweeps=1)
assert p.strain(y, springs[0]) > 0.1 + 1e-3
assert abs(p.strain(y, springs[1]) - 0.1) < 1e-12
y, n = p.limit_strain(x, [1.0, 1.0, 1.0], springs, 0.1, sweeps=None, slack=1e-3)
assert 1 < n < 10000 and p.max_strain(y, springs) <= 0.1
def test_repeated_sweeps_end_when_the_limits_can_hold():
"""Pins at rest positions: the rest shape satisfies every limit, so the sweeps stop."""
rng = random.Random(8)
x, st, sh = p.grid(8, 8, 0.1, 1.0, 1.0)
inv = [1.0] * len(x)
inv[0] = inv[7] = 0.0
y = [c if inv[i] == 0.0 else (c[0] + rng.uniform(-0.08, 0.08), c[1] + rng.uniform(-0.08, 0.08))
for i, c in enumerate(x)]
assert p.max_strain(y, st + sh) > 0.5
z, n = p.limit_strain(y, inv, st + sh, 0.1, sweeps=None, slack=1e-3)
assert n < 10000
for s in st + sh:
assert math.dist(z[s[0]], z[s[1]]) <= 1.1 * s[2]
assert z[0] == x[0] and z[7] == x[7]
def test_fixed_ends_forcing_a_stretch_do_not_converge():
"""Bridson et al. 2002, Section 4: fixed boundaries that force more than 10% cannot be met."""
n = 6
x = [(1.3 * i, 0.0) for i in range(n)]
inv = [1.0] * n
inv[0] = inv[-1] = 0.0
springs = [(i, i + 1, 1.0, 1.0) for i in range(n - 1)]
y, sweeps = p.limit_strain(x, inv, springs, 0.1, sweeps=None, slack=1e-3)
assert sweeps == 10000
# the springs sum to at least 6.5, so one of the five is at least 30% too long
assert p.max_strain(y, springs) >= 0.3 - 1e-12
def hanging(sweeps, limit, steps=1000):
x, st, sh = p.grid(9, 9, 0.1, 50.0, 50.0)
n = len(x)
mass = [0.01] * n
inv = [100.0] * n
inv[0] = inv[8] = 0.0 # hung by the two top corners
v = [(0.0, 0.0)] * n
worst = 0.0
for _ in range(steps):
x, v = p.step(x, v, mass, inv, st + sh, 0.002, tau=0.1, sweeps=sweeps,
limited=st if limit else [], damping=0.05, slack=1e-3 if sweeps is None else 0.0)
worst = max(worst, p.max_strain(x, st))
return worst
def test_hanging_cloth_super_elastic_and_limited():
soft = hanging(0, False)
one = hanging(1, True)
two = hanging(2, True)
full = hanging(None, True)
assert soft > 0.5 # the corner springs of the soft cloth stretch by more than 50%
assert full <= 0.1 # repeated sweeps: no structural spring is longer than 110%
assert 0.1 < two < one < 0.2 # one or two sweeps leave a small excess; two is better
History
Xavier Provot presented the method at Graphics Interface 1995, in a paper on a mass-spring model of cloth. He measured the super-elastic effect on a grid hung by two corners, related the stiffness to the time step, and proposed to correct the positions of the over-stretched springs after each step. He tested it with a 10% limit and found that running the correction twice gave better results. In 2002 Bridson, Fedkiw and Anderson pointed out that the method cannot converge when the boundaries force a stretch, and moved the limit to the velocities. The projection of positions onto constraints became the base of position-based dynamics.
References
- Xavier Provot, Deformation constraints in a mass-spring model to describe rigid cloth behavior, Graphics Interface 95, 147-154, 1995, Section 3 (the super-elastic effect), Section 4, equation (3) (the critical stiffness), Section 5 (the correction rules) and Section 6 (results with a 10% limit, one and two passes)
- Robert Bridson, Ronald Fedkiw and John Anderson, Robust treatment of collisions, contact and friction for cloth animation, ACM Transactions on Graphics 21(3), 594-603, 2002, Section 4 (strain limiting: the case where Provot's method does not converge, and a version on velocities with Jacobi iteration)
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 SR6S3F Edit this page History Report an error Markdown