Algorithmadvanced
Bridson-Fedkiw-Anderson cloth collision handling
Also called robust cloth collision handling.
Handle cloth contact with repulsion forces for proximity, continuous collision impulses for fast motion, and rigid impact zones as a final safeguard.
- Solves
- Cloth simulation
- Time
- O((1 + P + Z) (n t + e^2)) totalΘ(n t + e^2) passO(n (n t + e^2)) worst_case
- Space
- Θ(n t + e^2) pairs
- Where
- P = the number of impulse passes; Z = the number of impact zone passes; e = the number of edges; n = the number of nodes; t = the number of triangles
- Properties
- not angular momentum conservingcollision free resultdeterministicnot exactlinear momentum conservingorder dependent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert Bridson, Ronald Fedkiw, John Anderson, 2002
Cloth is thin, it folds onto itself, and it moves fast. A simulation that only checks for overlap at the end of a step lets cloth pass through cloth. Bridson, Fedkiw and Anderson (2002) gave a collision method for triangle cloth with three stages. Cheap repulsion impulses keep nearby pieces apart and add friction. Continuous collision tests then find every crossing on the straight paths of the step and stop it with an impulse. If crossings remain after a few passes, rigid impact zones remove them for certain. The result is a step with no intersection, whatever the internal cloth model did.
In plain words
Think of a shirt that is folding onto itself during one frame. The cloth solver has proposed where every point goes. This method checks that proposal before it is used.
First, points that are already very close get a small push apart, and sliding pieces rub with friction. This takes care of most contact.
Second, the method follows each point on a straight line through the frame and asks if a point passes through a triangle or an edge passes through an edge. Each such crossing gets a push that stops the approach. A push can cause a new crossing, so this is repeated a few times.
Third, if crossings still remain, the points of each crossing are glued together and move as one solid piece for this frame. A solid piece cannot pass through itself, so this always ends with no crossing.
The problem
Given a triangle mesh with node positions that have no intersection, masses , and candidate mean velocities from the cloth solver for a step of length , find new mean velocities such that the straight paths , , have no contact. A contact is a node on a triangle that does not contain it, or two edges with no common node that touch. The step then ends at , and the solver turns the mean velocity into the end velocity (Section 7.6 of the paper, not part of this page). The cloth also has a thickness : pairs closer than at the start get repulsions.
The algorithm
Each pair has four nodes and four weights that sum to : for a node and a triangle with barycentric weights , and for two edges with closest points at the fractions and . The relative velocity is . To change it by , node gets with , and the effective mass is .
ROBUST-CLOTH-COLLISIONS(x, v, m, mesh, dt, h, k, mu, P)- 1
for each point-triangle and edge-edge pair closer than h at x: ▷ repulsions - 2
n, c, d <- unit normal, node weights, overlap h - distance ; vN <- (sum c_j v_j) . n - 3
if vN < 0: apply the inelastic impulse that sets vN to 0 - 4
if vN < 0.1 d / dt: raise vN by min(dt k d / m_eff, 0.1 d / dt - vN) ▷ spring - 5
lower the tangential relative speed by min(mu dvN, |vT|) ▷ friction - 6
repeat at most P times: ▷ collisions - 7
C <- pairs that meet on the paths x + t v, t in [0, dt] ▷ cubic, proximity - 8
if C is empty: return v - 9
for each (pair, t) in C: if vN < 0 for the normal at time t: set vN to 0 - 10
loop: ▷ failsafe - 11
C <- pairs with nodes in two or more zones that meet on the paths - 12
if C is empty: return v - 13
merge the four nodes of each pair of C into one zone ; move each changed zone rigidly
Repulsions (L1 to L5). Section 7.2 of the paper. A pair that approaches gets a fully inelastic impulse, because cloth contact loses most of its energy. A spring of stiffness acts on the overlap $d = h - $ distance, but it may only raise the normal velocity to , so that it never pushes a pair out of the overlap in one step. Bridson et al. match to the stretch stiffness of the cloth (a heuristic). Friction follows Coulomb's law (Section 7.3): the normal impulse allows a tangential change of at most , and the tangential speed never changes sign.
Continuous detection (L7, L11). Section 6. Four moving points meet only when they are coplanar, so the code solves the cubic . The cubic is monotone between its critical points, so each root comes from bisection on a sign change, and the critical points are kept as times too. At each time in increasing order the code tests proximity with the tolerance m of the paper, by barycentric weights for a node and a triangle and by the closest points for two edges. See elementary CCD tests.
Collision impulses (L9). Section 7.4. Each collision gets an inelastic impulse with the normal of the collision time. The impulse changes the velocity for the whole step, so the pair then keeps about its start distance.
Failsafe (L10 to L13). Section 7.5 and the page impact zones. The zone keeps its linear and angular momentum, , and its end positions are the start positions rotated by about and moved by .
Choices of this code. The impulses act one pair at a time; the paper also allows a parallel update with a relaxation of . The spring cap is written for the relative velocity with the effective mass, which for equal masses is the weighting of Section 7.1. The code tests all pairs after a box test, not a bounding volume hierarchy, and it has no proximity test at the end of the step and no adaptive step. In the failsafe it skips pairs with all four nodes in one zone, because a rigid zone has no internal contact. If a zone would turn by or more, or its inertia tensor is singular, it only translates. If a cubic is zero for all , the code tests 65 evenly spaced times.
Example
A node falls on a triangle, by hand. The triangle has the corners , and at rest, and a node at falls with m/s, with s, all masses kg and m. The node is m away, so L1 finds no close pair. The cubic gives the coplanar time s, where the node is at the barycentric weights , inside the triangle. The weights of the pair are , so . The normal relative velocity is m/s, and L9 changes it by : the node gets m/s and its velocity becomes m/s; the corners get , and m/s. The momentum is kg m/s, as before, and the relative normal velocity is . The second pass of L7 finds no collision. For equal masses this is the impulse of Section 7.1 with .
A sheet falls through a sheet, measured. Two sheets of nodes and 32 triangles each, m apart in the grid and m apart in height, have 3008 point-triangle pairs and 5786 edge-edge pairs. The lower sheet is at rest. The nodes of the upper sheet fall with speeds from about to m/s, so without handling the upper sheet ends half through the lower one with s (the exact test finds an intersection). With m, N/m, and masses of kg, the first pass of L7 finds 75 collisions, and after their impulses the second pass finds none. The mean vertical velocity is then m/s for the lower sheet and m/s for the upper sheet. With the failsafe alone does the work: one pass makes one zone of 38 nodes, which moves as one rigid body for the step.
Close sheets, measured. Two sheets of nodes m apart, with m and s, have 66 close pairs at the start. After the repulsions the slowest node of the upper sheet falls with m/s instead of m/s, and the first pass of L7 finds no collision.
Self-collision, measured. One sheet of nodes with random velocities up to m/s and : with the seed 11 the impulses meet 19 collisions and one failsafe pass makes two zones of 4 nodes; with the seed 12 they meet 11 collisions and two failsafe passes make one zone of 8 nodes.
Correctness
The claims are proved in proofs/correctness.md.
- Momentum (proved). Every impulse changes the relative velocity of its pair by exactly the asked amount and keeps the linear momentum, because the weights sum to zero. For equal masses it is the weighting of Section 7.1. The rigid zones keep the momentum too.
- One repulsion (proved). For one pair alone, after L3 and L4 the normal relative velocity is at least and the spring part raises it to at most . Friction never reverses the sliding direction. With many pairs, later impulses can change earlier ones.
- Detection (proved). A contact makes the four nodes coplanar, so its time is a root of the cubic, and the list of times holds every root of the cubic in when the cubic is not zero.
- Termination and result (proved). The failsafe merges at least two zones in each pass that finds a collision, so it ends after at most such passes. A rigid zone has no internal contact when it turns by less than . So the paths have no contact, and the end state has no intersection when the start state has none.
- Plausibility (heuristic, not claimed). The stiffness , the cap , the relaxation and the number of passes are tuning choices. The page does not claim that the result is the motion of real cloth.
The tests check the cubic against the volume, the collision time against fine sampling of the volume with bisection, the closest points of two edges against an enumeration of all cases, the barycentric weights against area ratios, the impulse weights and momentum, the spring and friction formulas, and the rigid motion of a zone against a rotation matrix. On the sheet scenes they check the paths with the collision test, the end state with an exact test in rational arithmetic, the momentum to and the rigidity of each zone.
Proof: The impulses keep the momentum, the cubic finds every contact time, and the impact zones end with no collisionfull
We use the notation of the page. Node has mass , start position and mean velocity for a step of length , and moves on , . A pair is a node and a triangle that does not contain it, or two edges with no common node. A contact of a pair at time is a common point of its two parts at that time. All statements are in exact arithmetic, except where the last section says otherwise.
A pair has four nodes and weights with : for a node and a triangle with barycentric weights , and for two edges with closest points at and . The relative position is and the relative velocity is .
Impulses
Lemma 1. Let . The update changes the relative velocity by exactly and does not change the linear momentum . For equal masses , a point-triangle pair and , the point gets and triangle node gets with and , which is the weighting of Bridson, Fedkiw and Anderson (2002, Section 7.1).
Proof. The relative velocity changes by . The momentum changes by . For equal masses , and the point gets ; triangle node gets times this.
Every change of velocity in the method (lines L3, L4, L5, L9) is an update of Lemma 1, and the rigid motion of a zone keeps the momentum of the zone (Lemma 4). So the method keeps the linear momentum exactly.
Lemma 2. Take one close pair in isolation, with unit normal , overlap and normal relative velocity . After lines L3 and L4 the normal relative velocity is
with . So , and the spring part never makes larger than . Line L5 lowers the tangential relative speed by with , keeps its direction, and does not change .
Proof. By Lemma 1, L3 sets to when it is negative, and L4 adds when this is positive; the three cases follow. The friction update of L5 is , which is orthogonal to , so by Lemma 1 it only changes the tangential part, by that amount.
The lemma holds for one pair. The code treats the pairs one after the other, so a later pair can change the velocity of an earlier pair again. The page does not claim more for many pairs; the later stages do not depend on it.
Continuous detection
Lemma 3. If a pair has a contact at time , then is a root of the cubic , and, if is not the zero polynomial, the list of candidate times holds or, for a root of odd multiplicity inside a monotone piece, the limit of a bisection that brackets .
Proof. At a contact the four nodes lie in one plane, so the volume is . The coefficients of coplanarity_cubic are those of the product of the three linear vector polynomials (the test compares with the volume at four times). Between two consecutive points of and the roots of in , is monotone, so it has at most one root there or is constant. A root at a knot is kept by the test . A root inside a piece where changes sign is bracketed, and the bisection keeps the bracket. A root inside a piece where does not change sign would be a local extremum of inside the piece, which is a root of , so it is a knot.
The code then tests proximity at the candidates in increasing order with the tolerance (Section 6 of the paper), so the first candidate that passes is the first contact up to the length of the bracket. The test compares this time with fine sampling of the sign of the volume, bisection and the same proximity test.
Rigid impact zones in 3D
For a zone , let and be the mass-weighted means, , , and . With and the rotation by about , Section 7.5 of the paper sets the end position , which is the formula with and . The code uses if or is singular.
Lemma 4. (a) If and is invertible, then . (b) . (c) . (d) If , the nodes of the zone have no contact among themselves at any when they have none at .
Proof. (a) , and , so . (b) , so . (c) is direct. (d) The nodes move on with , one affine map for all nodes. is orthogonal, so it is normal with eigenvalues and , and is normal with eigenvalues and . These are only if and , which for has no solution. So is invertible. An invertible affine map keeps points, segments and triangles and the incidence between them, so a contact at time would give a contact at time .
Termination and the result
Theorem 5. Let the start state have no contact, and let no pair have the zero cubic. The method ends. The failsafe makes at most passes that find collisions, and at the end no pair has a contact on the paths.
Proof. Stage 1 visits each pair once, and stage 2 makes at most passes. In stage 3, every collision that the code finds has nodes in at least two zones, because pairs with all four nodes in one zone are skipped. Line L13 merges these zones, so each pass with a collision lowers the number of zones by at least one. There are at most zones, so there are at most such passes, and the loop stops at the first pass that finds no collision. At that pass, Lemma 3 says that no pair with nodes in two zones has a contact. A pair in one zone is rigid if the zone has more than one node, and by Lemma 4 (d) it has no contact either.
Corollary 6. The end state has no edge that meets a triangle with no common node. Whether a segment meets a triangle can change during the step only at a time when an endpoint of the segment lies on the triangle or the segment touches an edge of the triangle. Both are contacts of pairs, and the start state has no intersection, so the end state has none. The tests check this with an exact test in rational arithmetic.
What is not claimed
- Plausible motion. The page does not claim that the result is the motion of real cloth. The stiffness matched to the stretch springs, the cap and the number of passes are heuristics of Bridson et al. or choices of this code. The impact zones remove all relative motion inside a zone and keep the angular momentum only to , as in the 2D case.
- The zero cubic. If the four nodes of a pair stay in one plane for the whole step, Lemma 3 gives no times, and the code tests 65 evenly spaced times. A short contact between them can be missed.
- Rounding. Lemma 3 and Lemma 4 hold in exact arithmetic. In floating point the code accepts a contact within at a coplanar time, and the thickness of the repulsions keeps most pairs far from this limit. The tests check the result with exact arithmetic, not the proof.
- Order. Stages 1 and 2 apply impulses one pair at a time, so their result depends on the order of the pairs. Only stage 3 does not.
Complexity
Let be the number of nodes, the number of triangles and the number of edges. This code tests all pairs in each pass, and each test costs : a box test, a cubic, at most a fixed number of bisection steps and a few proximity tests. There is one repulsion pass, at most collision passes and failsafe passes, so the total is , and the worst case is . Bridson et al. use a hierarchy of bounding boxes instead, so that a pass costs about the number of nearby pairs. They report that the repulsions catch almost all collisions, so few collision passes are needed and the zones stay small and rare; this is an observation of the paper, not a bound.
Properties
- No intersection at the end. In exact arithmetic and when no cubic is zero, the step ends with no intersection.
- Momentum. The linear momentum is kept exactly. The angular momentum is not kept by the failsafe.
- Order dependent. The repulsions and collision impulses act one pair at a time, so the result depends on the order of the pairs.
- Inelastic. Contacts lose their normal approach speed, as the paper intends for cloth.
- Independent of the cloth model. The method only changes the mean velocities, so it can follow any internal solver, such as Baraff-Witkin cloth.
Variants and improvements
- Parallel update. All impulses of a pass are computed from the same velocities and added with a relaxation such as (Section 7.2 and 7.4).
- Inelastic projection. Harmon, Vouga, Tamstorf and Grinspun (2008) replace the rigid zones by a failsafe that cancels the approach but keeps sliding, so much less motion is lost.
- Barrier methods. Incremental potential contact keeps the cloth apart with a barrier energy inside the solver and needs no failsafe.
- Exact root tests. The floating-point cubic can give false negatives near degenerate cases. Later work, listed on elementary CCD tests, gives exact or conservative tests.
When to use it
Use it after any cloth solver that must never let cloth pass through cloth or through itself, for example in garments with many folds. It adds friction and thickness at the same time, which matters for folds and wrinkles.
Do not expect it to fix a start state that already intersects. If sliding contact must look smooth, prefer an inelastic projection or a barrier method to the rigid zones.
Pitfalls
- Coplanar motion. If four nodes stay in one plane, for example two pieces of a flat sheet that slide in their plane, the cubic is zero and gives no time. This code then tests 65 times, which can miss a short contact.
- Rounding. A floating-point cubic can miss a root near a double root. The tolerance m and the thickness make this rare, not impossible.
- Too many collision passes. Impulses can create new collisions without end. Limit the passes and leave the rest to the failsafe.
- Unequal masses. The weights of Section 7.1 assume equal masses. With other masses, use the effective mass so that the momentum stays exact.
- Sticky clumps. Large zones freeze the cloth for the step. If zones are large and frequent, the repulsions are too weak or the step is too long.
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
robust_cloth_collision.py 513 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-cloth-collision/. The authors are listed in prov/QXMR1R.jsonl.
"""Collision handling for triangle cloth after Bridson, Fedkiw and Anderson (2002), in 3D.
The cloth is a triangle mesh with node positions x (the start of the step),
masses m and candidate mean velocities v for a step of length dt, so that
without contact the step would end at x + dt v. The function
handle_collisions returns new mean velocities with three stages (Section 5 of
the paper):
1. Repulsions (Section 7.2, 7.3). For each point-triangle and edge-edge pair
closer than the thickness h at the start, an inelastic impulse stops the
approach, a spring impulse pushes the pair apart, and Coulomb friction
slows the sliding.
2. Collisions (Section 6, 7.4). A pair collides if its four nodes become
coplanar on the straight paths (a cubic in t) and are within a rounding
tolerance at that time. Each collision gets an inelastic impulse with the
normal of that time. This is repeated a few times.
3. Failsafe (Section 7.5). The nodes of the collisions that remain are merged
into rigid impact zones until no collision remains.
A contact is (nodes, coeffs, normal): four node indices and four weights with
sum 0, so that the relative position is sum c_j x_j and the relative velocity
is sum c_j v_j. A point-triangle pair (p; a, b, c) has the weights
(1, -w1, -w2, -w3) and an edge-edge pair (a, b; c, d) has the weights
(1 - s, s, -(1 - t), -t). An impulse j n on the contact changes v_j by
c_j j n / m_j, which keeps the momentum because the weights sum to 0.
Choices of this code (not fixed by the paper):
- The impulses are applied one pair at a time (Gauss-Seidel), not in parallel.
- The impulse that changes the relative velocity by dv uses the effective
mass 1 / sum(c_j^2 / m_j). For equal masses this is the weighting of
Section 7.1. The spring impulse is capped so that the relative normal
velocity is at most 0.1 d / dt, the aim stated in Section 7.2.
- All pairs are tested, with a box test first, instead of a bounding volume
hierarchy. There is no proximity test at the end of the step and no
adaptive time step.
- If the cubic is zero for all t (the four nodes stay in one plane), the code
tests 65 evenly spaced times. This can miss a short contact.
- In the failsafe a pair whose four nodes are in one zone is not tested,
because a rigid zone has no internal contact (the proof).
"""
import math
from anim import add, cross, dot, norm, scale, solve, sub
ROUNDING_TOL = 1e-6 # the distance tolerance at a coplanar time (Section 6, 1e-6 m)
SPRING_FRACTION = 0.1 # the overlap may shrink by at most this fraction per step (Section 7.2)
COPLANAR_SAMPLES = 64 # tuning constant of this code for the degenerate cubic
# ---------------------------------------------------------------- mesh
def mesh_edges(triangles):
"""The sorted list of the edges (i, j), i < j, of a triangle list."""
out = set()
for a, b, c in triangles:
for i, j in ((a, b), (b, c), (c, a)):
out.add((min(i, j), max(i, j)))
return sorted(out)
def pairs(n, triangles, edges):
"""All point-triangle pairs (p, tri) with p not in tri and edge-edge pairs with no shared node."""
pt = [(p, t) for t in triangles for p in range(n) if p not in t]
ee = [(e, f) for k, e in enumerate(edges) for f in edges[k + 1:] if len({e[0], e[1], f[0], f[1]}) == 4]
return pt, ee
# ---------------------------------------------------------------- proximity (Section 6)
def point_triangle_proximity(x4, x1, x2, x3, tol):
"""Return (w1, w2, w3, normal, distance) if the point x4 is within tol of the triangle, else None.
The normal points from the plane of the triangle to the point. The weights
come from the normal equations and must lie in [-delta, 1 + delta], with
delta = tol divided by a length of the triangle.
"""
n = cross(sub(x2, x1), sub(x3, x1))
nn = norm(n)
if nn == 0.0:
return None
n = scale(n, 1.0 / nn)
dist = dot(sub(x4, x1), n)
if abs(dist) >= tol:
return None
x13, x23, x43 = sub(x1, x3), sub(x2, x3), sub(x4, x3)
a11, a12, a22 = dot(x13, x13), dot(x13, x23), dot(x23, x23)
det = a11 * a22 - a12 * a12
if det <= 0.0:
return None
b1, b2 = dot(x13, x43), dot(x23, x43)
w1 = (a22 * b1 - a12 * b2) / det
w2 = (a11 * b2 - a12 * b1) / det
w3 = 1.0 - w1 - w2
delta = tol / math.sqrt(nn)
if min(w1, w2, w3) < -delta or max(w1, w2, w3) > 1.0 + delta:
return None
if dist < 0.0:
n, dist = scale(n, -1.0), -dist
return w1, w2, w3, n, dist
def segment_closest(p1, q1, p2, q2):
"""Parameters (s, t) in [0, 1] of the closest points p1 + s (q1 - p1) and p2 + t (q2 - p2)."""
d1, d2, r = sub(q1, p1), sub(q2, p2), sub(p1, p2)
a, e, f = dot(d1, d1), dot(d2, d2), dot(d2, r)
def clamp(z):
return 0.0 if z < 0.0 else 1.0 if z > 1.0 else z
if a == 0.0 and e == 0.0:
return 0.0, 0.0
if a == 0.0:
return 0.0, clamp(f / e)
c = dot(d1, r)
if e == 0.0:
return clamp(-c / a), 0.0
b = dot(d1, d2)
denom = a * e - b * b
s = clamp((b * f - c * e) / denom) if denom > 1e-14 * a * e else 0.0 # parallel: any s
t = (b * s + f) / e
if t < 0.0:
t, s = 0.0, clamp(-c / a)
elif t > 1.0:
t, s = 1.0, clamp((b - c) / a)
return s, t
def edge_edge_proximity(x1, x2, x3, x4, tol):
"""Return (s, t, normal, distance) if the segments x1x2 and x3x4 are within tol, else None.
The normal points from the closest point of the second edge to that of the
first. If the segments touch, it is the normal of the two edges.
"""
s, t = segment_closest(x1, x2, x3, x4)
pa = add(x1, scale(sub(x2, x1), s))
pb = add(x3, scale(sub(x4, x3), t))
d = sub(pa, pb)
dist = norm(d)
if dist >= tol:
return None
if dist > 1e-300:
return s, t, scale(d, 1.0 / dist), dist
c = cross(sub(x2, x1), sub(x4, x3))
if norm(c) == 0.0:
return None
return s, t, scale(c, 1.0 / norm(c)), dist
def proximity(x, kind, pair, tol):
"""A contact (nodes, coeffs, normal, distance) for a pair within tol at positions x, or None."""
if kind == "pt":
p, (a, b, c) = pair
r = point_triangle_proximity(x[p], x[a], x[b], x[c], tol)
if r is None:
return None
w1, w2, w3, n, dist = r
return (p, a, b, c), (1.0, -w1, -w2, -w3), n, dist
(a, b), (c, d) = pair
r = edge_edge_proximity(x[a], x[b], x[c], x[d], tol)
if r is None:
return None
s, t, n, dist = r
return (a, b, c, d), (1.0 - s, s, -(1.0 - t), -t), n, dist
# ---------------------------------------------------------------- continuous collision detection (Section 6)
def coplanarity_cubic(p, u):
"""Coefficients (k3, k2, k1, k0) of f(s) = (x21 x x31) . x41 on x_j(s) = p_j + s u_j."""
a, b, c = sub(p[1], p[0]), sub(p[2], p[0]), sub(p[3], p[0])
da, db, dc = sub(u[1], u[0]), sub(u[2], u[0]), sub(u[3], u[0])
ab = cross(a, b)
ab1 = add(cross(a, db), cross(da, b))
ab2 = cross(da, db)
return (dot(ab2, dc), dot(ab1, dc) + dot(ab2, c), dot(ab, dc) + dot(ab1, c), dot(ab, c))
def _poly(k, s):
return ((k[0] * s + k[1]) * s + k[2]) * s + k[3]
def _quadratic_roots(a, b, c):
if a == 0.0:
return [] if b == 0.0 else [-c / b]
disc = b * b - 4.0 * a * c
if disc < 0.0:
return []
q = -0.5 * (b + math.copysign(math.sqrt(disc), b))
out = [q / a]
if q != 0.0:
out.append(c / q)
return out
def candidate_times(k):
"""Sorted times in [0, 1] to test: the roots of the cubic k and its critical points.
The cubic is monotone between its critical points, so each root is found
by bisection on a sign change. The critical points are kept too, so that a
root of even multiplicity (a graze) is tested. If k is zero, the code
returns evenly spaced times.
"""
if k == (0.0, 0.0, 0.0, 0.0):
return [i / COPLANAR_SAMPLES for i in range(COPLANAR_SAMPLES + 1)]
crit = sorted(s for s in _quadratic_roots(3.0 * k[0], 2.0 * k[1], k[2]) if 0.0 < s < 1.0)
knots = [0.0] + crit + [1.0]
out = list(crit)
for lo, hi in zip(knots, knots[1:]):
flo, fhi = _poly(k, lo), _poly(k, hi)
if flo == 0.0:
out.append(lo)
if fhi == 0.0:
out.append(hi)
if (flo < 0.0) != (fhi < 0.0) and flo != 0.0 and fhi != 0.0:
for _ in range(200):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
fm = _poly(k, mid)
if fm == 0.0:
lo = hi = mid
break
if (fm < 0.0) == (flo < 0.0):
lo = mid
else:
hi = mid
out.append(hi)
return sorted(set(out))
def pair_nodes(kind, pair):
if kind == "pt":
p, (a, b, c) = pair
return (a, b, c, p) # triangle first, as in f(s)
(a, b), (c, d) = pair
return (a, b, c, d)
def collision_time(x0, x1, kind, pair, tol=ROUNDING_TOL):
"""The first s in [0, 1] at which the pair is within tol on the straight paths x0 -> x1, or None."""
nodes = pair_nodes(kind, pair)
p = [x0[i] for i in nodes]
u = [sub(x1[i], x0[i]) for i in nodes]
for s in candidate_times(coplanarity_cubic(p, u)):
xs = {i: add(x0[i], scale(sub(x1[i], x0[i]), s)) for i in nodes}
if proximity(xs, kind, pair, tol) is not None:
return s
return None
def _box(points, pad):
lo = tuple(min(q[k] for q in points) - pad for k in range(3))
hi = tuple(max(q[k] for q in points) + pad for k in range(3))
return lo, hi
def _overlap(b1, b2):
return all(b1[0][k] <= b2[1][k] and b2[0][k] <= b1[1][k] for k in range(3))
def all_collisions(x0, x1, pt, ee, skip=None):
"""All (kind, pair, s) that collide on the straight paths x0 -> x1, by box tests then the cubic."""
out = []
vbox = [_box((x0[i], x1[i]), ROUNDING_TOL) for i in range(len(x0))]
cache = {}
def box_of(nodes):
if nodes not in cache:
cache[nodes] = (tuple(min(vbox[i][0][k] for i in nodes) for k in range(3)),
tuple(max(vbox[i][1][k] for i in nodes) for k in range(3)))
return cache[nodes]
for kind, plist in (("pt", pt), ("ee", ee)):
for pair in plist:
if kind == "pt":
first, second = (pair[0],), pair[1]
else:
first, second = pair
if not _overlap(box_of(first), box_of(second)):
continue
if skip is not None and skip(pair_nodes(kind, pair)):
continue
s = collision_time(x0, x1, kind, pair)
if s is not None:
out.append((kind, pair, s))
return out
# ---------------------------------------------------------------- impulses (Section 7.1 to 7.4)
def relative_velocity(v, nodes, coeffs):
out = (0.0, 0.0, 0.0)
for i, c in zip(nodes, coeffs):
out = add(out, scale(v[i], c))
return out
def apply_impulse(v, mass, nodes, coeffs, dv):
"""Change the relative velocity sum c_j v_j by the vector dv. Change v in place.
The impulse j = dv / sum(c_j^2 / m_j) acts on node j as c_j j, so the
momentum change is j sum c_j = 0.
"""
w = sum(c * c / mass[i] for i, c in zip(nodes, coeffs))
for i, c in zip(nodes, coeffs):
v[i] = add(v[i], scale(dv, c / (mass[i] * w)))
def repulsion(v, mass, contact, h, dt, k, mu):
"""Inelastic, spring and friction impulses of one close pair (Section 7.2, 7.3).
Return the change of the relative normal velocity.
"""
nodes, coeffs, n, dist = contact
d = h - dist # @line L2
vn = dot(relative_velocity(v, nodes, coeffs), n)
vn0 = vn
if vn < 0.0:
apply_impulse(v, mass, nodes, coeffs, scale(n, -vn)) # @line L3
vn = 0.0
target = SPRING_FRACTION * d / dt
if vn < target:
m_eff = 1.0 / sum(c * c / mass[i] for i, c in zip(nodes, coeffs))
apply_impulse(v, mass, nodes, coeffs, scale(n, min(dt * k * d / m_eff, target - vn))) # @line L4
dvn = dot(relative_velocity(v, nodes, coeffs), n) - vn0
if mu > 0.0:
vr = relative_velocity(v, nodes, coeffs)
vt = sub(vr, scale(n, dot(vr, n)))
nt = norm(vt)
if nt > 0.0:
cut = min(mu * dvn, nt)
apply_impulse(v, mass, nodes, coeffs, scale(vt, -cut / nt)) # @line L5
return dvn
def collision_contact(x0, x1, kind, pair, s):
"""The contact of a collision at time s, with the normal of that time.
The normal is oriented so that the relative position at the start of the
step has a positive normal component.
"""
nodes = pair_nodes(kind, pair)
xs = {i: add(x0[i], scale(sub(x1[i], x0[i]), s)) for i in nodes}
con = proximity(xs, kind, pair, ROUNDING_TOL)
nodes, coeffs, n, _ = con
if kind == "pt":
a, b, c = pair[1]
tn = cross(sub(xs[b], xs[a]), sub(xs[c], xs[a]))
else:
(a, b), (c, d) = pair
tn = cross(sub(xs[b], xs[a]), sub(xs[d], xs[c]))
if norm(tn) > 0.0:
n = scale(tn, 1.0 / norm(tn))
if dot(relative_velocity(x0, nodes, coeffs), n) < 0.0:
n = scale(n, -1.0)
return nodes, coeffs, n
# ---------------------------------------------------------------- rigid impact zones (Section 7.5)
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, i):
while self.parent[i] != i:
self.parent[i] = self.parent[self.parent[i]] # path halving
i = self.parent[i]
return i
def union(self, i, j):
i, j = self.find(i), self.find(j)
if i == j:
return i
if self.size[i] < self.size[j]:
i, j = j, i
self.parent[j] = i
self.size[i] += self.size[j]
return i
def groups(self):
out = {}
for i in range(len(self.parent)):
out.setdefault(self.find(i), []).append(i)
return out
def rigid_zone_motion(x0, v, mass, nodes, dt):
"""Mean velocities {i: v_i} of the rigid motion of a zone (the formula of Section 7.5).
omega = I^-1 L keeps the angular momentum. The end position is
x_cm + dt v_cm + x_F + cos(dt |omega|) x_R + sin(dt |omega|) (omega_hat x x_R).
If the inertia tensor is singular (collinear nodes) or dt |omega| >= pi,
the zone only translates.
"""
m = sum(mass[i] for i in nodes)
xcm, vcm = (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)
for i in nodes:
xcm = add(xcm, scale(x0[i], mass[i] / m))
vcm = add(vcm, scale(v[i], mass[i] / m))
ang = (0.0, 0.0, 0.0)
inertia = [[0.0] * 3 for _ in range(3)]
for i in nodes:
r = sub(x0[i], xcm)
ang = add(ang, scale(cross(r, sub(v[i], vcm)), mass[i]))
rr = dot(r, r)
for a in range(3):
for b in range(3):
inertia[a][b] += mass[i] * ((rr if a == b else 0.0) - r[a] * r[b])
tr = inertia[0][0] + inertia[1][1] + inertia[2][2]
omega = (0.0, 0.0, 0.0)
if tr > 0.0:
try:
omega = tuple(solve(inertia, ang))
except ValueError:
omega = (0.0, 0.0, 0.0)
if not all(math.isfinite(w) for w in omega) or abs(_det3(inertia)) <= 1e-12 * tr ** 3:
omega = (0.0, 0.0, 0.0)
wn = norm(omega)
theta = dt * wn
if theta >= math.pi:
theta = 0.0
out = {}
for i in nodes:
r = sub(x0[i], xcm)
if theta > 0.0:
axis = scale(omega, 1.0 / wn)
xf = scale(axis, dot(r, axis))
xr = sub(r, xf)
r = add(add(xf, scale(xr, math.cos(theta))), scale(cross(axis, xr), math.sin(theta)))
end = add(add(xcm, scale(vcm, dt)), r)
out[i] = scale(sub(end, x0[i]), 1.0 / dt)
return out
def _det3(a):
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]))
# ---------------------------------------------------------------- the pipeline (Section 5)
def end_positions(x0, v, dt):
return [add(p, scale(w, dt)) for p, w in zip(x0, v)]
def handle_collisions(x0, v, mass, triangles, dt, h, k, mu=0.0, collision_passes=5, record=None):
"""New mean velocities for the step x0 -> x0 + dt v with no cloth collision.
x0 must be free of intersections. h is the cloth thickness, k the
repulsion stiffness (Bridson et al. match it to the stretch stiffness), mu
the friction coefficient and collision_passes the number of impulse passes
before the failsafe. If record is a dict, it gets the counts of each stage.
Return (v, zones), where zones lists the impact zones with more than one node.
"""
n = len(x0)
v = [tuple(w) for w in v]
edges = mesh_edges(triangles)
pt, ee = pairs(n, triangles, edges)
info = {"proximities": 0, "collisions": [], "zone_passes": 0}
# stage 1: repulsions at the start positions
for kind, plist in (("pt", pt), ("ee", ee)): # @line L1
for pair in plist:
con = proximity(x0, kind, pair, h)
if con is not None:
info["proximities"] += 1
repulsion(v, mass, con, h, dt, k, mu)
# stage 2: iterated collision impulses
for _ in range(collision_passes): # @line L6
x1 = end_positions(x0, v, dt)
found = all_collisions(x0, x1, pt, ee) # @line L7
info["collisions"].append(len(found))
if not found:
break # @line L8
for kind, pair, s in found:
nodes, coeffs, nrm = collision_contact(x0, x1, kind, pair, s)
vn = dot(relative_velocity(v, nodes, coeffs), nrm)
if vn < 0.0:
apply_impulse(v, mass, nodes, coeffs, scale(nrm, -vn)) # @line L9
# stage 3: rigid impact zones
zones = DisjointSet(n)
while True: # @line L10
x1 = end_positions(x0, v, dt)
found = all_collisions(x0, x1, pt, ee,
skip=lambda nd: len({zones.find(i) for i in nd}) == 1) # @line L11
if not found:
break # @line L12
if info["zone_passes"] >= n:
raise RuntimeError("impact zones did not resolve the collisions")
info["zone_passes"] += 1
touched = set()
for kind, pair, _ in found:
a, b, c, d = pair_nodes(kind, pair)
touched.add(zones.union(zones.union(a, b), zones.union(c, d))) # @line L13
groups = zones.groups()
for root in {zones.find(r) for r in touched}:
for i, w in rigid_zone_motion(x0, v, mass, groups[root], dt).items():
v[i] = w
if record is not None:
record.update(info)
return v, [g for g in zones.groups().values() if len(g) > 1]
test_robust_cloth_collision.py 381 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-cloth-collision/. The authors are listed in prov/QXMR1R.jsonl.
"""Tests of the cloth collision pipeline against sampling, brute force and exact rational tests."""
import math
import random
from fractions import Fraction
from anim import add, cross, dot, mul, norm, q_from_axis_angle, q_to_mat3, scale, sub, transpose
import robust_cloth_collision as rc
# ---------------------------------------------------------------- exact intersection test
def orient(a, b, c, d):
u, v, w = sub(b, a), sub(c, a), sub(d, a)
return dot(cross(u, v), w)
def orient2(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def segments_meet2(p, q, r, s):
d1, d2, d3, d4 = orient2(r, s, p), orient2(r, s, q), orient2(p, q, r), orient2(p, q, s)
if d1 * d2 < 0 and d3 * d4 < 0:
return True
def on(a, b, c):
return orient2(a, b, c) == 0 and min(a[0], b[0]) <= c[0] <= max(a[0], b[0]) \
and min(a[1], b[1]) <= c[1] <= max(a[1], b[1])
return on(r, s, p) or on(r, s, q) or on(p, q, r) or on(p, q, s)
def in_triangle2(p, a, b, c):
s1, s2, s3 = orient2(a, b, p), orient2(b, c, p), orient2(c, a, p)
return (s1 >= 0 and s2 >= 0 and s3 >= 0) or (s1 <= 0 and s2 <= 0 and s3 <= 0)
def segment_meets_triangle(p, q, a, b, c):
"""Exact test with Fractions: does the closed segment pq meet the closed triangle abc?"""
p, q, a, b, c = ([Fraction(z) for z in pt] for pt in (p, q, a, b, c))
o1, o2 = orient(a, b, c, p), orient(a, b, c, q)
if o1 == 0 and o2 == 0:
n = cross(sub(b, a), sub(c, a))
drop = max(range(3), key=lambda k: abs(n[k]))
p, q, a, b, c = ([z for k, z in enumerate(pt) if k != drop] for pt in (p, q, a, b, c))
return in_triangle2(p, a, b, c) or in_triangle2(q, a, b, c) or any(
segments_meet2(p, q, u, w) for u, w in ((a, b), (b, c), (c, a)))
if (o1 > 0 and o2 > 0) or (o1 < 0 and o2 < 0):
return False
s1, s2, s3 = orient(p, q, a, b), orient(p, q, b, c), orient(p, q, c, a)
return (s1 >= 0 and s2 >= 0 and s3 >= 0) or (s1 <= 0 and s2 <= 0 and s3 <= 0)
def boxes_meet(p, q):
"""Float comparisons are exact, so disjoint boxes prove that the parts do not meet."""
return all(min(a[k] for a in p) <= max(b[k] for b in q) and min(b[k] for b in q) <= max(a[k] for a in p)
for k in range(3))
def exact_intersection_free(x, triangles):
for e in rc.mesh_edges(triangles):
for t in triangles:
if e[0] in t or e[1] in t:
continue
seg, tri = (x[e[0]], x[e[1]]), tuple(x[i] for i in t)
if boxes_meet(seg, tri) and segment_meets_triangle(*seg, *tri):
return False
return True
# ---------------------------------------------------------------- continuous detection against sampling
def lerp(a, b, s):
return add(a, scale(sub(b, a), s))
def sampled_time(kind, p0, p1, samples=400):
"""First contact by sampling the sign of the coplanarity volume, bisection and a proximity test."""
def at(s):
q = [lerp(a, b, s) for a, b in zip(p0, p1)]
return orient(*q), q
def close(q):
if kind == "pt":
return rc.point_triangle_proximity(q[3], q[0], q[1], q[2], rc.ROUNDING_TOL) is not None
return rc.edge_edge_proximity(q[0], q[1], q[2], q[3], rc.ROUNDING_TOL) is not None
prev = at(0.0)[0]
for k in range(1, samples + 1):
cur = at(k / samples)[0]
if (prev > 0) != (cur > 0) or cur == 0.0:
lo, hi = (k - 1) / samples, k / samples
for _ in range(60):
mid = 0.5 * (lo + hi)
fm = at(mid)[0]
if fm != 0.0 and (fm > 0) == (prev > 0):
lo = mid
else:
hi = mid
if close(at(hi)[1]):
return hi
prev = cur
return None
def random_crossing(rng, kind):
"""Four moving points of a pair that often meet: the second part crosses the plane z = 0."""
if kind == "pt":
p0 = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-0.2, 0.2)) for _ in range(3)]
p0.append((rng.uniform(-0.4, 0.4), rng.uniform(-0.4, 0.4), 0.5))
p1 = [add(p, (rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3))) for p in p0[:3]]
p1.append((rng.uniform(-0.4, 0.4), rng.uniform(-0.4, 0.4), -0.5))
else:
p0 = [(-1.0, rng.uniform(-0.5, 0.5), rng.uniform(-0.2, 0.2)), (1.0, rng.uniform(-0.5, 0.5), rng.uniform(-0.2, 0.2)),
(rng.uniform(-0.5, 0.5), -1.0, 0.5), (rng.uniform(-0.5, 0.5), 1.0, 0.5)]
p1 = [add(p, (rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(-0.2, 0.2))) for p in p0[:2]]
p1 += [add(p, (rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), -1.0)) for p in p0[2:]]
return p0, p1
def test_collision_time_against_sampling_and_bisection():
rng = random.Random(1)
for kind in ("pt", "ee"):
hits = 0
for _ in range(50):
p0, p1 = random_crossing(rng, kind)
x0 = {i: p for i, p in enumerate(p0)}
x1 = {i: p for i, p in enumerate(p1)}
pair = (3, (0, 1, 2)) if kind == "pt" else ((0, 1), (2, 3))
got = rc.collision_time(x0, x1, kind, pair)
want = sampled_time(kind, p0, p1)
if want is None:
assert got is None
else:
hits += 1
assert got is not None and abs(got - want) < 1e-9
assert hits > 10
def test_coplanarity_cubic_matches_the_volume():
rng = random.Random(2)
for _ in range(50):
p = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
u = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
k = rc.coplanarity_cubic(p, u)
for s in (0.0, 0.3, 0.7, 1.0):
q = [add(a, scale(b, s)) for a, b in zip(p, u)]
assert abs(rc._poly(k, s) - orient(*q)) < 1e-12
# ---------------------------------------------------------------- proximity against brute force
def point_segment_distance(p, a, b):
d = sub(b, a)
t = dot(sub(p, a), d) / dot(d, d)
t = min(1.0, max(0.0, t))
return norm(sub(p, add(a, scale(d, t))))
def test_edge_edge_closest_points_against_enumeration():
rng = random.Random(3)
for trial in range(300):
q = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
if trial % 10 == 0: # parallel edges
q[3] = add(q[2], scale(sub(q[1], q[0]), rng.uniform(-1, 1)))
s, t = rc.segment_closest(*q)
got = norm(sub(lerp(q[0], q[1], s), lerp(q[2], q[3], t)))
cands = [point_segment_distance(q[0], q[2], q[3]), point_segment_distance(q[1], q[2], q[3]),
point_segment_distance(q[2], q[0], q[1]), point_segment_distance(q[3], q[0], q[1])]
n = cross(sub(q[1], q[0]), sub(q[3], q[2]))
if norm(n) > 1e-9:
# interior critical point: the closest points of the two lines
d1, d2, r = sub(q[1], q[0]), sub(q[3], q[2]), sub(q[0], q[2])
a, b, e = dot(d1, d1), dot(d1, d2), dot(d2, d2)
c, f = dot(d1, r), dot(d2, r)
den = a * e - b * b
s0, t0 = (b * f - c * e) / den, (a * f - b * c) / den
if 0 <= s0 <= 1 and 0 <= t0 <= 1:
cands.append(norm(sub(lerp(q[0], q[1], s0), lerp(q[2], q[3], t0))))
assert abs(got - min(cands)) < 1e-12
def test_point_triangle_weights_against_area_ratios():
rng = random.Random(4)
for _ in range(200):
a, b, c = (tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(3))
n = cross(sub(b, a), sub(c, a))
w = [rng.uniform(-0.1, 1.0) for _ in range(2)]
w.append(1.0 - w[0] - w[1])
h = rng.uniform(-0.01, 0.01)
p = add(add(add(scale(a, w[0]), scale(b, w[1])), scale(c, w[2])), scale(n, h / norm(n)))
r = rc.point_triangle_proximity(p, a, b, c, 0.02)
inside = min(w) >= 0.0
if r is None:
assert not inside
continue
nn = dot(n, n)
want = [dot(n, cross(sub(b, p), sub(c, p))) / nn, dot(n, cross(sub(c, p), sub(a, p))) / nn]
assert abs(r[0] - want[0]) < 1e-9 and abs(r[1] - want[1]) < 1e-9
assert abs(r[4] - abs(h)) < 1e-12 and r[4] >= 0.0
# ---------------------------------------------------------------- impulses
def momentum(v, mass):
return tuple(sum(m * w[k] for m, w in zip(mass, v)) for k in range(3))
def test_impulse_keeps_momentum_and_matches_section_7_1():
rng = random.Random(5)
for _ in range(100):
v = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(4)]
mass = [rng.uniform(0.5, 2.0) for _ in range(4)]
w = [rng.uniform(0, 1) for _ in range(2)]
coeffs = (1.0, -w[0], -w[1], -(1.0 - w[0] - w[1]))
dv = tuple(rng.uniform(-1, 1) for _ in range(3))
before = rc.relative_velocity(v, range(4), coeffs)
p0 = momentum(v, mass)
rc.apply_impulse(v, mass, range(4), coeffs, dv)
after = rc.relative_velocity(v, range(4), coeffs)
assert norm(sub(sub(after, before), dv)) < 1e-12
assert norm(sub(momentum(v, mass), p0)) <= 1e-10 * max(1.0, norm(p0))
# equal masses: the point gets I~/m n and triangle node i gets -w_i I~/m n, I~ = 2 I / (1 + sum w^2)
m, n_hat, dvn = 2.0, (0.0, 0.0, 1.0), 0.6
w = (0.2, 0.3, 0.5)
v = [(0.0, 0.0, 0.0)] * 4
rc.apply_impulse(v, [m] * 4, range(4), (1.0, -w[0], -w[1], -w[2]), scale(n_hat, dvn))
impulse = m * dvn / 2.0
it = 2.0 * impulse / (1.0 + sum(z * z for z in w))
assert abs(v[0][2] - it / m) < 1e-15
for i in range(3):
assert abs(v[i + 1][2] + w[i] * it / m) < 1e-15
def test_repulsion_spring_and_friction():
# one node 0.4 h above the middle of a triangle, moving down slowly and sliding
h, dt, k = 0.01, 0.01, 50.0
x = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.25, 0.25, 0.4 * h)]
mass = [0.1] * 4
v = [(0.0, 0.0, 0.0)] * 3 + [(0.2, 0.0, -0.05)]
con = rc.proximity(x, "pt", (3, (0, 1, 2)), h)
assert con is not None and abs(con[3] - 0.4 * h) < 1e-15
nodes, coeffs, n, dist = con
d = h - dist
m_eff = 1.0 / sum(c * c / mass[i] for i, c in zip(nodes, coeffs))
p0 = momentum(v, mass)
dvn = rc.repulsion(v, mass, con, h, dt, k, mu=0.5)
vr = rc.relative_velocity(v, nodes, coeffs)
want_vn = min(dt * k * d / m_eff, 0.1 * d / dt)
assert abs(dot(vr, n) - want_vn) < 1e-12
assert abs(dvn - (want_vn + 0.05)) < 1e-12
# Coulomb friction: the sliding speed drops by mu dvN
assert abs(vr[0] - (0.2 - 0.5 * dvn)) < 1e-12
assert norm(sub(momentum(v, mass), p0)) < 1e-15
# ---------------------------------------------------------------- rigid zones
def test_rigid_zone_recovers_a_rigid_velocity():
rng = random.Random(6)
dt = 0.1
for _ in range(20):
nodes = list(range(5))
x0 = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in nodes]
mass = [rng.uniform(0.5, 2.0) for _ in nodes]
u = tuple(rng.uniform(-1, 1) for _ in range(3))
w0 = tuple(rng.uniform(-5, 5) for _ in range(3))
c = tuple(rng.uniform(-1, 1) for _ in range(3))
v = [add(u, cross(w0, sub(p, c))) for p in x0]
out = rc.rigid_zone_motion(x0, v, mass, nodes, dt)
x1 = [add(x0[i], scale(out[i], dt)) for i in nodes]
rot = q_to_mat3(q_from_axis_angle(w0, dt * norm(w0)))
for i in nodes:
for j in nodes:
want = tuple(sum(rot[a][b] * (x0[i][b] - x0[j][b]) for b in range(3)) for a in range(3))
assert norm(sub(sub(x1[i], x1[j]), want)) < 1e-12
assert norm(sub(momentum(out.values(), mass), momentum(v, mass))) < 1e-12
# the rotation matrix is orthogonal, so the check above is a rigid motion
prod = mul(transpose(rot), rot)
assert all(abs(prod[a][b] - (1.0 if a == b else 0.0)) < 1e-12 for a in range(3) for b in range(3))
# ---------------------------------------------------------------- whole pipeline
def sheet(nx, ny, spacing, origin, rng, start=0, jitter=0.002):
pts = [(origin[0] + i * spacing, origin[1] + j * spacing, origin[2] + rng.uniform(-jitter, jitter))
for j in range(ny) for i in range(nx)]
tris = []
for j in range(ny - 1):
for i in range(nx - 1):
a = start + j * nx + i
tris += [(a, a + 1, a + nx + 1), (a, a + nx + 1, a + nx)]
return pts, tris
def check_result(x0, v0, v, mass, triangles, dt, zones):
x1 = rc.end_positions(x0, v, dt)
edges = rc.mesh_edges(triangles)
pt, ee = rc.pairs(len(x0), triangles, edges)
assert rc.all_collisions(x0, x1, pt, ee) == []
assert exact_intersection_free(x1, triangles)
p0, p1 = momentum(v0, mass), momentum(v, mass)
scale_p = sum(m * norm(w) for m, w in zip(mass, v0))
assert norm(sub(p1, p0)) <= 1e-10 * max(1.0, scale_p)
for z in zones:
for i in z:
for j in z:
assert abs(math.dist(x0[i], x0[j]) - math.dist(x1[i], x1[j])) < 1e-12
def two_sheets(gap, speed, seed, n=5, jitter=0.002):
"""Sheet b above sheet a. Its nodes fall with speeds from 0.2 speed to 1.2 speed, so it ends half through."""
rng = random.Random(seed)
a, ta = sheet(n, n, 0.1, (0.0, 0.0, 0.0), rng, jitter=jitter)
b, tb = sheet(n, n, 0.1, (0.013, 0.021, gap), rng, start=n * n, jitter=jitter)
v = [(0.0, 0.0, 0.0)] * (n * n) + [(rng.uniform(-0.1, 0.1), rng.uniform(-0.1, 0.1),
-speed * (0.2 + (i % n) / (n - 1)) + rng.uniform(-0.05, 0.05))
for i in range(n * n)]
return a + b, ta + tb, v
def test_sheet_falling_through_a_sheet():
x0, tris, v0 = two_sheets(0.05, 1.0, 1)
mass = [0.01] * 50
assert exact_intersection_free(x0, tris)
assert not exact_intersection_free(rc.end_positions(x0, v0, 0.1), tris)
for passes in (5, 0):
rec = {}
v, zones = rc.handle_collisions(x0, v0, mass, tris, 0.1, 0.005, 50.0, mu=0.3,
collision_passes=passes, record=rec)
check_result(x0, v0, v, mass, tris, 0.1, zones)
if passes == 0:
assert rec["zone_passes"] >= 1 and zones
else:
assert rec["collisions"][0] > 0 and rec["collisions"][-1] == 0
def test_close_sheets_get_repulsions():
x0, tris, v0 = two_sheets(0.004, 0.02, 2, n=4, jitter=0.001)
mass = [0.01] * 32
assert exact_intersection_free(x0, tris)
rec = {}
v, zones = rc.handle_collisions(x0, v0, mass, tris, 0.01, 0.005, 50.0, mu=0.3, record=rec)
assert rec["proximities"] > 0
check_result(x0, v0, v, mass, tris, 0.01, zones)
def test_random_self_collisions_of_one_sheet():
total = 0
zone_runs = 0
for trial in (1, 2):
rng = random.Random(10 + trial)
x0, tris = sheet(5, 5, 0.1, (0.0, 0.0, 0.0), rng, jitter=0.01)
assert exact_intersection_free(x0, tris)
v0 = [tuple(rng.uniform(-1.5, 1.5) for _ in range(3)) for _ in x0]
mass = [rng.uniform(0.005, 0.02) for _ in x0]
rec = {}
v, zones = rc.handle_collisions(x0, v0, mass, tris, 0.1, 0.005, 50.0, mu=0.3,
collision_passes=1, record=rec)
total += rec["collisions"][0]
zone_runs += rec["zone_passes"] > 0
assert rec["zone_passes"] <= len(x0) - 1
check_result(x0, v0, v, mass, tris, 0.1, zones)
assert total > 0 and zone_runs > 0
def test_no_contact_changes_nothing():
rng = random.Random(7)
x0, tris = sheet(4, 4, 0.1, (0.0, 0.0, 0.0), rng)
v0 = [(0.0, 0.0, -1.0)] * 16
v, zones = rc.handle_collisions(x0, v0, [0.01] * 16, tris, 0.1, 0.005, 50.0)
assert v == v0 and zones == []
History
Moore and Wilhelms (1988) found contact times of moving points from the times at which they are coplanar, and Provot (1997) and Doghri et al. (1998) reduced this to the roots of a cubic, as Bridson et al. note in Section 6. Provot (1997) also proposed impact zones. Bridson, Fedkiw and Anderson (2002) combined repulsion impulses with friction, continuous collision impulses and a corrected rigid motion for the zones, and made the step free of intersection in a way that does not depend on the cloth model. Harmon, Vouga, Tamstorf and Grinspun (2008) replaced the rigid zones by an inelastic projection that keeps sliding motion.
References
- Robert Bridson, Ronald Fedkiw and John Anderson, Robust treatment of collisions, contact and friction for cloth animation, ACM Transactions on Graphics 21(3), pages 594 to 603, 2002, Section 5 (the pipeline), Section 6 (proximity and the coplanarity cubic), Section 7.1 to 7.5 (impulse weights, repulsions, friction, iterated collisions, rigid impact zones)
- Xavier Provot, Collision and self-collision handling in cloth model dedicated to design garments, Computer Animation and Simulation 97, Eurographics, Springer, pages 177 to 189, 1997, the impact zones and the cubic for the coplanarity of moving points (as cited by Bridson et al. 2002, Sections 6 and 7.5)
- David Harmon, Etienne Vouga, Rasmus Tamstorf and Eitan Grinspun, Robust treatment of simultaneous collisions, ACM Transactions on Graphics 27(3), 2008, the abstract (a failsafe that cancels impact but not sliding motion)
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 QXMR1R Edit this page History Report an error Markdown