Algorithmadvanced
Impact zones
Also called rigid impact zones.
Group vertices involved in unresolved simultaneous collisions and move each group rigidly, or project it to a collision-free state, until no collisions remain.
- Solves
- Cloth simulation
- Time
- O(p n m) totalΘ(n m) passO(n^2 m) worst_case
- Space
- Θ(n + m) zones
- Where
- m = the number of edges; n = the number of nodes; p = the number of passes that find collisions
- Model
- Real RAM
- Properties
- not angular momentum conservingcollision free resultdeterministicnot exactlinear momentum conserving
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Xavier Provot, Robert Bridson, Ronald Fedkiw, John Anderson, 1997
Impact zones are the last line of defence of a cloth collision method. When a step has many collisions at once, applying impulses one collision at a time can go on for a long time, because fixing one collision can cause another. Provot (1997) suggested a failsafe: put all nodes of the collisions that remain into groups, the impact zones, and move each group as one rigid body. Bridson, Fedkiw and Anderson (2002) showed that Provot's formulas did not give a true rigid motion, corrected them, and used the zones after a few passes of impulses. A rigid zone cannot collide with itself, so the zones only grow, and the loop ends with a step that has no collisions.
In plain words
Imagine a crumpled sheet in which many folds hit each other in the same instant. Pushing the folds apart one pair at a time may never finish, because every push can cause a new hit.
Impact zones take a blunt approach: every group of points that collides is glued together for this step and moves as one solid piece. A solid piece cannot pass through itself, so the problem inside the group is gone. If a glued group still hits another part of the cloth, the two are glued together too. In the worst case the whole cloth moves as one solid piece for one step, and that motion has no collisions.
The price is that the glued points stop moving relative to each other for that step. The group keeps its total momentum, so it still drifts and turns in a believable way.
The problem
Given node positions with no contact, masses , velocities for a step of length , and the edges of the cloth, find new velocities such that the straight paths , , have no contact: no node lies on an edge that does not contain it at any time. The page works in 2D, where the cloth is a set of curves and a node-edge test covers every contact. In 3D the tests are node-triangle and edge-edge, as in robust cloth collision.
The algorithm
RIGID-IMPACT-ZONES(x, v, m, edges, dt)- 1
make each node its own zone ▷ a disjoint-set structure - 2
loop: - 3
C <- all node-edge collisions on the paths x + s dt v, s in [0, 1] - 4
if C is empty: return v - 5
for each collision (i, (a, b)) in C: unite the zones of i, a and b - 6
for each zone Z that took part in a collision of C: - 7
x_cm, v_cm <- mass-weighted means over Z ; L <- sum m_i r_i x (v_i - v_cm) ; I <- sum m_i |r_i|^2 - 8
omega <- L / I ▷ a scalar in 2D, I^-1 L in 3D - 9
for i in Z: y_i <- x_cm + dt v_cm + R(dt omega) r_i ▷ r_i = x_i - x_cm - 10
v_i <- (y_i - x_i) / dt
The collision test (L3). A node is on the line of a moving edge when . On straight paths this is a quadratic in . The code solves it, keeps the roots in , and checks at each root that is between and . The code tests all node-edge pairs; a real code uses a bounding volume hierarchy or spatial hashing first.
The rigid motion (L7 to L10). This is Section 7.5 of Bridson et al. The zone keeps its centre of mass velocity , and its angular velocity is the one that keeps the angular momentum. To make the step itself rigid, the end positions are the start positions rotated by the angle about the centre of mass and moved by , and the new velocity is the mean velocity over the step. In 3D the part of along does not rotate; in 2D that part is empty.
Choices of this code. Only zones that took part in a collision of the pass get a new motion. If the rotation angle is or more, the zone only translates, because the proof needs an angle below .
Example
One node falls on an edge, by hand. An edge joins and , both at rest, and a node at falls with m/s, with s and all masses kg. The node reaches the edge at . Line L5 makes one zone of the three nodes. Its centre is , its mean velocity is m/s, and the relative velocities are , and at offsets , and . The angular momentum is , so and all three nodes move down with m/s. The momentum kg m/s is kept, and the next pass finds no collision. If the node falls at instead, the same steps give , and rad/s, so the zone also turns.
Two chains, measured. A chain of 10 nodes at rest and a chain of 10 nodes m above it, falling with about m/s, with s, have 18 collisions in the first pass. All 20 nodes end in one zone after one pass, and the second pass finds no collision. Both chains then move together as one rigid body for that step: the failsafe resolves the collisions but freezes the cloth into a clump, which is why Bridson et al. use it only after the impulses fail.
One chain with random velocities, measured. For eight chains of 12 nodes with random velocities up to m/s, four have no collision, three need one pass with one zone of 3 nodes, and one needs one pass with a zone of 5 nodes.
Correctness
The claims are proved in proofs/correctness.md.
- Rigid and momentum (proved). The end positions of a zone are a rigid image of the start positions, and the zone keeps its linear momentum exactly. Rigid input velocities give back their angular velocity.
- Angular momentum (proved, not kept). The mean velocities have the angular momentum with , so it is kept only up to .
- No self-collision of a zone (proved). At every time of the step, the nodes of a rigid zone are an invertible affine image of their start positions when , so a zone without contact at the start has none during the step.
- Termination (proved). Every pass with a collision merges at least two zones, so the loop ends after at most such passes, and the result has no collision on the paths and no crossing at the end.
- Plausibility (not claimed). The method does not give the motion of real cloth; the zones remove all relative motion inside them for the step.
The tests check the collision time against fine sampling and bisection, a collinear case, the rigid motion, the momentum and the angular momentum factor, the fallback for large angles, two chains that pass through each other and random self-collisions of a chain. After each run they check the paths with the collision test, the end state with an exact test in rational arithmetic, the linear momentum to , the rigidity of each zone, and the zones against the connected components of all collisions found.
Proof: A rigid zone keeps its momentum and has no internal collision, so the zones stop growing after at most n - 1 passesfull
We use the notation of the page, in 2D. Node has mass , start position and velocity , and moves on for . A contact at time is a node on an edge that does not contain it. We assume that the start state has no contact. All statements are in exact arithmetic.
The rigid motion of a zone
For a zone with , let , , , (the scalar cross product) and . Lines L7 to L10 set , , the end position and the new velocity . This is the formula of Bridson, Fedkiw and Anderson (2002, Section 7.5) in the plane, where the component along the axis of rotation is empty. If , the code uses .
Lemma 1. (a) If the velocities are rigid, with the rotation by , then . (b) . (c) The end positions are a rigid image of the start positions: . (d) The angular momentum about of the new velocities is (and if because or ), not .
Proof. (a) With , , and , so . (b) . (c) , and keeps lengths. (d) by (b), so the angular momentum is . For the fallback with , the new angular momentum is .
So the zone keeps the linear momentum exactly, and the angular momentum up to the factor . This is the error in the rotation that Bridson et al. accept when they hold constant over the step.
No collision inside a rigid zone
Lemma 2. If , the straight paths of the nodes of a rigid zone have no contact among the nodes and edges of the zone at any .
Proof. For a node of the zone, with . The same map moves all nodes of the zone. Its determinant is . This is zero only if and ; for the second term is , and for with we have and the second term is . So the map is an invertible affine map for every . An invertible affine map sends segments to segments and points on a segment to points on its image, and its inverse does the same. A contact of the zone at time would then give a contact at , which the start state does not have.
For the fallback , , so the lemma holds too.
Termination
Theorem 3. The loop L2 to L10 ends after at most passes that find collisions, and at the end the paths of all nodes have no contact.
Proof. At the start of every pass, each zone is a single node or has the rigid motion of its last merge, because a zone that is not touched keeps its velocities. Take a collision of the pass: node and edge with . If , and were all in one zone, that zone would have at least 3 nodes, so it is rigid, and Lemma 2 says that it has no internal contact. So the three nodes lie in at least two zones, and line L5 merges at least two zones. Each pass with a collision lowers the number of zones by at least one. There are zones at the start, so after at most such passes there is one zone, which is rigid and has no contact by Lemma 2. The loop stops at the first pass with no collision, which is the claim.
Corollary 4. The end state has no two crossing edges and no node on an edge. A change in whether two segments meet needs a moment at which an endpoint of one lies on the other, which is a contact on the paths. The start state has none, so the end state has none.
The zones are the components. Line L5 unites the zones of , and for each collision, and the disjoint-set structure only unites. So the final zones are the connected components of the graph whose edges join the three nodes of every collision found in every pass. The test compares them with a search of that graph.
What is not claimed
The method does not give the motion that the cloth would have, and the page does not claim it does. It gives up all relative motion inside a zone, so cloth that is grouped this way freezes into clumps, as Bridson et al. note, and it does not keep the angular momentum exactly (Lemma 1 (d)). In floating point, Lemma 2 holds up to rounding, so a production code adds a small thickness. The tests use generic scenes, check the paths with the floating-point test, and check the end state with an exact rational test.
Complexity
A pass of this code tests every node against every edge, , and moves the zones in time. The disjoint-set operations cost each, amortized, with path halving and union by size. With passes the cost is , and , so the worst case is . With a bounding volume hierarchy, a pass costs about the number of nearby pairs instead of . In practice the impulses before the failsafe remove most collisions, and the zones stay small (Bridson et al., Section 7.5; an observation, not a bound).
Properties
- Always ends. The zones only grow, and one rigid zone has no collision.
- Collision free. The result has no contact on the paths, in exact arithmetic.
- Dissipative. All relative motion in a zone is lost, which can look like sticky cloth.
- Linear momentum. Kept exactly in each zone. Angular momentum is kept only to .
- Order free. All collisions of a pass are handled together, so the result does not depend on the order of the collision list.
Variants and improvements
- Provot's zones (1997). The original formulas for the zone motion did not give a rigid motion, so a zone could still deform during the step. Bridson et al. corrected them (Section 7.5).
- Inelastic projection. Harmon, Vouga, Tamstorf and Grinspun (2008) replace the rigid motion by a failsafe that cancels the approaching motion but keeps sliding, which removes much less energy, and they add an approximation of Coulomb friction.
- Barrier methods. Incremental potential contact keeps the cloth free of intersections by a barrier energy inside the time step, so no failsafe is needed.
- Contact as a complementarity problem. Simultaneous contacts can also be posed as a linear complementarity problem on the impulses.
When to use it
Use impact zones as the failsafe of a collision pipeline that must never let cloth pass through itself, after a few passes of local impulses have not removed every collision. Use it alone only when stickiness is acceptable, because the zones freeze the cloth into clumps.
Do not use it as the main contact method, and prefer an inelastic projection when the sliding of cloth on cloth matters.
Pitfalls
- Contact at the start. The proof needs a start state with no contact. If the input already intersects, the rigid motion keeps the intersection.
- Large rotations. For the path of a rigid zone is not an invertible affine image of the start, and a zone can pass through itself. The code then only translates the zone.
- Rounding. In floating point a node can end on an edge by rounding. Real codes add a small thickness and test proximity, not only exact contact.
- Angular velocity in 3D. needs the inertia tensor of the current positions. For collinear nodes the tensor is singular, and the angular velocity along the line has no effect and must be set to zero.
- Recomputing old zones. Giving an unchanged zone a new rigid motion from its mean velocities shrinks its rotation by every pass. The code recomputes only zones that took part in a collision.
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
impact_zones.py 195 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impact-zones/. The authors are listed in prov/BJ4E1Y.jsonl.
"""Rigid impact zones (Provot 1997, with the rigid motion of Bridson, Fedkiw and Anderson 2002), in 2D.
The cloth is a set of nodes and edges in the plane. In a step of length dt each
node moves on the straight line x_i(s) = x_i + s dt v_i, s in [0, 1]. A
collision is a time s at which a node lies on an edge that does not contain it
(in 2D this point-edge test covers all contacts of a curve).
The failsafe merges the nodes of every collision into one zone (a disjoint-set
structure) and gives each zone the rigid motion with the same linear and
angular momentum, until the paths have no collision. In 2D the rotation of a
zone is a scalar angle, and the 3D fixed component of Bridson et al. is empty.
Choices of this code:
- Only the zones that took part in a collision in this pass get a new rigid
motion. Other zones keep their velocities.
- If the rotation angle dt |omega| of a zone is pi or more, the zone gets the
pure translation with its mean velocity. Both motions keep the linear
momentum; the translation does not keep the angular momentum.
"""
import math
from anim import add, cross2, dot, rot2, scale, sub
# ---------------------------------------------------------------- continuous point-edge test
def _roots_01(a, b, c):
"""Real roots of a s^2 + b s + c in [0, 1], sorted. None if the polynomial is zero."""
if a == 0.0:
if b == 0.0:
return None if c == 0.0 else []
roots = [-c / b]
else:
disc = b * b - 4.0 * a * c
if disc < 0.0:
return []
q = -0.5 * (b + math.copysign(math.sqrt(disc), b))
roots = [q / a]
if q != 0.0:
roots.append(c / q)
else:
roots.append(0.0)
return sorted(s for s in roots if 0.0 <= s <= 1.0)
def _on_segment(p, a, b):
e = sub(b, a)
t = dot(sub(p, a), e)
return 0.0 <= t <= dot(e, e)
def point_edge_time(p0, p1, a0, a1, b0, b1):
"""The first s in [0, 1] at which the moving point p lies on the moving segment ab, or None.
The point is on the line of the segment where cross(b - a, p - a) = 0, which
is a quadratic in s, and on the segment where 0 <= (p - a) . (b - a) <= |b - a|^2.
"""
e0, q0 = sub(b0, a0), sub(p0, a0)
de, dq = sub(sub(b1, a1), e0), sub(sub(p1, a1), q0)
roots = _roots_01(cross2(de, dq), cross2(e0, dq) + cross2(de, q0), cross2(e0, q0))
if roots is None:
# the three points stay on one line: test where the order along the line can change
cand = [0.0, 1.0]
ee = (dot(de, de), 2.0 * dot(e0, de), dot(e0, e0))
qe = (dot(dq, de), dot(q0, de) + dot(dq, e0), dot(q0, e0))
for coef in (qe, (qe[0] - ee[0], qe[1] - ee[1], qe[2] - ee[2])):
r = _roots_01(*coef)
cand.extend(r or [])
roots = sorted(cand)
for s in roots:
p, a, b = (lerp_point(u, w, s) for u, w in ((p0, p1), (a0, a1), (b0, b1)))
if _on_segment(p, a, b):
return s
return None
def lerp_point(u, w, s):
return (u[0] + s * (w[0] - u[0]), u[1] + s * (w[1] - u[1]))
def collisions(x0, x1, edges):
"""All (node, edge index, s) with a point-edge collision on the straight paths from x0 to x1."""
out = []
for k, (a, b) in enumerate(edges):
for i in range(len(x0)):
if i == a or i == b:
continue
s = point_edge_time(x0[i], x1[i], x0[a], x1[a], x0[b], x1[b])
if s is not None:
out.append((i, k, s))
return out
# ---------------------------------------------------------------- zones
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):
"""New velocities {i: v_i} that move the zone rigidly with its linear and angular momentum."""
m = sum(mass[i] for i in nodes)
xcm = scale(sum_vec(scale(x0[i], mass[i]) for i in nodes), 1.0 / m)
vcm = scale(sum_vec(scale(v[i], mass[i]) for i in nodes), 1.0 / m)
ang = 0.0
inertia = 0.0
for i in nodes:
r = sub(x0[i], xcm)
ang += mass[i] * cross2(r, sub(v[i], vcm))
inertia += mass[i] * dot(r, r) # @line L7
omega = ang / inertia if inertia > 0.0 else 0.0 # @line L8
phi = dt * omega
if abs(phi) >= math.pi:
phi = 0.0
rot = rot2(phi)
out = {}
for i in nodes:
r = sub(x0[i], xcm)
rr = (rot[0][0] * r[0] + rot[0][1] * r[1], rot[1][0] * r[0] + rot[1][1] * r[1])
end = add(add(xcm, scale(vcm, dt)), rr) # @line L9
out[i] = scale(sub(end, x0[i]), 1.0 / dt) # @line L10
return out
def sum_vec(vs):
s = (0.0, 0.0)
for w in vs:
s = (s[0] + w[0], s[1] + w[1])
return s
def impact_zones(x0, v, mass, edges, dt, max_passes=None, record=None):
"""Apply rigid impact zones until the paths x0 + s dt v have no collision.
x0 must be free of contacts (no node on an edge that does not contain it).
Return (v, zones, passes): the new velocities, the list of zones with more
than one node, and the number of passes that found collisions. If record
is a list, the collisions of each pass are appended to it.
"""
n = len(x0)
v = [tuple(w) for w in v]
zones = DisjointSet(n) # @line L1
passes = 0
limit = n if max_passes is None else max_passes
while True: # @line L2
x1 = [add(x0[i], scale(v[i], dt)) for i in range(n)]
found = collisions(x0, x1, edges) # @line L3
if record is not None:
record.append(found)
if not found:
break # @line L4
if passes >= limit:
raise RuntimeError("impact zones did not resolve the collisions")
passes += 1
touched = set()
for i, k, _ in found:
a, b = edges[k]
touched.add(zones.union(zones.union(i, a), b)) # @line L5
groups = zones.groups()
for root in {zones.find(r) for r in touched}: # @line L6
v_new = rigid_zone_motion(x0, v, mass, groups[root], dt)
for i, w in v_new.items():
v[i] = w
multi = [g for g in zones.groups().values() if len(g) > 1]
return v, multi, passes
test_impact_zones.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/impact-zones/. The authors are listed in prov/BJ4E1Y.jsonl.
"""Tests of rigid impact zones against sampling, exact rational tests and exact identities."""
import math
import random
from fractions import Fraction
from anim import cross2, sub
import impact_zones as iz
def f_cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def exact_segments_meet(p, q, r, s):
"""Exact test with Fractions: do the closed segments pq and rs share a point?"""
p, q, r, s = ([Fraction(c) for c in pt] for pt in (p, q, r, s))
d1, d2 = f_cross(r, s, p), f_cross(r, s, q)
d3, d4 = f_cross(p, q, r), f_cross(p, q, s)
if ((d1 > 0) != (d2 > 0)) and d1 != 0 and d2 != 0 and ((d3 > 0) != (d4 > 0)) and d3 != 0 and d4 != 0:
return True
def on(a, b, c):
return f_cross(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 exact_interference_free(x, edges):
for k, (a, b) in enumerate(edges):
for c, d in edges[k + 1:]:
if len({a, b, c, d}) == 4 and exact_segments_meet(x[a], x[b], x[c], x[d]):
return False
for i in range(len(x)):
if i not in (a, b) and exact_segments_meet(x[a], x[b], x[i], x[i]):
return False
return True
def sampled_time(p0, p1, a0, a1, b0, b1, samples=20000):
"""The first collision by fine sampling of the collinearity sign and bisection."""
def at(s):
p, a, b = (iz.lerp_point(u, w, s) for u, w in ((p0, p1), (a0, a1), (b0, b1)))
return cross2(sub(b, a), sub(p, a)), p, a, b
prev = at(0.0)[0]
for k in range(1, samples + 1):
s = k / samples
cur = at(s)[0]
if (prev > 0) != (cur > 0) or cur == 0.0:
lo, hi = (k - 1) / samples, s
for _ in range(60):
mid = 0.5 * (lo + hi)
if (at(mid)[0] > 0) == (prev > 0) and at(mid)[0] != 0.0:
lo = mid
else:
hi = mid
_, p, a, b = at(hi)
if iz._on_segment(p, a, b):
return hi
prev = cur
return None
def test_point_edge_time_against_sampling_and_bisection():
rng = random.Random(1)
hits = 0
for _ in range(150):
pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(6)]
got = iz.point_edge_time(*pts)
want = sampled_time(*pts, samples=3000)
if want is None:
assert got is None
else:
hits += 1
assert got is not None and abs(got - want) < 1e-9
assert hits > 15
def test_collinear_motion():
# the point slides along the line of the edge and enters it at s = 0.5
s = iz.point_edge_time((-1.0, 0.0), (1.0, 0.0), (0.0, 0.0), (0.0, 0.0), (1.0, 0.0), (1.0, 0.0))
assert s == 0.5
assert iz.point_edge_time((-3.0, 0.0), (-2.0, 0.0), (0.0, 0.0), (0.0, 0.0), (1.0, 0.0), (1.0, 0.0)) is None
def rigid_check(x0, x1, nodes, tol):
for a in nodes:
for b in nodes:
assert abs(math.dist(x0[a], x0[b]) - math.dist(x1[a], x1[b])) <= tol
def test_rigid_zone_recovers_a_rigid_velocity_and_keeps_momentum():
rng = random.Random(2)
dt = 0.1
for _ in range(20):
nodes = list(range(6))
x0 = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in nodes]
mass = [rng.uniform(0.5, 2.0) for _ in nodes]
c = (rng.uniform(-1, 1), rng.uniform(-1, 1))
w0 = rng.uniform(-5, 5)
vt = (rng.uniform(-1, 1), rng.uniform(-1, 1))
v = [(vt[0] - w0 * (p[1] - c[1]), vt[1] + w0 * (p[0] - c[0])) for p in x0]
out = iz.rigid_zone_motion(x0, v, mass, nodes, dt)
x1 = [(x0[i][0] + dt * out[i][0], x0[i][1] + dt * out[i][1]) for i in nodes]
rigid_check(x0, x1, nodes, 1e-12)
# the rotation angle is dt w0
ang = math.atan2(cross2(sub(x0[1], x0[0]), sub(x1[1], x1[0])),
sum(a * b for a, b in zip(sub(x0[1], x0[0]), sub(x1[1], x1[0]))))
assert abs(ang - dt * w0) < 1e-12
# linear momentum is kept exactly; the angular momentum of the mean velocities is L sin(phi) / phi
m = sum(mass)
for k in range(2):
assert abs(sum(mi * vi[k] for mi, vi in zip(mass, v)) - sum(mass[i] * out[i][k] for i in nodes)) < 1e-12
xcm = tuple(sum(mi * p[k] for mi, p in zip(mass, x0)) / m for k in range(2))
lin = [sum(mass[i] * vi[k] for i, vi in enumerate(v)) / m for k in range(2)]
def ang_mom(vel):
return sum(mass[i] * cross2(sub(x0[i], xcm), sub(vel[i], lin)) for i in nodes)
phi = dt * w0
assert abs(ang_mom(out) - ang_mom(v) * math.sin(phi) / phi) < 1e-12 * max(1.0, abs(ang_mom(v)))
def test_large_angle_falls_back_to_translation():
x0 = [(1.0, 0.0), (-1.0, 0.0)]
v = [(0.0, 40.0), (0.0, -40.0)] # omega = 40 rad/s, dt omega = 4 > pi
out = iz.rigid_zone_motion(x0, v, [1.0, 1.0], [0, 1], 0.1)
assert out[0] == (0.0, 0.0) and out[1] == (0.0, 0.0)
def chain(n, x0, y0, spacing, start=0):
pts = [(x0 + i * spacing, y0) for i in range(n)]
edges = [(start + i, start + i + 1) for i in range(n - 1)]
return pts, edges
def components(n, record, edges):
"""Brute force: connected components of the graph of all collisions found."""
adj = [set() for _ in range(n)]
for found in record:
for i, k, _ in found:
a, b = edges[k]
for p, q in ((i, a), (i, b), (a, b)):
adj[p].add(q)
adj[q].add(p)
seen, comps = set(), []
for s in range(n):
if s in seen or not adj[s]:
continue
stack, comp = [s], []
seen.add(s)
while stack:
u = stack.pop()
comp.append(u)
for w in adj[u]:
if w not in seen:
seen.add(w)
stack.append(w)
comps.append(sorted(comp))
return sorted(comps)
def check_resolved(x0, v0, v, mass, edges, zones, record, dt):
n = len(x0)
x1 = [(x0[i][0] + dt * v[i][0], x0[i][1] + dt * v[i][1]) for i in range(n)]
assert iz.collisions(x0, x1, edges) == []
assert exact_interference_free(x1, edges)
for k in range(2):
p0 = sum(m * w[k] for m, w in zip(mass, v0))
p1 = sum(m * w[k] for m, w in zip(mass, v))
assert abs(p1 - p0) <= 1e-10 * max(1.0, sum(m * abs(w[k]) for m, w in zip(mass, v0)))
for z in zones:
rigid_check(x0, x1, z, 1e-12)
assert sorted(sorted(z) for z in zones) == components(n, record, edges)
def test_two_chains_passing_through_each_other():
a, ea = chain(10, 0.0, 0.0, 0.1)
b, eb = chain(10, 0.03, 0.05, 0.1, start=10)
x0 = a + b
edges = ea + eb
rng = random.Random(3)
v0 = [(0.0, 0.0)] * 10 + [(rng.uniform(-0.1, 0.1), -1.0 + rng.uniform(-0.1, 0.1)) for _ in range(10)]
mass = [1.0] * 20
assert exact_interference_free(x0, edges)
record = []
v, zones, passes = iz.impact_zones(x0, v0, mass, edges, 0.1, record=record)
assert passes >= 1 and zones
check_resolved(x0, v0, v, mass, edges, zones, record, 0.1)
def test_random_self_collisions_of_one_chain():
rng = random.Random(4)
total_passes = 0
for trial in range(8):
n = 12
x0 = [(0.1 * i, rng.uniform(-0.02, 0.02)) for i in range(n)]
edges = [(i, i + 1) for i in range(n - 1)]
assert exact_interference_free(x0, edges)
v0 = [(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5)) for _ in range(n)]
mass = [rng.uniform(0.5, 2.0) for _ in range(n)]
record = []
v, zones, passes = iz.impact_zones(x0, v0, mass, edges, 0.1, record=record)
assert passes <= n - 1
total_passes += passes
check_resolved(x0, v0, v, mass, edges, zones, record, 0.1)
assert total_passes > 0
def test_no_collision_changes_nothing():
x0, edges = chain(5, 0.0, 0.0, 0.1)
v0 = [(0.0, -1.0)] * 5
v, zones, passes = iz.impact_zones(x0, v0, [1.0] * 5, edges, 0.1)
assert v == v0 and zones == [] and passes == 0
History
Xavier Provot described impact zones in 1997 for garment design, as a way to handle many collisions at once in cloth that bunches together, where friction prevents most relative motion. Bridson, Fedkiw and Anderson (2002) used the idea as the failsafe of their robust collision method, after the repulsion forces and iterated collision impulses, and noted that Provot's formulas for the angular velocity were flawed. Harmon, Vouga, Tamstorf and Grinspun (2008) replaced the rigid motion by an inelastic projection that keeps sliding motion.
References
- 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 (as described and corrected by Bridson et al. 2002, Section 7.5)
- 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 7.4 (iterated geometric collisions and the switch to a failsafe), Section 7.5 (rigid impact zones, the corrected rigid motion)
- 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)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BJ4E1Y Edit this page History Report an error Markdown