Algorithmadvanced
Automatic rigging by heat diffusion
Also called Pinocchio rigging, bone heat weights.
Embed a template skeleton into a character mesh and compute skinning weights by heat diffusion from each bone over the surface.
- Solves
- Character skinning
- Time
- O(B C^2 n + J C^J log C) embeddingO(n^2 B + n^3) weights
- Space
- O(B C^2 + J C^J + n^2) extra
- Where
- B = the number of bones; C = the number of candidate joint positions; J = the number of joints; n = the number of surface vertices
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Automatic rigging takes a character mesh and a template skeleton, and returns the skeleton fitted inside the mesh together with skinning weights for linear blend skinning. Baran and Popović (2007) built it in two parts, in a system that they called Pinocchio. The first part places the joints: it searches over a discrete set of points inside the mesh for the placement with the smallest sum of penalties, and then refines the result. The second part computes the weights: each bone acts as a heat source, the heat spreads over the surface, and the steady state temperature of the bone at a vertex is its weight. The weights are smooth, nonnegative and sum to 1, and they stay low on parts of the body that the bone cannot see.
In plain words
To animate a character, you need a skeleton inside it and a rule that tells each vertex how much it follows each bone. This method does both from a template, such as a generic human skeleton. It first tries many ways to put the template joints inside the shape and scores each one: are the bones as long as they should be, do they point the right way, do they stay inside? A best-first search finds the placement with the best score without trying all of them. Then it heats each bone and lets the heat flow over the skin. A vertex near the upper arm gets hot from the upper arm bone and stays cold for the leg bones. Heat flows along the surface, not through the air, so a hand that rests on a leg does not get weight from the leg.
The problem
The input is a closed surface mesh with vertices , , and a template skeleton: a tree of joints with a rest offset for the bone from the parent of to . The output is a position for every joint inside the mesh and a weight per bone and vertex , with .
For the embedding, fix a set of candidate points inside the mesh. An embedding assigns a candidate to each joint, and its cost is , a sum of nonnegative bone penalties. The best embedding has the smallest cost.
For the weights, let be the discrete Laplacian of the surface, the distance from to the nearest bone that is visible from (the segment between them stays inside the mesh), and the diagonal matrix with , or if no bone is visible. Let if bone is one of the nearest visible bones of , else . The weights of bone solve
The algorithm
RIG(mesh, template skeleton, candidates, c)- 1
embed the skeleton (lines L2 to L6), then make one bone per joint and its parent - 2
precompute the penalty of every bone for every pair of candidates, and its minimum low_j - 3
push the empty assignment with the priority low_1 + … + low_J - 4
pop the partial assignment with the smallest g + h, where h = the sum of low_j over the joints not placed yet - 5
if every joint is placed, return it - 6
else for each candidate c: place the next joint at c and push the result with g increased by its bone penalty - 7
build the Laplacian of the surface: the stiffness matrix K and the masses M - 8
for each vertex j: find its nearest visible bones; set H_jj and p^i_j - 9
factor K + M H by Cholesky, once - 10
for each bone i: solve (K + M H) w^i = M H p^i with the factor; return the weights
Lines L2 to L6 are A* search over partial assignments, with joints placed in an order where each parent comes before its children. The heuristic adds the smallest possible penalty of every bone not placed yet, so it never overestimates the remaining cost. The paper builds its candidates from the centers of spheres packed along the medial axis of the mesh and uses a branch and bound search that is close to A*. It then refines the joint positions by a continuous optimization; the code does not.
Lines L7 to L10 are the equation of the problem in the weak form: is the stiffness matrix, so , and multiplying by gives a symmetric system. On a triangle mesh, is the cotangent Laplacian. The matrix does not depend on the bone, so one Cholesky factorization serves all bones.
The code in impl/python works in 2D.
The character is a simple polygon and its surface is the closed boundary, so has the entry for each edge of length , and the mass of a vertex is half the length of its two edges.
The bone penalties are three terms of the same kind as the paper's: the relative length error squared, one minus the cosine of the angle to the template direction, and a fixed penalty when the bone leaves the shape.
The paper uses a larger set of nine penalties.
Example
Take the square with the corners , , , as the surface, with four vertices and four edges of length 2. Bone A is the segment from to , and bone B is the segment from to . The two lower corners have bone A as the nearest visible bone, at the distance , so with , ; the upper corners have bone B at the same distance.
Each vertex has the mass and the stiffness entries and for its two neighbors. By symmetry, . The row of vertex 1 reads , so and .
| vertex | ||||
|---|---|---|---|---|
| 0.9 | 0.9 | 0.1 | 0.1 | |
| 0.1 | 0.1 | 0.9 | 0.9 |
The weights sum to 1 at every vertex, and the heat leaks a little to the far side along the surface. The tests check these numbers.
Correctness
The proofs are in proofs/correctness.md.
- The embedding is optimal. The heuristic is consistent: along an edge of the search tree, grows by a bone penalty, which is at least the that loses. So the first complete assignment that line L4 pops has the smallest cost.
- The system has one solution. If at least one vertex sees a bone, is symmetric positive definite, so line L9 succeeds.
- The weights sum to 1. and at every vertex with , so solves the system with the right side , whose solution is .
- The weights are nonnegative. has nonpositive entries off the diagonal and is positive definite, so its inverse has no negative entries, and the right side has none.
The search is exact for the discrete problem, but the result is only as good as the penalties and the candidates. The heat weights are a model, not the solution of a problem about the best deformation.
Proof: The A* embedding is optimal, and the heat weights exist, are nonnegative and sum to 1full
We use the notation of the page. The arithmetic is exact.
The embedding
The joints are numbered so that , with the root . A node of the search is a partial assignment , and its cost is . Every bone of has both ends placed, because the parent of a placed joint is placed. Let and .
Lemma 1. is admissible and consistent: for every completion of a node, the cost of the completion, and if a child places joint , then .
Proof. A completion adds for every , which gives the first claim. For the child, and .
Theorem 1. The first complete assignment that line L4 pops has the smallest cost.
Proof. Let be an optimal assignment with the cost , and suppose that line L4 pops a complete assignment with the cost . At that time, some prefix of is in the heap: the empty prefix was pushed, and when a prefix is popped, its child on the way to is pushed. By Lemma 1, the priority of that prefix is at most , which is smaller than the priority of (for a complete node ). The heap pops the smallest priority first, so it cannot pop before that prefix, and the same holds for every later prefix of down to itself. So , or another complete node with the priority at most , is popped before , which contradicts the choice of .
The search tree has no repeated states, because a state is a sequence of choices for the joints in a fixed order, so no closed set is needed. Every node popped has priority at most , so the search expands at most the nodes with , and at most nodes.
The heat system
Let be the stiffness matrix of the closed polyline (or of the mesh), the diagonal of positive masses, and diagonal. For the polyline, , with equality exactly for constant on a connected surface; the cotangent Laplacian of a Delaunay mesh has the same two properties.
Lemma 2. If for some , then is symmetric positive definite.
Proof. is symmetric because is and is diagonal. . If it is zero, , so is constant, , and the second term is for the with , so .
So the Cholesky factorization of line L9 exists, and each line L10 has exactly one solution.
Theorem 2. .
Proof. if vertex sees a bone, and the sum is 0 if it sees none, in which case . So . The system is linear, so solves . , because the rows of sum to 0. By Lemma 2 the solution is unique, so .
Theorem 3. for every bone, when the off-diagonal entries of are not positive (always on the polyline, and on a mesh with nonnegative cotangent weights).
Proof. is symmetric positive definite with nonpositive entries off the diagonal, so is a nonsingular M-matrix, and has no negative entries. A direct argument: let be the index of the smallest entry of , and suppose . With , row reads . Each term of the sum is at most 0 because is the smallest entry, and the last term is at most 0 because . The right side is at least 0. So both sides are 0, gives , and for every neighbor with . The neighbors are also minima, and the same argument spreads over the connected surface, so is the constant and everywhere, which contradicts the assumption of Lemma 2.
With Theorem 2, also .
The check value
On the square with side 2, every edge has , so , for the two neighbors, and . Every vertex has its nearest visible bone at the distance , so and . The system for bone A is invariant under the reflection , which swaps vertices 1 and 2 and vertices 3 and 4, so by uniqueness , and by Theorem 2. Row 1: , so , and . Row 3: gives , which holds.
Complexity
The costs are in the real RAM model. The penalty tables take evaluations, and each tests the bone against the edges of the boundary, so . The search can visit up to partial assignments, each with a heap operation of cost , which gives the exponential worst case . A good heuristic and good penalties make the search visit far fewer nodes in practice; in an L-shaped example with 48 candidates and three joints, A* expands 55 nodes instead of the assignments of a brute force search. For the weights, the visibility tests cost , the dense Cholesky factorization , and each solve . The matrix is sparse, so a sparse Cholesky factorization costs much less on real meshes.
Properties
- Automatic: the only inputs are the mesh and a template skeleton.
- Smooth weights: the weights are harmonic away from the vertices with .
- Convex weights: the weights are nonnegative and sum to 1 at every vertex.
- Aware of the surface: heat flows along the surface, and visibility keeps a bone from attaching to a vertex that it cannot see.
- Not local by construction: every weight is positive on the connected part of the surface that holds its heat source, even if it is very small.
Variants and improvements
- Bounded biharmonic weights. Bounded biharmonic weights minimize a biharmonic energy with explicit bounds, which gives smoother weights and supports points and cages as handles.
- Weights from examples. Skinning decomposition fits weights and bones to a sequence of example meshes instead of a template.
- Volumetric weights. Solving the heat equation in the volume instead of on the surface avoids the visibility test, at the price of a volume mesh.
- Other skinning models. The weights also work with dual quaternion skinning.
When to use it
Use automatic rigging when you need a working rig quickly for many characters of the same kind, such as humanoids, and an artist can fix the result afterwards. It works best on closed meshes with a clear shape, where the limbs are separated. Use bounded biharmonic weights if you need smoother weights or other kinds of handles.
Pitfalls
- Bones on the surface. If a bone touches the surface, and is infinite. The code rejects such bones.
- Broken meshes. Holes and parts that are not connected stop the heat from spreading, and a part without a visible bone gets weights only from the parts that it is connected to.
- Visibility near contacts. A hand that touches the hip can see the hip bone, and the weights near the contact need a manual fix.
- Penalties that do not match the shape. A creature with an unusual body plan needs other penalties or another template. In the paper, the search found a correct embedding for most but not all of the test characters.
- The choice of c. A larger makes the weights closer to the nearest bone weights and the joints sharper; a smaller makes the weights smoother. The test with shows that the weights tend to .
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
automatic_rigging.py 225 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/automatic-rigging/. The authors are listed in prov/FM8DXC.jsonl.
"""Automatic rigging by heat diffusion (Baran and Popovic 2007), in 2D.
The character is a simple polygon, and its surface is the closed boundary
polyline. The method has two parts.
1. Embedding. Each joint of a template skeleton is assigned to one of a set
of candidate points inside the shape (the paper uses the centers of
medial spheres). The cost of an assignment is a sum of nonnegative
penalties of the bones. The best assignment is found by a best-first (A*)
search over partial assignments, with an admissible lower bound for the
bones that are not placed yet. The penalties here are a small set of the
same kind as in the paper (length, direction, a bone that leaves the
shape), not the paper's set.
2. Heat weights. For each bone i, the weights w^i on the surface vertices
solve the discrete equation (K + M H) w^i = M H p^i, the weak form of
-Lap w + H w = H p. K is the stiffness matrix of the polyline (1 / length
per edge), M the lumped mass (half the length of the two edges at a
vertex), H_jj = c / d(j)^2 with d(j) the distance from vertex j to the
nearest bone that it can see, and p^i_j = 1 / k if bone i is one of the k
nearest visible bones of j, else 0. A vertex that sees no bone has
H_jj = 0. The matrix does not depend on i, so it is factored once by
Cholesky.
"""
import heapq
import itertools
import math
from anim import cross2, dot, norm, sub
# ---------------------------------------------------------------- geometry
def _orient(a, b, c):
return cross2(sub(b, a), sub(c, a))
def segments_cross(a, b, c, d):
"""Return True if the segments ab and cd cross at a point inside both (proper crossing)."""
o1, o2 = _orient(a, b, c), _orient(a, b, d)
o3, o4 = _orient(c, d, a), _orient(c, d, b)
return o1 * o2 < 0.0 and o3 * o4 < 0.0
def closest_on_segment(p, a, b):
"""Return the point of the segment ab closest to p."""
ab = sub(b, a)
l2 = dot(ab, ab)
if l2 == 0.0:
return a
t = max(0.0, min(1.0, dot(sub(p, a), ab) / l2))
return (a[0] + t * ab[0], a[1] + t * ab[1])
def crosses_boundary(a, b, poly, skip=()):
"""Return True if the segment ab crosses an edge of the closed polygon, skipping edges that touch vertex indices in skip."""
n = len(poly)
for e in range(n):
f = (e + 1) % n
if e in skip or f in skip:
continue
if segments_cross(a, b, poly[e], poly[f]):
return True
return False
# ---------------------------------------------------------------- embedding
def bone_penalty(pa, pc, template, poly, alpha=(1.0, 1.0, 10.0)):
"""Return the nonnegative penalty of a bone placed from pa to pc.
template is the bone vector of the skeleton. The terms are the relative
length error squared, 1 - cos of the angle to the template direction, and
a fixed penalty if the bone leaves the shape.
"""
d = sub(pc, pa)
ld, lt = norm(d), norm(template)
length = ((ld - lt) / lt) ** 2
direction = 1.0 if ld == 0.0 else 1.0 - dot(d, template) / (ld * lt)
outside = 1.0 if crosses_boundary(pa, pc, poly) else 0.0
return alpha[0] * length + alpha[1] * direction + alpha[2] * outside
def embed(parents, offsets, candidates, poly):
"""Return (cost, assignment, expanded) of the best embedding by A* search.
parents[j] is the parent of joint j (-1 for the root, and parents[j] < j);
offsets[j] is the template vector of the bone from parents[j] to j.
assignment[j] is the index of the candidate point of joint j.
"""
nj, nc = len(parents), len(candidates)
table = [None] * nj # @line L2
low = [0.0] * nj
for j in range(1, nj):
table[j] = [
[bone_penalty(candidates[a], candidates[b], offsets[j], poly) for b in range(nc)] for a in range(nc)
]
low[j] = min(min(row) for row in table[j])
rest = [sum(low[j + 1 :]) for j in range(nj)]
heap = [(rest[0], 0.0, 0, ())] # @line L3
count = 1
expanded = 0
while heap:
f, g, _, part = heapq.heappop(heap) # @line L4
if len(part) == nj: # @line L5
return g, list(part), expanded
expanded += 1
j = len(part)
for c in range(nc): # @line L6
g2 = g if j == 0 else g + table[j][part[parents[j]]][c]
heapq.heappush(heap, (g2 + rest[j], g2, count, part + (c,)))
count += 1
raise ValueError("no embedding")
def brute_force_embedding(parents, offsets, candidates, poly):
"""Return (cost, assignment) of the best embedding by trying every assignment."""
nj, nc = len(parents), len(candidates)
best = (math.inf, None)
for part in itertools.product(range(nc), repeat=nj):
cost = sum(bone_penalty(candidates[part[parents[j]]], candidates[part[j]], offsets[j], poly) for j in range(1, nj))
if cost < best[0]:
best = (cost, list(part))
return best
# ---------------------------------------------------------------- heat weights
def stiffness_and_mass(poly):
"""Return (K, m): the stiffness matrix of the closed polyline and the lumped masses."""
n = len(poly)
k = [[0.0] * n for _ in range(n)]
m = [0.0] * n
for e in range(n):
f = (e + 1) % n
le = norm(sub(poly[f], poly[e]))
k[e][e] += 1.0 / le
k[f][f] += 1.0 / le
k[e][f] -= 1.0 / le
k[f][e] -= 1.0 / le
m[e] += 0.5 * le
m[f] += 0.5 * le
return k, m
def nearest_visible(poly, bones, j, rel_tie=1e-9):
"""Return (d, ids): the distance to the nearest visible bones of vertex j and their indices."""
v = poly[j]
dist = []
for i, (a, b) in enumerate(bones):
c = closest_on_segment(v, a, b)
if not crosses_boundary(v, c, poly, skip=(j,)):
dist.append((norm(sub(c, v)), i))
if not dist:
return math.inf, []
d = min(x for x, _ in dist)
return d, [i for x, i in dist if x <= d * (1.0 + rel_tie)]
def cholesky(a):
"""Return the lower triangular L with a = L L^T. Raise ValueError if a is not positive definite."""
n = len(a)
lo = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(lo[i][k] * lo[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
lo[i][i] = math.sqrt(s)
else:
lo[i][j] = s / lo[j][j]
return lo
def cholesky_solve(lo, b):
"""Solve L L^T x = b."""
n = len(lo)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(lo[i][k] * y[k] for k in range(i))) / lo[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(lo[k][i] * x[k] for k in range(i + 1, n))) / lo[i][i]
return x
def heat_system(poly, bones, c=1.0):
"""Return (A, rhs) with A = K + M H and rhs[i] = M H p^i for each bone i."""
n, nb = len(poly), len(bones)
k, m = stiffness_and_mass(poly) # @line L7
a = [row[:] for row in k]
rhs = [[0.0] * n for _ in range(nb)]
for j in range(n):
d, ids = nearest_visible(poly, bones, j) # @line L8
if not ids:
continue
if d == 0.0:
raise ValueError("a bone touches the surface; bones must lie strictly inside")
h = c / (d * d)
a[j][j] += m[j] * h
for i in ids:
rhs[i][j] = m[j] * h / len(ids)
return a, rhs
def heat_weights(poly, bones, c=1.0):
"""Return w with w[i][j] the weight of bone i at vertex j."""
a, rhs = heat_system(poly, bones, c)
lo = cholesky(a) # @line L9
return [cholesky_solve(lo, r) for r in rhs] # @line L10
def rig(poly, parents, offsets, candidates, c=1.0):
"""Return (joints, weights): the embedded joint positions and the heat weights of the bones 1..J-1."""
_, part, _ = embed(parents, offsets, candidates, poly) # @line L1
joints = [candidates[x] for x in part]
bones = [(joints[parents[j]], joints[j]) for j in range(1, len(parents))]
return joints, heat_weights(poly, bones, c)
test_automatic_rigging.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/automatic-rigging/. The authors are listed in prov/FM8DXC.jsonl.
"""Tests of automatic rigging by heat diffusion.
The A* embedding is compared with a brute force search over all
assignments. The Cholesky solve is compared with Gaussian elimination. The
heat weights are nonnegative and sum to 1 at every vertex, also at vertices
that see no bone, they tend to the nearest bone weights as c grows, and the
check value of the page holds.
"""
import random
from anim import norm, solve, sub
from automatic_rigging import (
brute_force_embedding,
cholesky,
cholesky_solve,
embed,
heat_system,
heat_weights,
nearest_visible,
rig,
)
L_SHAPE = [(0.0, -0.3), (2.3, -0.3), (2.3, 2.0), (1.7, 2.0), (1.7, 0.3), (0.0, 0.3)]
U_SHAPE = [(0.0, 0.0), (3.0, 0.0), (3.0, 3.0), (2.0, 3.0), (2.0, 1.0), (1.0, 1.0), (1.0, 3.0), (0.0, 3.0)]
def resample(poly, h):
out = []
n = len(poly)
for e in range(n):
a, b = poly[e], poly[(e + 1) % n]
k = max(1, round(norm(sub(b, a)) / h))
for s in range(k):
out.append((a[0] + (b[0] - a[0]) * s / k, a[1] + (b[1] - a[1]) * s / k))
return out
def inside(poly, p):
c = False
n = len(poly)
for e in range(n):
a, b = poly[e], poly[(e + 1) % n]
if (a[1] > p[1]) != (b[1] > p[1]):
x = a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1])
if p[0] < x:
c = not c
return c
def test_embedding_matches_brute_force_on_a_chain():
cands = [(0.5 * x, 0.5 * y - 0.25) for x in range(5) for y in range(5)]
cands = [p for p in cands if inside(L_SHAPE, p)]
parents, offsets = [-1, 0, 1], [None, (2.0, 0.0), (0.0, 1.6)]
cost, part, _ = embed(parents, offsets, cands, L_SHAPE)
bf_cost, _ = brute_force_embedding(parents, offsets, cands, L_SHAPE)
assert abs(cost - bf_cost) < 1e-12
assert cands[part[1]][0] > 1.7 and cands[part[2]][1] > 1.0
def test_embedding_matches_brute_force_on_random_trees():
rng = random.Random(4)
box = [(0.0, 0.0), (3.0, 0.0), (3.0, 3.0), (0.0, 3.0)]
for _ in range(4):
cands = [(rng.uniform(0, 3), rng.uniform(0, 3)) for _ in range(6)]
parents = [-1, 0, 0, 1]
offsets = [None] + [(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5)) for _ in range(3)]
shape = rng.choice([box, U_SHAPE])
cost, part, expanded = embed(parents, offsets, cands, shape)
bf_cost, _ = brute_force_embedding(parents, offsets, cands, shape)
assert abs(cost - bf_cost) < 1e-12
assert expanded <= 1 + 6 + 6**2 + 6**3
def test_cholesky_against_gaussian_elimination():
rng = random.Random(5)
n = 12
b = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
a = [[sum(b[k][i] * b[k][j] for k in range(n)) + (n if i == j else 0.0) for j in range(n)] for i in range(n)]
rhs = [rng.gauss(0, 1) for _ in range(n)]
x = cholesky_solve(cholesky(a), rhs)
y = solve(a, rhs)
assert max(abs(p - q) for p, q in zip(x, y)) < 1e-10
poly = resample(L_SHAPE, 0.2)
bones = [((0.2, 0.0), (2.0, 0.0)), ((2.0, 0.0), (2.0, 1.5))]
a, rhs = heat_system(poly, bones)
for r in rhs:
x = cholesky_solve(cholesky(a), r)
y = solve(a, r)
assert max(abs(p - q) for p, q in zip(x, y)) < 1e-10
def test_weights_are_a_partition_of_unity_and_nonnegative():
poly = resample(L_SHAPE, 0.1)
bones = [((0.2, 0.0), (2.0, 0.0)), ((2.0, 0.0), (2.0, 1.5))]
w = heat_weights(poly, bones)
for j in range(len(poly)):
assert abs(sum(wi[j] for wi in w) - 1.0) < 1e-12
assert all(-1e-15 <= wi[j] <= 1.0 + 1e-12 for wi in w)
assert w[0][poly.index((0.0, -0.3))] > 0.99
assert w[1][poly.index((2.3, 2.0))] > 0.99
def test_vertices_that_see_no_bone():
poly = resample(U_SHAPE, 0.25)
bones = [((0.5, 0.5), (0.5, 2.5)), ((0.5, 0.5), (1.5, 0.5))]
hidden = [j for j in range(len(poly)) if not nearest_visible(poly, bones, j)[1]]
assert poly.index((3.0, 3.0)) in hidden
w = heat_weights(poly, bones)
for j in range(len(poly)):
assert abs(w[0][j] + w[1][j] - 1.0) < 1e-12
assert w[0][j] >= 0.0 and w[1][j] >= 0.0
j = poly.index((3.0, 3.0))
assert w[1][j] > w[0][j]
def test_large_c_tends_to_the_nearest_bone():
poly = resample(L_SHAPE, 0.15)
bones = [((0.2, 0.0), (2.0, 0.0)), ((2.0, 0.0), (2.0, 1.5))]
w = heat_weights(poly, bones, c=1e7)
for j in range(len(poly)):
_, ids = nearest_visible(poly, bones, j)
for i in range(2):
p = 1.0 / len(ids) if i in ids else 0.0
assert abs(w[i][j] - p) < 1e-3
def test_rig_end_to_end():
cands = [(0.25 + 0.5 * x, 0.5 * y) for x in range(5) for y in range(4)]
cands = [p for p in cands if inside(L_SHAPE, p)]
poly = resample(L_SHAPE, 0.25)
joints, w = rig(poly, [-1, 0, 1], [None, (2.0, 0.0), (0.0, 1.6)], cands)
assert 1.7 < joints[1][0] < 2.3 and joints[2][1] > 1.0
for j in range(len(poly)):
assert abs(w[0][j] + w[1][j] - 1.0) < 1e-12
def test_check_value_of_the_page():
square = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
bones = [((-0.5, -0.5), (0.5, -0.5)), ((-0.5, 0.5), (0.5, 0.5))]
w = heat_weights(square, bones)
for got, want in zip(w[0], (0.9, 0.9, 0.1, 0.1)):
assert abs(got - want) < 1e-12
for got, want in zip(w[1], (0.1, 0.1, 0.9, 0.9)):
assert abs(got - want) < 1e-12
History
Before Pinocchio, an artist placed the skeleton by hand and painted the weights, which took hours per character. Baran and Popović (2007) automated both steps with a template skeleton: a discrete embedding scored by penalties, followed by heat diffusion for the weights. In their tests, the embedding was correct for 13 of 16 characters. The heat weights, often called bone heat weights, became the default automatic weights in common animation tools, and later work such as bounded biharmonic weights built on the same idea of weights as the solution of a partial differential equation.
References
- Ilya Baran and Jovan Popović, Automatic rigging and animation of 3D characters, ACM Transactions on Graphics 26(3), SIGGRAPH 2007, article 72, the skeleton embedding by a discrete search over the centers of medial spheres followed by a continuous refinement, and the attachment by the heat equation with one weight function per bone (general locator)
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 FM8DXC Edit this page History Report an error Markdown