Algorithmresearch
Optimized centers of rotation skinning
Also called CoR skinning.
Precomputes a center of rotation per vertex as a mean of the rest surface weighted by weight similarity, then turns the vertex about it by blended quaternions and moves it by blended translations.
- Solves
- Character skinning
- Time
- O(j + n k) frameO(n m k^2) precompute
- Space
- O(n + m) extra
- Where
- j = the number of joints; k = the largest number of joints per vertex; m = the number of triangles of the refined mesh; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Skinning with optimized centers of rotation (CoR skinning) is a skinning method of Le and Hodgins (2016) that sits between linear blend skinning and dual quaternion skinning. In a precomputation it gives each vertex a center of rotation : the mean of the rest surface, where each part counts by how similar its skinning weights are to the weights of the vertex. In each frame the vertex turns about by the normalized blend of the joint quaternions, and itself moves by linear blend skinning:
The rotation part has no candy wrapper collapse, and the center sits inside the limb near the joint, so a bent elbow neither collapses as with LBS nor bulges as with DQS. The run-time cost is close to that of DQS, and the result depends only on the weights and the rest mesh, so it fits an existing rig.
In plain words
Each point of the skin needs a pivot to turn about. Bones that move the same point turn in different ways, so there is no single obvious pivot. This method picks the pivot of each point once, before the animation starts. It looks at all the parts of the skin that the same bones move in the same proportions, and takes their average position. For a point on an elbow, those parts form a ring around the arm at the elbow, so the pivot falls in the middle of the arm. During the animation each point turns about its pivot by the average turn of its bones, so the arm keeps its thickness when it bends or twists.
The problem
The input is the rest mesh with the vertices , the normals and the triangles, the weights with , and in each frame the rigid skinning transforms (see bind pose), with the rotation , the translation and the unit quaternion . The output is the deformed mesh of each frame. This is the character skinning problem with rigid joint transforms and fixed weights.
The algorithm
The similarity of two weight vectors is
A term is large when both vectors use the joints and in the same ratio; the factor makes it zero unless both vectors use both joints. The center of vertex is the integral over the rest surface, with the interpolated weights. The method subdivides the rest mesh until the weights change little across each triangle, and then sums over the triangles with the area , the centroid and the mean weight vector .
COR-SKINNING▷ precomputation, once for the rest mesh- 1
refine the triangles; for each triangle t: a_t ← area, c_t ← centroid, w̄_t ← mean of its vertex weights - 2
for each vertex i - 3
num ← 0; den ← 0 - 4
for each triangle t: s ← s(w_i, w̄_t) a_t; num ← num + s c_t; den ← den + s - 5
p_i ← num / den if den > 0, else v_i ▷ each frame- 6
for each vertex i - 7
R ← the rotation of normalize(Σ_j s_j w_ij q_j) ▷ s_j = ±1, aligned to the joint of the largest weight - 8
t ← Σ_j w_ij C_j p_i - R p_i - 9
v'_i ← R v_i + t - 10
n'_i ← R n_i - 11
return V', N'
Line L5 handles a vertex whose weights share no pair of joints with any triangle, such as a vertex with one joint: with , lines L8 and L9 give the linear blend , which is the rigid motion of the joint. Line L7 is the same quaternion blend as in spherical blend skinning; line L8 makes the translation the linear blend of the images of the center, so the center moves exactly as in LBS. The width of the similarity and the refinement bound are tuning values; the code uses and refines until the weight vectors of the two ends of every edge differ by at most in length.
Example
Take an open tube of radius along from 0 to 2, with 8 vertices per ring and 9 rings, two joints at and , and the weight of joint 1 rising smoothly from 0 at to 1 at . The rings are symmetric about the axis, so every center of a vertex with two joints lies on the axis: the vertices at , and get the centers , and .
| pose | vertex | CoR | LBS |
|---|---|---|---|
| twist by about | |||
| bend by about through | |||
| same bend |
In the twist, LBS pulls the middle ring onto the axis, and CoR keeps the radius . In the bend, the middle ring keeps the distance from the elbow with CoR and drops to with LBS. These values come from the code of this page, so they are measurements of this mesh and these weights.
Correctness
The proofs are in proofs/correctness.md; they are proved properties of the formulas in exact arithmetic.
- The similarity is symmetric, nonnegative, and zero unless both weight vectors use at least two common joints.
- Each center is a convex combination of triangle centroids, so it lies in the convex hull of the rest mesh; the centers move with the rest mesh under a rigid motion.
- In the bind pose the mesh stays where it is; under a common rigid motion the mesh moves by .
- A vertex with one joint moves by the transform of that joint.
- Each vertex moves by a rotation and a translation, so its normal stays a unit vector, and the center moves as in LBS.
- If the center of a vertex is a fixed point of all its joint transforms, the vertex keeps its distance to the center; this is why the twisted and the bent tube keep their radius.
Proof: CoR skinning moves each vertex rigidly, keeps the bind pose and common rigid motions, and keeps the distance to a center that the joints fixfull
We use the notation of the page. The arithmetic is exact, the weights of each vertex and of each triangle are nonnegative with the sum 1, and each is rigid with the unit quaternion . For a vertex , let , so that lines L8 and L9 give .
The similarity
Lemma 1. , and if fewer than two joints have a positive weight in both vectors.
Proof. Swapping and swaps the two products in and changes only its sign, which the square removes; the factor in front is symmetric. Every term is a product of nonnegative numbers and an exponential. A term for the pair is zero unless are all positive.
The centers
Lemma 2. If in line L5, then is a convex combination of the centroids . If the rest mesh is moved by a rigid motion and the weights are kept, the new center is .
Proof. with and . A rigid motion keeps the areas, maps each centroid to , and does not change the weights, so the stay the same, and because is affine and . If , the center is , which moves to .
Each centroid lies in the convex hull of the mesh vertices, so does too.
The rotation
Lemma 3. The sum in line L7 has a norm of at least the largest weight , so is a rotation.
Proof. With the pivot and the signs with , the sum satisfies . A unit quaternion gives a rotation matrix.
Rigid motion of each vertex
Lemma 4. For each vertex the frame step is with a rotation , so , and the center goes to , its image under LBS.
Proof. By lines L8 and L9, . is a rotation by Lemma 3.
Lemma 5. In the bind pose, with all , and . If all for one rigid , then and .
Proof. If all , then all are for the quaternion of , the aligned sum is times a positive number, and . , so . The bind pose is the case .
Lemma 6. If only the joint has a positive weight for vertex , then .
Proof. Then and , so for any center.
By Lemma 1 such a vertex has , and line L5 sets ; Lemma 6 shows that the choice does not matter.
Twist and bend about a fixed center
Lemma 7. If for every joint of vertex , then .
Proof. , so , and keeps lengths.
In the tube of the example, the twist and the bend fix every point of the joint axis or of the elbow line through for the two joints, and the centers of the middle ring are on that axis or line, so the middle ring keeps its distance to the center. Linear blend skinning does not keep it: for the weights and the twist by , it maps the vertex to .
Complexity
The precomputation compares each vertex with each triangle of the refined mesh, which costs time with joint pairs per similarity; the code of this page uses this plain double loop, and a production tool needs a faster evaluation of the sum. Each frame costs for the quaternions of the joints and per vertex, so , the same order as LBS and DQS. The extra space is one center per vertex and the refined mesh during the precomputation, .
Properties
- Rigid per vertex at run time: no candy wrapper collapse under twist (a proved property for centers on the twist axis, and a measurement for the tube above).
- Less bulge than DQS and less collapse than LBS in bends; Le and Hodgins show this on character models (a measurement).
- The center depends only on the rest mesh and the weights, so changing the animation needs no new precomputation; changing the weights does.
- The similarity, and the refinement are heuristic choices.
- A vertex far from all others with similar weights can get a center that is far from the joint, because the mean is over the whole surface.
Variants and improvements
- Spherical blend skinning. SBS uses the same formula, but finds the center in each frame by least squares per set of joints, from the pose instead of the rest surface.
- Dual quaternion skinning. DQS has no explicit center; for a bend it turns the vertices about a point that can lie outside the limb, which gives the bulge that CoR removes.
- Delta mush. Delta mush also fixes the artifacts of LBS, by smoothing and stored details instead of a better blend.
- Better weights. The method keeps the weights of the rig; bounded biharmonic weights or skinning decomposition can provide them.
When to use it
Use it as a drop-in replacement of LBS or DQS in a real-time engine when twists collapse and bends bulge, and the weights are fixed. Use DQS if no precomputation is possible, for example when the weights change at run time.
Pitfalls
- Coarse meshes. Without the refinement, the sum over triangles is a poor stand-in for the integral where the weights change fast, and the centers jump between neighbor vertices.
- One joint per vertex. Such a vertex has no similar triangles; give it its own position as the center, or any point, since the result is then the rigid motion of the joint anyway.
- The sign of the quaternions. Align the signs to a pivot before the blend, or the blend can turn the long way.
- Scale in the rig. The rotation blend assumes rigid joint transforms; with scale in , the quaternions of line L7 are not defined, and the scale must be handled separately.
- Weights not normalized. The weights of each vertex must sum to 1, or the center does not move as in LBS.
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
optimized_centers_of_rotation_skinning.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimized-centers-of-rotation-skinning/. The authors are listed in prov/3BKQB9.jsonl.
"""Skinning with optimized centers of rotation (Le and Hodgins 2016).
Precomputation, once per mesh in the rest pose. For each vertex i with the
weight vector w_i, the center of rotation is the mean of the triangle
centroids c_t, weighted by the triangle area a_t and by the similarity of
w_i to the mean weight vector of the triangle:
p_i = sum_t s(w_i, w_t) a_t c_t / sum_t s(w_i, w_t) a_t,
s(w_p, w_v) = sum_{j < k} w_pj w_pk w_vj w_vk
exp(-(w_pj w_vk - w_pk w_vj)^2 / sigma^2).
The similarity is zero unless both vectors have at least two joints in
common, so a vertex with one joint has no center. The code then sets
p_i = v_i, which makes the frame step give linear blend skinning, that is
the rigid motion of the joint.
The mesh is first subdivided so that the weights vary little across each
triangle; the subdivision only serves the integral, and the skinned
vertices are the original ones. Here every triangle is split into four,
level by level, until the weights of the two ends of each edge differ by at
most eps. sigma and eps are tuning values.
Each frame: q is the normalized sum of the joint quaternions with the signs
aligned to the joint of the largest weight, R is its rotation, and
t = sum_j w_ij C_j p_i - R p_i, v_i' = R v_i + t, n_i' = R n_i.
The cost of the precomputation here is the plain double loop over vertices
and triangles; the paper speeds it up, which this code does not do.
"""
import math
from anim import add, cross, matvec, norm, q_dot, q_from_mat3, q_to_mat3, scale, sub
SIGMA = 0.1
EPS = 0.1
def similarity(wp, wv, sigma=SIGMA):
"""Return s(w_p, w_v) for two dense weight vectors."""
s = 0.0
nz = [j for j in range(len(wp)) if wp[j] > 0.0 and wv[j] > 0.0]
for a in range(len(nz)):
j = nz[a]
for b in range(a + 1, len(nz)):
k = nz[b]
d = wp[j] * wv[k] - wp[k] * wv[j]
s += wp[j] * wp[k] * wv[j] * wv[k] * math.exp(-(d * d) / (sigma * sigma))
return s
def subdivide(vertices, triangles, weights):
"""Split each triangle into four at the edge midpoints, with linear weights."""
verts = list(vertices)
ws = [list(w) for w in weights]
mid = {}
def midpoint(a, b):
key = (a, b) if a < b else (b, a)
if key not in mid:
verts.append(scale(add(verts[a], verts[b]), 0.5))
ws.append([0.5 * (x + y) for x, y in zip(ws[a], ws[b])])
mid[key] = len(verts) - 1
return mid[key]
tris = []
for a, b, c in triangles:
ab, bc, ca = midpoint(a, b), midpoint(b, c), midpoint(c, a)
tris += [(a, ab, ca), (ab, b, bc), (ca, bc, c), (ab, bc, ca)]
return verts, tris, ws
def max_edge_weight_change(triangles, weights):
m = 0.0
for t in triangles:
for a, b in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0])):
m = max(m, norm(sub(weights[a], weights[b])))
return m
def refine(vertices, triangles, weights, eps=EPS, max_levels=4):
"""Subdivide until the weights change by at most eps along every edge."""
for _ in range(max_levels):
if max_edge_weight_change(triangles, weights) <= eps:
break
vertices, triangles, weights = subdivide(vertices, triangles, weights)
return vertices, triangles, weights
def triangle_data(vertices, triangles, weights):
"""Return the areas, centroids and mean weight vectors of the triangles."""
out = []
for a, b, c in triangles:
area = 0.5 * norm(cross(sub(vertices[b], vertices[a]), sub(vertices[c], vertices[a])))
cen = scale(add(add(vertices[a], vertices[b]), vertices[c]), 1.0 / 3.0)
wbar = [(x + y + z) / 3.0 for x, y, z in zip(weights[a], weights[b], weights[c])]
out.append((area, cen, wbar))
return out
def centers_of_rotation(vertices, triangles, weights, sigma=SIGMA, eps=EPS, max_levels=4):
"""Return one center of rotation per vertex (the precomputation)."""
fv, ft, fw = refine(vertices, triangles, weights, eps, max_levels)
data = triangle_data(fv, ft, fw) # @line L1
centers = []
for i, v in enumerate(vertices): # @line L2
num = (0.0, 0.0, 0.0) # @line L3
den = 0.0
for area, cen, wbar in data: # @line L4
s = similarity(weights[i], wbar, sigma) * area
if s > 0.0:
num = add(num, scale(cen, s))
den += s
centers.append(scale(num, 1.0 / den) if den > 0.0 else tuple(v)) # @line L5
return centers
def blend_rotation(wi, quats):
"""Return the rotation matrix of the normalized, sign-aligned quaternion sum."""
pivot = quats[max(range(len(wi)), key=lambda j: wi[j])]
s = [0.0, 0.0, 0.0, 0.0]
for j, w in enumerate(wi):
if w == 0.0:
continue
q = quats[j]
f = -w if q_dot(pivot, q) < 0.0 else w
for k in range(4):
s[k] += f * q[k]
n = math.sqrt(q_dot(s, s))
return q_to_mat3([x / n for x in s])
def apply_rigid(m, p):
return tuple(m[r][0] * p[0] + m[r][1] * p[1] + m[r][2] * p[2] + m[r][3] for r in range(3))
def cor_skinning(vertices, weights, centers, palette, normals=None):
"""Return (positions, normals) skinned with the precomputed centers.
palette: rigid skinning matrices C_j = M_j B_j^(-1) of the frame.
weights: dense weight vectors, one per vertex.
"""
quats = [q_from_mat3([row[:3] for row in p[:3]]) for p in palette]
out_v = []
out_n = [] if normals is not None else None
for i, v in enumerate(vertices): # @line L6
wi = weights[i]
r = blend_rotation(wi, quats) # @line L7
p = centers[i]
lp = (0.0, 0.0, 0.0)
for j, w in enumerate(wi):
if w != 0.0:
lp = add(lp, scale(apply_rigid(palette[j], p), w))
t = sub(lp, matvec(r, p)) # @line L8
out_v.append(add(matvec(r, v), t)) # @line L9
if normals is not None:
out_n.append(matvec(r, normals[i])) # @line L10
return out_v, out_n # @line L11
def lbs(vertices, weights, palette):
"""Linear blend skinning with dense weights, the reference of the tests."""
out = []
for v, wi in zip(vertices, weights):
p = (0.0, 0.0, 0.0)
for j, w in enumerate(wi):
if w != 0.0:
p = add(p, scale(apply_rigid(palette[j], v), w))
out.append(p)
return out
test_optimized_centers_of_rotation_skinning.py 231 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimized-centers-of-rotation-skinning/. The authors are listed in prov/3BKQB9.jsonl.
"""Tests of skinning with optimized centers of rotation.
They check the similarity, the refinement, the centers against a direct
quadrature of the integral, the bind pose, the single joint case, a common
rigid motion, the twist of a tube (no volume loss, unlike linear blend
skinning), unit normals, and that the centers move with the rest mesh.
"""
import functools
import math
import random
import anim
from optimized_centers_of_rotation_skinning import (
centers_of_rotation,
cor_skinning,
lbs,
max_edge_weight_change,
refine,
similarity,
)
def smoothstep(x):
x = min(1.0, max(0.0, x))
return x * x * (3.0 - 2.0 * x)
def tube(nr=8, ny=9, radius=0.5, length=2.0):
"""An open tube along y with two joints, at y = 0 and y = 1."""
verts, normals, weights = [], [], []
for r in range(ny):
y = length * r / (ny - 1)
w1 = smoothstep(y - 0.5)
for k in range(nr):
a = 2.0 * math.pi * k / nr
verts.append((radius * math.cos(a), y, radius * math.sin(a)))
normals.append((math.cos(a), 0.0, math.sin(a)))
weights.append([1.0 - w1, w1])
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, normals, weights, tris
@functools.lru_cache(maxsize=None)
def tube_centers():
verts, _, weights, tris = tube()
return tuple(centers_of_rotation(verts, tris, weights, eps=0.2))
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 rot_y(t):
return anim.make_T(anim.q_to_mat3(anim.q_from_axis_angle((0.0, 1.0, 0.0), t)), (0.0, 0.0, 0.0))
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def grid(rng, n=3, nj=3):
"""A small bumpy grid with random weights over nj joints."""
verts, weights = [], []
for r in range(n):
for c in range(n):
verts.append((float(c), float(r), 0.3 * rng.random()))
w = [rng.random() + 0.05 for _ in range(nj)]
s = sum(w)
weights.append([x / s for x in w])
tris = []
for r in range(n - 1):
for c in range(n - 1):
a = r * n + c
tris += [(a, a + 1, a + n), (a + 1, a + n + 1, a + n)]
return verts, tris, weights
def quadrature_centers(verts, tris, weights, m, sigma=0.1):
"""The integral of the center formula by the midpoint rule on an m by m split of each triangle."""
out = []
for wi in weights:
num, den = (0.0, 0.0, 0.0), 0.0
for a, b, c in tris:
area = 0.5 * anim.norm(anim.cross(anim.sub(verts[b], verts[a]), anim.sub(verts[c], verts[a]))) / (m * m)
for i in range(m):
for j in range(m - i):
pts = [((i + 1 / 3) / m, (j + 1 / 3) / m)]
if i + j < m - 1:
pts.append(((i + 2 / 3) / m, (j + 2 / 3) / m))
for u, v in pts:
bc = (1.0 - u - v, u, v)
x = tuple(sum(bc[k] * verts[t][d] for k, t in enumerate((a, b, c))) for d in range(3))
w = [sum(bc[k] * weights[t][q] for k, t in enumerate((a, b, c))) for q in range(len(wi))]
s = similarity(wi, w, sigma) * area
num = anim.add(num, anim.scale(x, s))
den += s
out.append(anim.scale(num, 1.0 / den))
return out
def test_similarity():
rng = random.Random(1)
for _ in range(50):
a = [rng.random() for _ in range(4)]
b = [rng.random() for _ in range(4)]
assert abs(similarity(a, b) - similarity(b, a)) < 1e-15
assert similarity(a, b) > 0.0
assert similarity([1.0, 0.0, 0.0], [0.5, 0.5, 0.0]) == 0.0
assert similarity([0.5, 0.0, 0.5], [0.0, 0.5, 0.5]) == 0.0
# for a fixed own weight vector, the closest match is the most similar
w = [0.5, 0.5]
assert similarity(w, [0.5, 0.5]) > similarity(w, [0.6, 0.4]) > similarity(w, [0.8, 0.2])
def test_refine_meets_the_bound():
verts, _, weights, tris = tube()
fv, ft, fw = refine(verts, tris, weights, eps=0.2)
assert max_edge_weight_change(ft, fw) <= 0.2
assert fv[: len(verts)] == verts
for w in fw:
assert abs(sum(w) - 1.0) < 1e-12
def test_centers_match_quadrature():
rng = random.Random(2)
verts, tris, weights = grid(rng)
# three levels of splitting are the midpoint rule on an 8 by 8 split
got = centers_of_rotation(verts, tris, weights, eps=0.0, max_levels=3)
ref = quadrature_centers(verts, tris, weights, 8)
for a, b in zip(got, ref):
assert close(a, b, 1e-12)
# and the refinement converges to the integral
fine = quadrature_centers(verts, tris, weights, 24)
errs = []
for lv in (0, 1, 2):
c = centers_of_rotation(verts, tris, weights, eps=0.0, max_levels=lv)
errs.append(max(anim.norm(anim.sub(a, b)) for a, b in zip(c, fine)))
assert errs[0] > errs[1] > errs[2]
def test_bind_pose_gives_rest_mesh():
verts, normals, weights, _ = tube()
pal = [anim.eye(4), anim.eye(4)]
out_v, out_n = cor_skinning(verts, weights, tube_centers(), pal, normals)
for a, b in zip(out_v, verts):
assert close(a, b, 1e-12)
for a, b in zip(out_n, normals):
assert close(a, b, 1e-12)
def test_single_joint_is_rigid():
rng = random.Random(3)
verts, _, weights, _ = tube()
centers = tube_centers()
pal = [rand_T(rng), rand_T(rng)]
out_v, _ = cor_skinning(verts, weights, centers, pal)
count = 0
for v, w, c, a in zip(verts, weights, centers, out_v):
if w[1] == 0.0:
assert c == v
assert close(a, anim.T_apply(pal[0], v), 1e-12)
count += 1
assert count >= 8
def test_common_rigid_motion():
rng = random.Random(4)
verts, normals, weights, _ = tube()
g = rand_T(rng)
out_v, out_n = cor_skinning(verts, weights, tube_centers(), [g, g], normals)
gr = [row[:3] for row in g[:3]]
for v, n, a, b in zip(verts, normals, out_v, out_n):
assert close(a, anim.T_apply(g, v), 1e-12)
assert close(b, anim.matvec(gr, n), 1e-12)
def test_twist_keeps_the_radius():
verts, normals, weights, _ = tube()
centers = tube_centers()
for c, w in zip(centers, weights):
if min(w) > 0.0:
assert math.hypot(c[0], c[2]) < 1e-9
for t in (1.0, math.pi / 2, 2.5, math.pi):
pal = [anim.eye(4), rot_y(t)]
out_v, out_n = cor_skinning(verts, weights, centers, pal, normals)
ref = lbs(verts, weights, pal)
for v, a, b, n in zip(verts, out_v, ref, out_n):
assert abs(math.hypot(a[0], a[2]) - 0.5) < 1e-12
assert abs(a[1] - v[1]) < 1e-12
assert abs(anim.norm(n) - 1.0) < 1e-12
lbs_min = min(math.hypot(b[0], b[2]) for b in ref)
assert lbs_min < 0.5 * abs(math.cos(t / 2)) + 1e-9
def test_bend_reduces_the_loss_of_volume():
# bend joint 1 by pi/2 about the z axis through (0, 1, 0); the mean
# distance of the middle ring from the elbow drops less than with LBS
verts, _, weights, _ = tube()
centers = tube_centers()
r = anim.q_to_mat3(anim.q_from_axis_angle((0.0, 0.0, 1.0), math.pi / 2))
elbow = (0.0, 1.0, 0.0)
pal = [anim.eye(4), anim.make_T(r, anim.sub(elbow, anim.matvec(r, elbow)))]
out_v, _ = cor_skinning(verts, weights, centers, pal)
ref = lbs(verts, weights, pal)
ring = [i for i, v in enumerate(verts) if abs(v[1] - 1.0) < 1e-12]
d_cor = sum(anim.norm(anim.sub(out_v[i], elbow)) for i in ring) / len(ring)
d_lbs = sum(anim.norm(anim.sub(ref[i], elbow)) for i in ring) / len(ring)
assert d_cor > d_lbs
def test_centers_move_with_the_mesh():
rng = random.Random(5)
verts, tris, weights = grid(rng)
g = rand_T(rng)
c0 = centers_of_rotation(verts, tris, weights, eps=0.0, max_levels=2)
c1 = centers_of_rotation([anim.T_apply(g, v) for v in verts], tris, weights, eps=0.0, max_levels=2)
for a, b in zip(c0, c1):
assert close(anim.T_apply(g, a), b, 1e-9)
xs = [v[0] for v in verts]
ys = [v[1] for v in verts]
for a in c0:
assert min(xs) <= a[0] <= max(xs) and min(ys) <= a[1] <= max(ys)
History
Binh Huy Le and Jessica K. Hodgins presented the method at SIGGRAPH 2016. It takes the idea of a center of rotation from the spherical blend skinning of Kavan and Žára (2005), and moves the computation of the center from each frame to a precomputation over the rest surface.
References
- Binh Huy Le and Jessica K. Hodgins, Real-time skeletal skinning with optimized centers of rotation, ACM Transactions on Graphics 35(4), article 37, 2016 (SIGGRAPH 2016), the similarity of skinning weights, the center of rotation integral, the subdivision of the rest mesh and the run-time blend
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 3BKQB9 Edit this page History Report an error Markdown