Algorithmadvanced
Meshless shape matching
Also called shape matching deformation.
Pull particles toward goal positions given by the best rigid or linear transform of the rest shape, found by polar decomposition each step.
- Time
- Θ(n) precompute · step
- Space
- Θ(n) step
- Where
- n = the number of particles of a body
- Model
- Real RAM
- Properties
- angular momentum conservingdeterministicnot exactlinear momentum conservingnot needs mesh
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matthias Müller, Bruno Heidelberger, Matthias Teschner, Markus Gross, 2005
Meshless shape matching moves a soft body made of particles without a mesh and without elastic forces. In each step it finds the rotation and translation that best map the rest shape onto the current particles, in the mass weighted least squares sense, and pulls each particle a fraction of the way toward its place in that rigid copy. Müller, Heidelberger, Teschner and Gross (2005) proposed it for games: a step costs , the pull never overshoots the goal, and with a fixed goal the motion neither grows nor decays for any . A linear or quadratic fit instead of the rotation gives softer bodies.
In plain words
Keep a photo of the object in its rest shape. In each frame, lay the photo over the particles: slide it and turn it until it covers them as well as possible, with heavy particles counting more. The place of each particle on the photo is its goal. Then give each particle a push toward its goal, so that it would cover the fraction of the gap in one frame, and let it move. A dent pops back out because the photo has no dent. With the body snaps back at once and acts rigid. With a small it wobbles like jelly. If the photo may also stretch and shear, not only slide and turn, the body can keep some of its deformation.
The problem
The input is one body with particles: masses , rest positions , current positions and velocities , external forces , a stiffness and a step . The output is the state after one step. The rest shape must not lie on a line, so that is invertible. There is no material law to solve: the method is a model of its own, chosen for speed and robustness. The page uses 2D, up and m/s²; the paper works in 3D, and the 2D code is a version of it.
The algorithm
Let be the rest positions about the rest center of mass, computed once with .
SHAPE-MATCH-STEP(x, v, m, q, S0⁻¹, α, Δt, mode, β)- 1
x_cm <- Σ m_i x_i / Σ m_i; p_i <- x_i - x_cm - 2
A_pq <- Σ m_i p_i q_iᵀ ▷ 2 by 2 - 3
R <- rotation factor of the polar decomposition of A_pq - 4
G <- R, or in the linear mode G <- β A~ + (1 - β) R ▷ A~ = A/√det A, A = A_pq S0⁻¹ - 5
for each particle i: g_i <- G q_i + x_cm ▷ goal - 6
for each particle i: v_i <- v_i + α (g_i - x_i)/Δt + Δt f_i/m_i - 7
for each particle i: x_i <- x_i + Δt v_i
The best rotation (L1 to L3). The rotation and translation that minimize are and the rotation that maximizes . This is the weighted orthogonal Procrustes problem that the Kabsch algorithm solves, and its answer is the rotation factor of the polar decomposition (Section 3.3, equations (5) to (8)). The paper computes by a diagonalization and . In 2D there is a closed form, with , which the code uses through the shared polar helper. It is always a rotation; the formula is a reflection when , for example after a body is pushed inside out. In 3D, a singular value decomposition gives the same rotation with a sign fix.
Linear deformation (L4). The best linear map is (Section 4.2). Dividing by in 2D, or by in 3D, keeps the area or the volume. The blend lets the body keep a part of its stretch and shear. The code falls back to when .
Integration (L6, L7). Equation (9) of the paper adds the pull to the velocity and then moves the particles with the new velocity, as in symplectic Euler. The pull is a velocity, not a force, so it does not depend on the mass, and with a particle at rest never passes its goal in one step.
Example
A stretched square by hand. Four particles of mass 1 rest at . Now they are at , stretched along , at rest. The center of mass is the origin, so for with , and . Then and , so the goals are the rest positions. With , and no gravity, the corner at gets the velocity along and moves to . In the linear mode, , so , and . With the goal of that corner is : the stretch is turned into an area preserving shape.
The oscillation does not decay (measured). The same square, started at with in the rigid mode, oscillates about its rest shape. Over 3000 steps:
| period in steps (measured) | largest gap, steps 1 to 300 | largest gap, steps 2701 to 3000 | ||
|---|---|---|---|---|
| 0.05 | 28.04 | 28.04 | 1.0062 | 1.0056 |
| 0.2 | 13.93 | 13.93 | 1.0260 | 1.0260 |
| 0.5 | 8.69 | 8.69 | 1.0690 | 1.0690 |
The gap is the distance of the corner from its goal along . The period in steps matches the eigenvalue angle of the fixed goal model (claim 6), and the size of the oscillation stays the same. The period does not depend on when it is counted in steps, so in seconds it is proportional to : the stiffness that gives changes with the step size.
Correctness
The claims are proved in proofs/correctness.md.
- Best rigid fit (proved). The translation and the rotation of L3 minimize over all rotations. The test compares the rotation with a scan of 720 angles.
- Best linear fit (proved). is the least squares linear map, and it recovers exactly when . The test checks for random .
- No pull at a rigid pose (proved). If the particles are a rotated and moved copy of the rest shape, every goal equals its particle, in all modes.
- Momentum (proved). With no external force, a step keeps the linear and the angular momentum exactly, in the rigid and the linear mode, because the pull sums to zero and has zero torque. The test checks both to over 200 steps.
- Snap to the goals (proved). With and zero velocity, one step puts every particle on its goal.
- Fixed goal model (proved). For a particle with a fixed goal the step is the matrix of equation (11), whose eigenvalues have magnitude 1 for . This is the sense in which the paper calls the method unconditionally stable. It does not cover the real case, where the goals move with the particles; the table above measures that case for one body.
- Gravity (proved). Under gravity the center of mass moves by symplectic Euler; the test checks the value m after 10 steps of s.
Proof: The goals are the best rigid or linear fit of the rest shape, and the step keeps linear and angular momentum exactlyfull
We use the notation of the page, in 2D. A body has particles with masses , total mass , rest positions and current positions . Let and be the centers of mass, and , so . Let and , which we assume invertible (the rest shape does not lie on a line). The goal positions are for a matrix , and the step of lines L6 and L7 is
equation (9) of Müller et al. (2005). The cross product of two vectors in the plane is the number .
The goals are best fits
Lemma 1 (rigid fit). Among all rotations and translations , the sum is smallest for and for the rotation with , which line L3 computes. The rotation is unique unless both arguments of atan2 are zero.
Proof. The sum is a convex quadratic in with gradient , because . So for every . Then the sum is , and . For , . This is with and the angle of the formula, so it is largest exactly at when .
When this is the rotation factor of the polar decomposition with symmetric positive definite, the formula of Section 3.3 of the paper. When the paper's formula would be a reflection, while the formula above is still the best rotation. In both cases is symmetric: with and , . We write for this symmetric matrix.
Lemma 2 (linear fit). The matrix minimizes over all matrices. If for all , then .
Proof. The sum is a convex quadratic in with gradient , which is zero exactly at . If , then , so , and .
The volume preserving matrix of line L4 is when , with in 2D; the code uses when . Line L4 uses (Section 4.2 of the paper).
Lemma 3 (no pull at a rigid pose). If for a rotation , then for all , in the rigid mode and in the linear mode for every .
Proof. Here and . For any rotation , with the rotation , and because is symmetric positive definite and the diagonal entries of in the eigenbasis of are at most 1. Equality holds for , and by Lemma 1 the maximizer is unique since . So . By Lemma 2, , which has determinant 1, so and in every mode. Then .
Momentum
Lemma 4. For every , .
Proof. .
Lemma 5. If is symmetric, then . This holds for , , and every .
Proof. Write and . Then the sum is . The first term is zero by Lemma 4 and the last term is zero. For the middle term, , and . So the middle term is the difference of the off-diagonal entries of , which is zero when this matrix is symmetric. Now is symmetric because is (Lemma 1). is symmetric because is. is a multiple of , and a combination of matrices with the property has it.
Theorem 6. With no external forces, one step keeps and exactly, in the rigid and in the linear mode, for every and .
Proof. By Lemma 4, . For , , so by Lemma 5.
Corollary 7. Under uniform gravity, , the center of mass moves by symplectic Euler: and .
Proof. Multiply the step by , sum and divide by ; the goal terms cancel by Lemma 4.
Stability with a fixed goal
Lemma 8. For one particle with a fixed goal and no external force, the pair with evolves by the matrix in each coordinate (equation (11) of the paper). For its eigenvalues are with , so they have magnitude 1, and the motion is a rotation of in a fixed elliptic norm: it neither grows nor decays.
Proof. The step gives and , which is . Its determinant is and its trace is . The eigenvalues solve . For the discriminant is negative, so the two roots are complex conjugates whose product is 1, hence both have magnitude 1, and . The roots are distinct, so is diagonalizable over and is similar to a rotation by .
The paper calls this unconditionally stable. It is a statement about the model with a fixed goal; the real goals move with the particles. The period is steps for every , so the stiffness that gives depends on : a spring with the same period has .
Lemma 9. If , and , one step gives .
Proof. , so .
Cost
Lemma 10. A step costs time and memory, after a precomputation of , the and .
Proof. Lines L1, L2, L5, L6 and L7 are sums or maps over the particles with work each. Lines L3 and L4 work on matrices in .
Complexity
A step costs time: two sums over the particles (L1, L2), work on or matrices (L3, L4) and two maps over the particles (L5 to L7). The rest data and cost once. The memory is . With overlapping clusters, each particle is in a bounded number of clusters and the cost is linear in the total cluster size.
Properties
- Robust. The pull is toward a valid shape, so a body recovers from any deformation, even an inverted one, and a step cannot blow up with in the fixed goal model.
- No mesh. Only the particles and their rest positions are needed; the connectivity does not matter.
- Not a material model. is a tuning value, and the stiffness it gives depends on and on the size of the body. Measured periods depend only on when counted in steps.
- No damping of its own. The oscillation keeps its size; damping must be added, for example by the rigid body damping of PBD.
- Exact momentum. Linear and angular momentum are kept exactly without external forces.
- Global stiffness. One cluster can only deform by a single rotation or linear map, so a long object cannot bend. Clusters fix this.
Variants and improvements
- Quadratic deformation. Section 4.3 fits a (in 3D ) map on quadratic terms of , which allows bending and twisting of a single cluster.
- Clusters. Section 4.4 divides the particles into overlapping clusters, matches each one, and averages the goals of a particle over its clusters, so that the body can bend.
- Plasticity. Section 4.5 updates the rest shape from the linear part of the fit when the deformation is large, so the body keeps a dent.
- Lattice shape matching. Rivers and James (2007) matched many small regions of a regular lattice, with fast summation over the regions, for detailed soft bodies.
- As a PBD constraint. Shape matching is often projected as one constraint in a PBD or XPBD solver, together with distance and collision constraints.
- Related energies. The same best rotation appears in the as-rigid-as-possible energy, in corotational FEM and in the local step of projective dynamics.
When to use it
Use shape matching for soft objects in games and interactive tools that must never fail and must cost little: jelly, rubber toys, soft props and objects made of many particles without a mesh. It is also a simple way to make a set of particles behave as a rigid body ( with one cluster).
Do not use it when the material must have a physical stiffness or must behave the same at different step sizes; use corotational FEM or projective dynamics then. One cluster cannot bend; use clusters or the quadratic mode for long objects.
Pitfalls
- Reflections. The paper's formula gives a reflection when , which turns the body inside out. Use the best rotation, as the code does in 2D, or fix the sign of the SVD in 3D.
- Degenerate rest shapes. If the rest particles lie on a line (in 3D, a plane), is singular and the linear mode fails. The rotation can still be undefined when is close to zero.
- Volume normalization. Without dividing by the root of the linear mode lets the body grow or shrink; with the root is not defined and the code falls back to .
- Step size changes the look. Changing with the same changes the period in seconds.
- No damping. Without added damping, a body that was hit keeps wobbling.
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
meshless_shape_matching.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meshless-shape-matching/. The authors are listed in prov/CV2R4Y.jsonl.
"""Meshless shape matching (Mueller, Heidelberger, Teschner and Gross 2005), in 2D.
A body is a set of particles with masses m_i and rest positions x0_i. In each
step the goal positions are the best rigid (or linear) map of the rest shape
onto the current positions x_i, in the mass weighted least squares sense:
q_i = x0_i - x0_cm, p_i = x_i - x_cm, A_pq = sum m_i p_i q_i^T,
R = the rotation factor of the polar decomposition of A_pq,
g_i = G q_i + x_cm with G = R (rigid) or G = beta A~ + (1 - beta) R (linear),
where A = A_pq (sum m_i q_i q_i^T)^(-1) and A~ = A / sqrt(det A) has det 1 in
2D (if det A <= 0 the code uses R instead of A~). The step is equation (9)
of the paper:
v_i <- v_i + alpha (g_i - x_i) / dt + dt f_ext,i / m_i, x_i <- x_i + dt v_i.
The 2D rotation is the closed form of anim.polar, the rotation that maximizes
trace(R^T A_pq). It is always a rotation, also when det A_pq < 0. A step
costs Theta(n) time and the memory is Theta(n) for n particles.
"""
import math
from anim import det, inv, mul, polar
GRAVITY = (0.0, -9.81)
def center(x, m):
total = sum(m)
return (sum(mi * p[0] for mi, p in zip(m, x)) / total, sum(mi * p[1] for mi, p in zip(m, x)) / total)
def outer_sum(m, a, b):
"""sum m_i a_i b_i^T as a 2 by 2 list of rows."""
s = [[0.0, 0.0], [0.0, 0.0]]
for mi, u, w in zip(m, a, b):
for r in range(2):
for c in range(2):
s[r][c] += mi * u[r] * w[c]
return s
class RestShape:
"""The rest positions with their center of mass, the vectors q_i and (sum m q q^T)^(-1)."""
def __init__(self, x0, m):
self.m = list(m)
self.cm = center(x0, m)
self.q = [(p[0] - self.cm[0], p[1] - self.cm[1]) for p in x0]
self.aqq = inv(outer_sum(self.m, self.q, self.q))
def match(rest, x, mode="rigid", beta=0.0):
"""Return (G, x_cm): the matrix of the goal map and the current center of mass."""
m = rest.m
xcm = center(x, m) # @line L1
p = [(u[0] - xcm[0], u[1] - xcm[1]) for u in x]
apq = outer_sum(m, p, rest.q) # @line L2
r, _ = polar(apq) # @line L3
if mode == "rigid":
return r, xcm
a = mul(apq, rest.aqq)
d = det(a)
if d <= 0.0:
a_vol = r
else:
s = 1.0 / math.sqrt(d)
a_vol = [[s * a[0][0], s * a[0][1]], [s * a[1][0], s * a[1][1]]]
g = [[beta * a_vol[i][j] + (1.0 - beta) * r[i][j] for j in range(2)] for i in range(2)] # @line L4
return g, xcm
def goals(rest, x, mode="rigid", beta=0.0):
g, xcm = match(rest, x, mode, beta)
return [(g[0][0] * q[0] + g[0][1] * q[1] + xcm[0], g[1][0] * q[0] + g[1][1] * q[1] + xcm[1])
for q in rest.q] # @line L5
def step(rest, x, v, alpha, dt, mode="rigid", beta=0.0, gravity=GRAVITY):
"""One step of equation (9). Return (x, v)."""
g = goals(rest, x, mode, beta)
v_new = [(u[0] + alpha * (gi[0] - xi[0]) / dt + dt * gravity[0], u[1] + alpha * (gi[1] - xi[1]) / dt + dt * gravity[1])
for u, gi, xi in zip(v, g, x)] # @line L6
x_new = [(xi[0] + dt * u[0], xi[1] + dt * u[1]) for xi, u in zip(x, v_new)] # @line L7
return x_new, v_new
def momentum(x, v, m):
"""Return (P_x, P_y, L) with L = sum m x cross v about the origin."""
px = sum(mi * u[0] for mi, u in zip(m, v))
py = sum(mi * u[1] for mi, u in zip(m, v))
ang = sum(mi * (xi[0] * u[1] - xi[1] * u[0]) for mi, xi, u in zip(m, x, v))
return px, py, ang
def fit_error(rest, x, g):
"""sum m_i |G q_i + x_cm - x_i|^2 for a 2 by 2 matrix G."""
xcm = center(x, rest.m)
e = 0.0
for mi, q, xi in zip(rest.m, rest.q, x):
gx = g[0][0] * q[0] + g[0][1] * q[1] + xcm[0] - xi[0]
gy = g[1][0] * q[0] + g[1][1] * q[1] + xcm[1] - xi[1]
e += mi * (gx * gx + gy * gy)
return e
def amplification(alpha, dt):
"""The matrix of equation (11) for one particle and a fixed goal, on (v, x - g)."""
return [[1.0, -alpha / dt], [dt, 1.0 - alpha]]
test_meshless_shape_matching.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meshless-shape-matching/. The authors are listed in prov/CV2R4Y.jsonl.
"""Tests of shape matching against an angle scan, closed forms and conservation laws."""
import cmath
import math
import random
from anim import rot2
import meshless_shape_matching as sm
def random_body(rng, count):
x0 = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(count)]
m = [rng.uniform(0.5, 2.0) for _ in range(count)]
return x0, m
def apply(f, t, pts):
return [(f[0][0] * p[0] + f[0][1] * p[1] + t[0], f[1][0] * p[0] + f[1][1] * p[1] + t[1]) for p in pts]
def test_example_square():
x0 = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
rest = sm.RestShape(x0, [1.0] * 4)
x = [(2.0 * p[0], p[1]) for p in x0]
g = sm.goals(rest, x)
assert max(math.dist(a, b) for a, b in zip(g, x0)) < 1e-15
x1, v1 = sm.step(rest, x, [(0.0, 0.0)] * 4, 0.5, 0.1, gravity=(0.0, 0.0))
assert math.dist(x1[2], (1.5, 1.0)) < 1e-14 and math.dist(v1[2], (-5.0, 0.0)) < 1e-13
gl = sm.goals(rest, x, "linear", 1.0)
assert math.dist(gl[2], (math.sqrt(2.0), 1.0 / math.sqrt(2.0))) < 1e-14
def test_rotation_is_the_best_rigid_fit():
"""The polar rotation of A_pq beats every angle of a fine scan."""
rng = random.Random(21)
for _ in range(30):
x0, m = random_body(rng, 6)
rest = sm.RestShape(x0, m)
x = [(p[0] + rng.gauss(0, 0.5), p[1] + rng.gauss(0, 0.5)) for p in x0]
r, _ = sm.match(rest, x)
best = sm.fit_error(rest, x, r)
assert abs(r[0][0] * r[1][1] - r[0][1] * r[1][0] - 1.0) < 1e-12
for k in range(720):
assert best <= sm.fit_error(rest, x, rot2(2.0 * math.pi * k / 720)) + 1e-12
def test_rigid_pose_has_no_pull():
rng = random.Random(22)
for _ in range(50):
x0, m = random_body(rng, 5)
rest = sm.RestShape(x0, m)
x = apply(rot2(rng.uniform(-math.pi, math.pi)), (rng.uniform(-3, 3), rng.uniform(-3, 3)), x0)
for mode in ("rigid", "linear"):
g = sm.goals(rest, x, mode, rng.uniform(0.0, 1.0))
assert max(math.dist(a, b) for a, b in zip(g, x)) < 1e-12
def test_linear_mode_recovers_the_affine_map():
"""For x = F x0 + t with det F > 0, A = F and A~ = F / sqrt(det F)."""
rng = random.Random(23)
for _ in range(50):
x0, m = random_body(rng, 5)
rest = sm.RestShape(x0, m)
f = [[rng.uniform(0.5, 2.0), rng.uniform(-0.5, 0.5)], [rng.uniform(-0.5, 0.5), rng.uniform(0.5, 2.0)]]
d = f[0][0] * f[1][1] - f[0][1] * f[1][0]
x = apply(f, (rng.uniform(-1, 1), rng.uniform(-1, 1)), x0)
g, _ = sm.match(rest, x, "linear", 1.0)
for i in range(2):
for j in range(2):
assert abs(g[i][j] - f[i][j] / math.sqrt(d)) < 1e-10
def test_momentum_is_kept_exactly():
rng = random.Random(24)
for mode, beta in (("rigid", 0.0), ("linear", 0.5), ("linear", 1.0)):
x0, m = random_body(rng, 8)
rest = sm.RestShape(x0, m)
x = [(p[0] + rng.gauss(0, 0.3), p[1] + rng.gauss(0, 0.3)) for p in x0]
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in x0]
p0 = sm.momentum(x, v, m)
for _ in range(200):
x, v = sm.step(rest, x, v, 0.3, 0.02, mode, beta, gravity=(0.0, 0.0))
p1 = sm.momentum(x, v, m)
scale = sum(mi * math.hypot(*u) for mi, u in zip(m, v)) * (1.0 + max(math.hypot(*p) for p in x))
assert max(abs(a - b) for a, b in zip(p0, p1)) < 1e-10 * scale
def test_alpha_one_reaches_the_goals():
rng = random.Random(25)
x0, m = random_body(rng, 6)
rest = sm.RestShape(x0, m)
x = [(p[0] + rng.gauss(0, 0.3), p[1] + rng.gauss(0, 0.3)) for p in x0]
g = sm.goals(rest, x)
x1, _ = sm.step(rest, x, [(0.0, 0.0)] * 6, 1.0, 0.05, gravity=(0.0, 0.0))
assert max(math.dist(a, b) for a, b in zip(x1, g)) < 1e-14
def test_fixed_goal_amplification_has_unit_eigenvalues():
for alpha in (0.01, 0.1, 0.5, 0.9, 1.0):
for dt in (1e-3, 0.01, 0.1, 1.0):
a = sm.amplification(alpha, dt)
tr = a[0][0] + a[1][1]
dt_ = a[0][0] * a[1][1] - a[0][1] * a[1][0]
disc = cmath.sqrt(tr * tr - 4.0 * dt_)
for lam in ((tr + disc) / 2.0, (tr - disc) / 2.0):
assert abs(abs(lam) - 1.0) < 1e-12
def test_oscillation_neither_grows_nor_decays():
"""A stretched square keeps the size of its oscillation over 2000 steps (measured)."""
x0 = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
rest = sm.RestShape(x0, [1.0] * 4)
x = [(2.0 * p[0], p[1]) for p in x0]
v = [(0.0, 0.0)] * 4
amp = []
for n in range(2000):
x, v = sm.step(rest, x, v, 0.2, 0.01, gravity=(0.0, 0.0))
amp.append(max(math.dist(a, b) for a, b in zip(x, sm.goals(rest, x))))
first = max(amp[:200])
last = max(amp[-200:])
assert 0.95 < last / first < 1.05
def test_center_of_mass_falls_as_symplectic_euler():
rng = random.Random(26)
x0, m = random_body(rng, 5)
rest = sm.RestShape(x0, m)
x = [(p[0] + rng.gauss(0, 0.2), p[1] + rng.gauss(0, 0.2)) for p in x0]
c0 = sm.center(x, m)
v = [(0.0, 0.0)] * 5
for _ in range(10):
x, v = sm.step(rest, x, v, 0.4, 0.1)
c1 = sm.center(x, m)
assert abs(c1[1] - c0[1] + 5.3955) < 1e-12 and abs(c1[0] - c0[0]) < 1e-12
History
Müller, Heidelberger, Teschner and Gross introduced meshless shape matching at SIGGRAPH 2005, with the rigid, linear and quadratic modes, clusters and plasticity. The best rotation of two point sets goes back to the orthogonal Procrustes problem and to Kabsch (1976). Rivers and James (2007) extended the idea to lattice shape matching, and later position based solvers took shape matching in as one more kind of constraint.
References
- Matthias Müller, Bruno Heidelberger, Matthias Teschner and Markus Gross, Meshless deformations based on shape matching, ACM Transactions on Graphics 24(3), 471-478, 2005 (SIGGRAPH 2005), Section 3.3 (the optimal rotation, equations (5) to (8)), Section 3.4 (the integration, equations (9) to (11)), Section 4 (linear and quadratic deformations, clusters and plasticity)
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 CV2R4Y Edit this page History Report an error Markdown