Algorithmadvanced
Delta mush
Also called direct delta mush.
Smooths the skinned mesh and adds back the rest detail, stored as offsets in frames of the smoothed rest mesh. It hides the faults of rough skinning weights.
- Solves
- Character skinning
- Time
- O(j + n k + K (n + f)) frameO(K (n + f)) precompute
- Space
- O(n + f) extra
- Where
- K = the number of smoothing steps; f = the number of triangles; j = the number of joints; k = the largest number of joints per vertex; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Delta mush is a correction step that runs after a skinning method such as linear blend skinning. It smooths the skinned mesh until the faults of the skinning are gone, and then adds back the detail that the smoothing removed. That detail comes from the rest pose: the rest mesh is smoothed in the same way once, and the difference between each rest vertex and its smoothed position is the delta of the vertex. The delta is stored in a frame of the smoothed rest surface at the vertex, so it turns with the surface when the mesh moves:
where and are the smoothed rest and skinned meshes, and and are their orthonormal frames at vertex . Joe Mancewicz, Matt Derksen, Hans Rijpkema and Cyrus Wilson described it in 2014. It needs no extra data from an artist, so rough weights, even weights of only 0 and 1, give a smooth result.
In plain words
Skinning with rough weights gives a mesh with dents and sharp folds at the joints. If you blur that mesh, the dents go away, but so do the small shapes of the model, such as wrinkles and muscles. Delta mush blurs the model once in its rest pose and records, for each point, how far the point sits from its blurred place. It records this offset in a small frame that sits on the blurred surface, so the offset turns when the surface turns. In each frame of the animation, it skins the mesh, blurs it the same way, and puts each recorded offset back. The small shapes come back, and the dents of the skinning stay blurred away.
The problem
The input is the rest mesh with its triangles, the skinning weights, and in each frame the skinning transforms of the pose (see bind pose). The output is the deformed mesh. The goal is a smooth deformation near the joints that keeps the detail of the rest mesh, with weights that need little painting. This is the character skinning problem with a correction step.
The algorithm
The smoothing is steps of uniform Laplacian smoothing with the step , done for all vertices at once, as in the Jacobi method: each vertex moves the fraction of the way to the mean of its neighbors. The frame of a vertex has the normal , the normalized sum of the cross products of the triangles around it; the tangent , the edge to a fixed neighbor with its part along removed, normalized; and .
DELTA-MUSH(V, triangles, W, C)- 1
Ṽ ← SMOOTH(V) ▷ precomputation, once - 2
for each vertex i: F_i ← FRAME(Ṽ, i); δ_i ← F_iᵀ (v_i - ṽ_i) - 3
U ← the skinned mesh, here u_i = Σ_j w_ij C_j v_i ▷ each frame - 4
Ũ ← SMOOTH(U) - 5
for each vertex i: G_i ← FRAME(Ũ, i) - 6
u'_i ← ũ_i + G_i δ_i - 7
return U' SMOOTH(X)- 8
repeat K times: x_i ← x_i + λ (mean of x_k over the neighbors k of i - x_i), for all i at once FRAME(X, i)- 9
n ← normalized Σ of the face cross products at i; t ← normalized (e - (e·n) n) for the edge e to the first neighbor; return (t, n × t, n)
Lines L1 and L2 depend only on the rest mesh, so they run once. Line L6 is the only use of the deltas: the frame of the smoothed pose carries the rest detail to its place in the pose. Any skinning can give in line L3; the code of this page takes LBS by default and also accepts a given deformed mesh. The tuning values of the code are and .
Example
Take an open tube of radius along the axis from to , with 12 vertices around and 13 rings. Joint 0 is at the origin and joint 1 at , and the weight of joint 1 rises smoothly over . The table gives the mean distance of the middle ring, at , from the joint ; in the rest pose it is .
| pose of joint 1 | LBS | delta mush on LBS |
|---|---|---|
| twist by about | ||
| twist by about | ||
| bend by about through the joint |
In the bend, delta mush keeps more of the radius than LBS. In the twist by , LBS puts the whole middle ring on the axis, and delta mush keeps the tube open. In the twist by , it is a little worse than LBS: it does not cure the candy wrapper artifact. Even when the input twists each ring rigidly, so that every ring keeps the radius , the output middle ring has the radius , and the output moves up to from the input.
With rigid weights, 0 below and 1 above, and a bend by , LBS tears the tube between the rings at and , whose rest gap is . The worst change of that gap is with LBS and with delta mush. These values come from the code of this page and are measurements, not proved properties.
Correctness
The proofs are in proofs/correctness.md; they are proved properties in exact arithmetic.
- SMOOTH is the linear map with the random-walk Laplacian ; each row of sums to 1.
- The frames are orthonormal and right-handed wherever the normal sum is not zero and the tangent edge is not along the normal.
- In the bind pose the output is the rest mesh exactly, because ; the same holds for any skinning that returns the rest mesh.
- If all the joints move by one rigid motion , the output is : the smoothing commutes with affine maps, and the frames turn with the mesh.
These do not say that the output is close to a "true" deformation; how well the method hides the faults of the skinning is a measurement, as in the example.
Proof: Delta mush is a linear smoothing with orthonormal frames, gives the rest mesh in the bind pose, and commutes with a common rigid motionfull
We use the notation of the page. The arithmetic is exact, every vertex has at least one neighbor, and the weights of each vertex sum to 1. Write the positions of a mesh as the rows of an matrix , the adjacency matrix as , and the diagonal matrix of the degrees as .
The smoothing
Lemma 1. One step of line L8 is with and , so SMOOTH is . Each row of , and so each row of , sums to 1.
Proof. Row of is the mean of the neighbors of , so row of is the update of line L8; all rows use the old , as in the code. The rows of sum to 1, so the rows of sum to 0 and those of sum to 1. If the rows of and sum to 1, then , so by induction the rows of sum to 1.
Lemma 2. For an affine map , applied to each vertex, .
Proof. Let be the entries of . Vertex of the smoothed is , by Lemma 1.
The frames
Lemma 3. If the normal sum at vertex is not zero and the edge to the first neighbor is not parallel to it, line L9 returns a right-handed orthonormal frame .
Proof. is a unit vector. is not zero, because is not parallel to , and its dot product with is ; so is a unit vector orthogonal to . is orthogonal to and , and . Finally , so the frame is right-handed.
So the matrix is a rotation, and .
Lemma 4. For a rigid motion with a rotation, the frame of vertex of is , where is the frame of .
Proof. Each difference of two vertices turns to times the old difference, and for a rotation. So each face cross product, and their sum , turns to times the old one, and since , the normal turns to . The edge turns to , and , so the tangent turns to . Then .
Bind pose and rigid motions
Lemma 5. If the skinned mesh of line L3 is the rest mesh, , the output is . In particular this holds in the bind pose, where every and .
Proof. , so for every , and line L6 gives by Lemma 3.
Lemma 6. If every is the same rigid motion , the output is for every vertex.
Proof. Line L3 gives , because the weights sum to 1. By Lemma 2, , and by Lemma 4, . So line L6 gives .
What is not proved
The lemmas say nothing about how close the output is to a good deformation in a general pose. The smoothing of a bent or twisted mesh does not shrink it in the same way as the rest mesh, so the deltas restore the rest shape only in part; the tables of the page are measurements.
Complexity
One smoothing step visits each vertex and its neighbors, which costs on a triangle mesh, so SMOOTH costs . The frames cost . The precomputation costs , and each frame costs for LBS plus for the correction. The extra space is for the neighbor lists, the deltas and the work arrays. The cost grows with , so a large for a wide blur makes delta mush much slower than LBS.
Properties
- It is a correction step: any skinning can come before it, and the bind pose and common rigid motions pass through unchanged (proved).
- It keeps the detail of the rest mesh in the local frames, so wrinkles and other small shapes move with the surface.
- It hides rough weights: with weights of only 0 and 1 the joint still bends smoothly (a measurement on the example).
- It does not keep volume in twists: on the tube it is no better than LBS at (a measurement).
- It is global within the reach of the smoothing: a vertex depends on the skinned positions of all vertices within about edges.
- , and the choice of the tangent edge are tuning values.
Variants and improvements
- Masks. Production tools let the artist scale the correction per vertex, so that some regions follow the skinning directly.
- Other smoothing. Taubin smoothing shrinks the mesh less per step, and a cotangent Laplacian depends less on the triangulation than the uniform one.
- Direct delta mush. Binh Huy Le and J. P. Lewis (2019) rewrote the method as a direct skinning with precomputed data per vertex and joint, which avoids the smoothing at run time; it is a different method and has its own trade-offs.
- Better input. Since delta mush corrects any skinning, dual quaternion skinning can give in line L3, but the example shows that a good input alone does not keep the twist radius.
- Other corrections. Implicit skinning corrects the skinning with fields of the bones and models contact; Laplacian surface editing also stores detail as differential coordinates.
When to use it
Use it when the weights are rough or the rig is in early work, and smooth joints with the rest detail kept matter more than the cost per frame. For twist-heavy joints, add a twist bone or another fix, since delta mush does not keep the radius in a twist.
Pitfalls
- Shrinking. The smoothing shrinks the mesh, and the deltas restore the rest shape only where the deformation is close to rigid; with large the results can drift.
- Degenerate frames. A vertex whose normal sum is near zero, or whose tangent edge is near the normal, has an unstable frame, and its delta can jump.
- Boundaries. On an open boundary the uniform smoothing pulls vertices inward along the surface; the deltas restore this in the rest pose, but a pose that stretches the boundary changes it.
- Topology. The neighbor lists and the frames depend on the mesh connectivity, so the rest mesh and the skinned mesh must have the same triangles and the same vertex order.
- Cost. A wide blur needs a large , and the cost per frame grows with it.
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
delta_mush.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-mush/. The authors are listed in prov/118N6H.jsonl.
"""Delta mush (Mancewicz, Derksen, Rijpkema and Wilson 2014).
Precomputation, once in the rest pose:
1. Smooth the rest mesh V into S(V) by K steps of uniform Laplacian
smoothing with the step lam.
2. At each smoothed vertex build an orthonormal frame F_i (tangent,
bitangent, normal), and store the delta d_i = F_i^T (v_i - S(V)_i), the
detail that the smoothing removed, in that frame.
Each frame:
3. Deform the mesh with any skinning, here linear blend skinning: U.
4. Smooth U into S(U) with the same K and lam.
5. Build the frames G_i of S(U) and add back the details:
u_i' = S(U)_i + G_i d_i.
The frame of vertex i has the normal n_i (the sum of the cross products of
the faces around i, normalized), the tangent t_i (the edge to the first
neighbor of i in the vertex list, with its part along n_i removed,
normalized) and b_i = n_i x t_i. K and lam are tuning values.
"""
from anim import add, cross, dot, normalize, scale, sub
LAM = 0.5
ITERS = 10
def neighbors(n, triangles):
"""Return the sorted neighbor lists of the n vertices of a triangle mesh."""
nb = [set() for _ in range(n)]
for a, b, c in triangles:
nb[a] |= {b, c}
nb[b] |= {a, c}
nb[c] |= {a, b}
return [sorted(s) for s in nb]
def smooth(points, nbrs, lam=LAM, iters=ITERS):
"""K steps of x_i <- x_i + lam (mean of the neighbors - x_i), all at once."""
x = [tuple(p) for p in points]
for _ in range(iters): # @line L8
new = []
for i, p in enumerate(x):
m = (0.0, 0.0, 0.0)
for k in nbrs[i]:
m = add(m, x[k])
m = scale(m, 1.0 / len(nbrs[i]))
new.append(add(p, scale(sub(m, p), lam)))
x = new
return x
def frames(points, triangles, nbrs):
"""Return the frame of each vertex as the columns (t, b, n)."""
nsum = [(0.0, 0.0, 0.0) for _ in points]
for a, b, c in triangles:
fn = cross(sub(points[b], points[a]), sub(points[c], points[a]))
for v in (a, b, c):
nsum[v] = add(nsum[v], fn)
out = []
for i, p in enumerate(points):
nrm = normalize(nsum[i]) # @line L9
e = sub(points[nbrs[i][0]], p)
t = normalize(sub(e, scale(nrm, dot(e, nrm))))
out.append((t, cross(nrm, t), nrm))
return out
def to_local(f, v):
return (dot(f[0], v), dot(f[1], v), dot(f[2], v))
def to_world(f, d):
return add(add(scale(f[0], d[0]), scale(f[1], d[1])), scale(f[2], d[2]))
def precompute(rest, triangles, lam=LAM, iters=ITERS):
"""Return (nbrs, deltas) of the rest mesh."""
nbrs = neighbors(len(rest), triangles)
s = smooth(rest, nbrs, lam, iters) # @line L1
fr = frames(s, triangles, nbrs)
deltas = [to_local(fr[i], sub(rest[i], s[i])) for i in range(len(rest))] # @line L2
return nbrs, deltas
def lbs(vertices, weights, palette):
"""Linear blend skinning with sparse weights (joint, weight)."""
out = []
for v, wi in zip(vertices, weights):
p = (0.0, 0.0, 0.0)
for j, w in wi:
m = palette[j]
q = tuple(m[r][0] * v[0] + m[r][1] * v[1] + m[r][2] * v[2] + m[r][3] for r in range(3))
p = add(p, scale(q, w))
out.append(p)
return out
def delta_mush(rest, triangles, weights, palette, pre=None, lam=LAM, iters=ITERS, deformed=None):
"""Return the delta mush result of one frame.
deformed: the skinned mesh to correct; if None, linear blend skinning of
rest with weights and palette is used.
"""
if pre is None:
pre = precompute(rest, triangles, lam, iters)
nbrs, deltas = pre
u = deformed if deformed is not None else lbs(rest, weights, palette) # @line L3
su = smooth(u, nbrs, lam, iters) # @line L4
fr = frames(su, triangles, nbrs) # @line L5
out = [add(su[i], to_world(fr[i], deltas[i])) for i in range(len(rest))] # @line L6
return out # @line L7
test_delta_mush.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delta-mush/. The authors are listed in prov/118N6H.jsonl.
"""Tests of delta mush.
They check the smoothing against powers of the dense smoothing matrix, the
frames, the bind pose, a common rigid motion, a full twist of a tube (the
middle ring does not collapse to the axis), a bend of the tube (the middle
ring keeps more of its radius than with linear blend skinning), and the
case of rigid weights.
"""
import math
import random
import anim
from delta_mush import delta_mush, frames, lbs, neighbors, precompute, smooth
def smoothstep(x):
x = min(1.0, max(0.0, x))
return x * x * (3.0 - 2.0 * x)
def tube(nr=12, ny=13, radius=0.5, length=2.0, rigid=False):
"""An open tube along y with two joints, at y = 0 and y = 1."""
verts, weights = [], []
for r in range(ny):
y = length * r / (ny - 1)
w1 = (1.0 if y > 1.0 else 0.0) if rigid else smoothstep((y - 0.6) / 0.8)
for k in range(nr):
a = 2.0 * math.pi * k / nr
verts.append((radius * math.cos(a), y, radius * math.sin(a)))
weights.append([jw for jw in ((0, 1.0 - w1), (1, w1)) if jw[1] > 0.0])
tris = []
for r in range(ny - 1):
for k in range(nr):
a, b = r * nr + k, r * nr + (k + 1) % nr
c, d = a + nr, b + nr
tris += [(a, c, b), (b, c, d)]
return verts, tris, weights
def rand_T(rng):
q = anim.q_normalize([rng.gauss(0.0, 1.0) for _ in range(4)])
return anim.make_T(anim.q_to_mat3(q), tuple(rng.uniform(-2.0, 2.0) for _ in range(3)))
def about(axis, angle, c):
r = anim.q_to_mat3(anim.q_from_axis_angle(axis, angle))
return anim.make_T(r, anim.sub(c, anim.matvec(r, c)))
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def ring_radius(points, ring, nr, center):
pts = points[ring * nr : (ring + 1) * nr]
return sum(anim.norm(anim.sub(p, center)) for p in pts) / nr
def test_smoothing_matches_matrix_power():
rng = random.Random(1)
verts, tris, _ = tube(nr=6, ny=5)
verts = [anim.add(v, tuple(rng.uniform(-0.05, 0.05) for _ in range(3))) for v in verts]
nb = neighbors(len(verts), tris)
n = len(verts)
m = anim.eye(n)
for i in range(n):
for k in nb[i]:
m[i][k] += 0.4 / len(nb[i])
m[i][i] -= 0.4
p = anim.eye(n)
for _ in range(7):
p = anim.mul(m, p)
ref = anim.mul(p, [list(v) for v in verts])
got = smooth(verts, nb, 0.4, 7)
for a, b in zip(got, ref):
assert close(a, b, 1e-12)
def test_frames_are_orthonormal():
rng = random.Random(2)
verts, tris, _ = tube()
verts = [anim.add(v, tuple(rng.uniform(-0.05, 0.05) for _ in range(3))) for v in verts]
nb = neighbors(len(verts), tris)
for t, b, n in frames(smooth(verts, nb), tris, nb):
for u in (t, b, n):
assert abs(anim.norm(u) - 1.0) < 1e-12
assert abs(anim.dot(t, b)) < 1e-12 and abs(anim.dot(t, n)) < 1e-12 and abs(anim.dot(b, n)) < 1e-12
assert close(anim.cross(t, b), n, 1e-12)
# the normals of the tube point outward
for v, (_, _, n) in zip(verts, frames(verts, tris, nb)):
assert n[0] * v[0] + n[2] * v[2] > 0.0
def test_bind_pose_gives_rest_mesh():
verts, tris, weights = tube()
out = delta_mush(verts, tris, weights, [anim.eye(4), anim.eye(4)])
for a, b in zip(out, verts):
assert close(a, b, 1e-12)
def test_common_rigid_motion():
rng = random.Random(3)
verts, tris, weights = tube()
pre = precompute(verts, tris)
for _ in range(3):
g = rand_T(rng)
out = delta_mush(verts, tris, weights, [g, g], pre=pre)
for a, v in zip(out, verts):
assert close(a, anim.T_apply(g, v), 1e-9)
def test_full_twist_does_not_collapse_to_the_axis():
# LBS puts the middle ring of a twist by pi on the axis; delta mush keeps
# it open, but it does not restore the rest radius (see the page)
verts, tris, weights = tube()
pre = precompute(verts, tris)
pal = [anim.eye(4), about((0.0, 1.0, 0.0), math.pi, (0.0, 0.0, 0.0))]
out = delta_mush(verts, tris, weights, pal, pre=pre)
ref = lbs(verts, weights, pal)
c = (0.0, 1.0, 0.0)
assert ring_radius(ref, 6, 12, c) < 1e-9
assert 0.25 < ring_radius(out, 6, 12, c) < 0.5
def test_bend_keeps_more_radius_than_lbs():
verts, tris, weights = tube()
pre = precompute(verts, tris)
pal = [anim.eye(4), about((0.0, 0.0, 1.0), math.pi / 2, (0.0, 1.0, 0.0))]
out = delta_mush(verts, tris, weights, pal, pre=pre)
ref = lbs(verts, weights, pal)
c = (0.0, 1.0, 0.0)
assert abs(ring_radius(out, 6, 12, c) - 0.5) < abs(ring_radius(ref, 6, 12, c) - 0.5)
def test_rigid_weights_are_smoothed():
# with weights of 0 or 1 linear blend skinning tears the tube at the
# joint; delta mush gives a gap between rings close to the rest one
verts, tris, weights = tube(rigid=True)
pal = [anim.eye(4), about((0.0, 0.0, 1.0), math.pi / 3, (0.0, 1.0, 0.0))]
out = delta_mush(verts, tris, weights, pal)
ref = lbs(verts, weights, pal)
rest_edge = anim.norm(anim.sub(verts[6 * 12], verts[7 * 12]))
def worst(points):
return max(abs(anim.norm(anim.sub(points[6 * 12 + k], points[7 * 12 + k])) - rest_edge) for k in range(12))
assert worst(out) < worst(ref)
def test_any_deformer_and_identity():
# the correction of the rest mesh itself is the rest mesh, whatever the
# weights and the palette
rng = random.Random(4)
verts, tris, weights = tube()
out = delta_mush(verts, tris, weights, [rand_T(rng), rand_T(rng)], deformed=list(verts))
for a, b in zip(out, verts):
assert close(a, b, 1e-12)
History
Joe Mancewicz, Matt Derksen, Hans Rijpkema and Cyrus Wilson of Rhythm and Hues presented delta mush at DigiPro 2014. Commercial animation tools soon added it as a deformer. In 2019 Binh Huy Le and J. P. Lewis turned it into direct delta mush, a direct skinning method with precomputed data.
References
- Joe Mancewicz, Matt L. Derksen, Hans Rijpkema and Cyrus A. Wilson, Delta mush, smoothing deformations while preserving detail, Proceedings of the Fourth Symposium on Digital Production (DigiPro '14), pages 7-11, 2014, the smoothing of the rest mesh and the skinned mesh, the deltas in local frames, and the examples
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 118N6H Edit this page History Report an error Markdown