Algorithmcore
Dual quaternion skinning
Also called DQS, dual quaternion linear blending.
Blends the joint transforms as unit dual quaternions with aligned signs, then normalizes. The result is rigid unless the blended real part is zero, and twisted joints do not collapse.
- Solves
- Character skinning
- Time
- O(j + n k) frame
- Space
- O(j) extra
- Where
- 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
Dual quaternion skinning (DQS) deforms a mesh by a skeleton, like linear blend skinning, but it blends the joint transforms as unit dual quaternions instead of as matrices. A rigid transform with the rotation quaternion and the translation is with . For a vertex with the weights , DQS computes
where aligns the signs of the quaternions and is the dual quaternion norm. If the real part of is not zero, is a unit dual quaternion, so the vertex moves by a rigid transform. A twisted joint therefore does not collapse: the skin turns about the bone and keeps its distance from it. Kavan, Collins, Žára and O'Sullivan gave the method in 2007, and it is in most animation tools and game engines as an option next to LBS.
In plain words
Linear blend skinning averages the places where each bone would carry a point of the skin. That average cuts across the circle, so the skin shrinks at a twist. DQS averages the motions themselves, in a form where a turn and a shift are one object. After the average, it scales the result so that it is again an exact turn and shift. The point then moves on the circle, not across it, so a twist of half a turn between two bones gives a quarter turn in the middle, with no loss of thickness. The price is that the skin can bulge out a little at a bent joint, and the method cannot blend a bone that is scaled.
The problem
The input is the same as for linear blend skinning: rest vertices and normals in the bind pose, weights with , and the skinning matrices of joints. Here each must be rigid, a rotation and a translation. The output is the deformed position and unit normal of each vertex, for the character skinning problem.
Quaternions use the Hamilton convention with the scalar first. A dual quaternion is with . It is a unit dual quaternion if and (the dot product in ). The translation is recovered by .
The algorithm
DQS(v, n, W, P) ▷ rest mesh, weights, rigid skinning matrices- 1
for each joint j: (rⱼ, dⱼ) ← DQ(Pⱼ) ▷ dⱼ = ½ (0, tⱼ) rⱼ - 2
for each vertex i do - 3
p ← r of the joint of largest weight in Wᵢ ▷ the pivot - 4
b₀ ← 0; b_ε ← 0 - 5
for each (j, w) in Wᵢ do - 6
s ← -1 if p · rⱼ < 0, else 1 ▷ rⱼ and -rⱼ are the same rotation - 7
b₀ ← b₀ + s w rⱼ; b_ε ← b_ε + s w dⱼ - 8
if b₀ = 0 then fail ▷ no rigid transform - 9
c₀ ← b₀ / |b₀|; c_ε ← b_ε / |b₀| - (c₀ · b_ε / |b₀|) c₀ - 10
t ← 2 c_ε c₀* ▷ its vector part - 11
v′ᵢ ← c₀ vᵢ c₀* + t; n′ᵢ ← c₀ nᵢ c₀* - 12
return v′, n′
Line L1 converts each skinning matrix once per frame. Lines L3 to L7 blend the dual quaternions of the vertex after the sign alignment of Kavan et al. (2008), Algorithm 2, with the joint of largest weight as the pivot. Line L9 is the division by the dual norm . The term makes ; it changes only the scalar part of , so a shader may drop it and still get the same . Line L11 rotates the normal by the rotation of the blend, so it stays unit length.
Example
Take and , with the weights and on the vertex . The quaternions are and , and , so no sign changes. The blend is with , so , the rotation by about . The vertex goes to , at the distance 1 from the axis. LBS puts it at .
A bent joint: let be the rotation by about the axis through the joint , so . Then and . For the vertex with the weights and , the blend gives , the rotation by , and the vertex goes to . That is the distance 0.5 from the joint, as in the rest pose. LBS gives , at the distance 0.35355.
Correctness
The proofs are in proofs/correctness.md. They are proved properties of the blend in exact arithmetic.
- Rigidity. If , line L9 gives and , so is a unit dual quaternion and line L11 applies a rotation and a translation.
- The exception. If , there is no normalization and no rigid transform. Without the sign alignment this happens even for two joints with the same rotation, for example the weights and on and .
- The pivot bound. With the pivot alignment of line L6, , where is the weight of the pivot joint. So line L8 never fails after this alignment.
- Single joints. A vertex with one weight of 1 gets , the transform , which is also the LBS result.
- Bind pose. If every , then every and the mesh is the rest mesh.
- Coordinate invariance. Changing the world frame by a rigid changes the result by (Kavan et al. 2008, Lemma 2).
- Pure translations. If all , the translation of the blend is , the same as LBS.
The pivot bound does not mean that the signs are right. For three or more joints the signs may have no choice where every pair has a nonnegative dot product (Kavan et al. 2008, Section 4.1), and the blend then depends on the pivot.
Proof: The normalized dual quaternion blend is rigid when its real part is not zero, and the pivot alignment keeps the real part away from zerofull
We use the notation of the page. Quaternions are in the Hamilton convention, scalar first, and is the dot product in . A dual quaternion is with quaternions , and . For a rotation quaternion () and a translation , written as the pure quaternion , the joint has with . The arithmetic is exact.
Unit dual quaternions are rigid transforms
Lemma 1. For and with a pure , and .
Proof. . For quaternions, is the scalar part of , so is the scalar part of , which is 0 because is pure.
Lemma 2. Let and . Then is a pure quaternion, and the map of line L11 is a rotation followed by a translation.
Proof. The scalar part of is , so is pure. For a unit , is the rotation of unit quaternion rotation, and adding a fixed vector is a translation.
The normalization of line L9
Lemma 3. If , line L9 gives and .
Proof. . Write . Then , and .
Lemma 4. The removed term does not change the translation: and have the same vector part.
Proof. , and is a real number.
By Lemmas 2 and 3, every vertex with moves by a rigid transform, and its normal is rotated by , so it keeps unit length.
The real part after the pivot alignment
Lemma 5. Let be the quaternion of an influence with weight , and let if and otherwise, as in line L6. Then .
Proof. By lines L6 and L7, , because every term is nonnegative. By the Cauchy-Schwarz inequality and , .
So line L8 never fails when the pivot is one of the influences, and the code uses the largest weight, which is at least . Without alignment the bound fails: the weights and on and , which are the same rotation, give .
Special cases
Lemma 6. If a vertex has one influence with , the result is .
Proof. The pivot is and , so . By Lemma 1, and , so line L9 gives , and by Lemma 1 line L11 applies the rotation and the translation , which is .
In the bind pose every , so every vertex has and stays at its rest position.
Lemma 7. If every , the vertex moves by the translation .
Proof. All signs are 1 and . is pure, so and .
Lemma 8. Let be a unit dual quaternion. If every is replaced by (with the dual quaternion conjugate), the normalized blend is replaced by .
Proof. The real part of is , and , because a map is a rotation of . So the pivot and the signs are the same. The map is linear, so the blend becomes , with the real part of the same length. Line L9 divides by the dual norm , and the dual norm is multiplicative with . So , and the normalized blend is .
This is the coordinate invariance of Kavan et al. (2008, Lemma 2): skinning in a world frame moved by gives the same mesh moved by .
The twist check value
With , (the rotation ) and the weights and , , so the signs are 1, , and , the rotation by about . It maps to , at the distance 1 from the axis. For a twist by , the same computation gives the rotation by .
Complexity
Line L1 costs per frame. Each vertex costs for the blend and for the normalization and the transform, so in total, and the time per frame is . The extra space is dual quaternions, 8 numbers each instead of 12 for a matrix.
Properties
- Rigid when : no loss of volume at a twist.
- For two joints, DQS and the screw linear interpolation ScLERP use the same screw axis; Kavan et al. (2008, Section 3.4) bound the difference of the rotation angles by 8.15 degrees and of the translations by 15.1%.
- Bulges at bent joints: near a bend the method acts like a spherical blend about the joint, and the skin can bulge out (the course of Jacobson et al. 2014, Section 4).
- Cannot represent scale or shear. Kavan et al. (2008, Section 4.2) handle them by a two phase method: blend the scale and shear part as matrices first, then the rigid part as dual quaternions.
- Kavan et al. (2008, Section 5) measured DQS at more than twice the speed of the log-matrix and spherical blending methods; this is a measurement on their GPU setup.
Variants and improvements
- Sign alignment. Instead of one pivot per vertex, each joint can take its sign relative to its parent, once per frame for the whole skeleton (Kavan et al. 2008, Section 4.1).
- Spherical blend skinning. Spherical blend skinning, by the same group, blends the rotations about a center of rotation found by least squares.
- Optimized centers of rotation. CoR skinning removes the bulge with a precomputed center per vertex.
- Contact. Implicit skinning uses DQS or LBS as its first step.
- Rotation interpolation. For two keys, the rotation part of DQS is normalized linear interpolation of quaternions, not slerp; for curves through many keys, see squad.
When to use it
Use DQS where joints twist, for example forearms, wrists, necks and shoulders, and where the joints have no scale. Its cost is close to LBS, so it is a common default in games when the bulge at bent joints is acceptable. If the joints scale, use LBS or the two phase method.
Pitfalls
- No sign alignment. Without lines L3 to L6, two joints with nearly the same rotation can cancel, and the skin of the vertex jumps or the blend fails.
- Sign flips over time. When the pivot changes, or when crosses zero, the sign of a term flips, and the vertex can jump. Kavan et al. (2008, Section 4.1) discuss these cases.
- Wrong translation formula. is for applied as a rotation then a translation. The order is a different convention.
- Scaled joints. A joint matrix with a scale has no unit dual quaternion. Converting it with a rotation extraction silently drops the scale.
- Normals. The normal is rotated by . Using the inverse transpose of the LBS matrix instead gives normals that do not match the DQS surface.
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
dual_quaternion_skinning.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dual-quaternion-skinning/. The authors are listed in prov/SVNNAZ.jsonl.
"""Dual quaternion skinning (DQS) by dual quaternion linear blending.
A rigid transform with the rotation quaternion r and the translation t is the
unit dual quaternion r + eps d with d = (1/2) (0, t) r, and t = 2 d r*.
Each joint has the skinning transform P_j = M_j B_j^(-1), which must be
rigid. For a vertex with the weights w_j, the method (Kavan, Collins, Zara and
O'Sullivan 2007, 2008):
1. aligns the sign of each r_j with a pivot quaternion (the joint of the
largest weight of the vertex), because r and -r are the same rotation;
2. blends b = sum_j w_j s_j (r_j + eps d_j);
3. normalizes: c0 = b0 / |b0|, ce = be / |b0| - (c0 . be / |b0|) c0;
4. applies the rigid transform of c0 + eps ce to the vertex and c0 to the
normal.
Step 3 needs b0 != 0. With the pivot alignment, |b0| >= the pivot weight,
so this holds; without alignment (align=False) b0 can be zero, and the code
raises ValueError.
"""
import math
from anim import q_conj, q_dot, q_from_mat3, q_mul, q_rotate
REAL_PART_TOL = 1e-12
def dq_from_transform(m):
"""Return (r, d) of a rigid 4 by 4 transform, with d = (1/2) (0, t) r."""
r = q_from_mat3([row[:3] for row in m[:3]])
t = (0.0, m[0][3], m[1][3], m[2][3])
d = tuple(0.5 * x for x in q_mul(t, r))
return r, d
def dq_translation(r, d):
"""Return the translation t = 2 d r* (vector part) of a unit dual quaternion."""
p = q_mul(d, q_conj(r))
return (2.0 * p[1], 2.0 * p[2], 2.0 * p[3])
def dq_palette(palette):
"""Return the unit dual quaternions of the rigid skinning matrices."""
return [dq_from_transform(p) for p in palette] # @line L1
def blend(influences, dqs, align=True):
"""Return the normalized blend (c0, ce) of the dual quaternions of one vertex."""
pivot = dqs[max(influences, key=lambda jw: jw[1])[0]][0] # @line L3
b0 = [0.0, 0.0, 0.0, 0.0] # @line L4
be = [0.0, 0.0, 0.0, 0.0]
for j, w in influences: # @line L5
r, d = dqs[j]
s = -1.0 if (align and q_dot(pivot, r) < 0.0) else 1.0 # @line L6
for k in range(4): # @line L7
b0[k] += s * w * r[k]
be[k] += s * w * d[k]
n0 = math.sqrt(q_dot(b0, b0))
if n0 <= REAL_PART_TOL: # @line L8
raise ValueError("the blended real part is zero: no rigid transform")
c0 = tuple(x / n0 for x in b0) # @line L9
ce = tuple(x / n0 for x in be)
k = q_dot(c0, ce)
ce = tuple(e - k * c for e, c in zip(ce, c0))
return c0, ce
def dq_apply(c0, ce, v):
"""Apply the rigid transform of the unit dual quaternion c0 + eps ce to a point."""
t = dq_translation(c0, ce) # @line L10
p = q_rotate(c0, v)
return (p[0] + t[0], p[1] + t[1], p[2] + t[2]) # @line L11
def dual_quaternion_skinning(vertices, weights, palette, normals=None, align=True):
"""Return (positions, normals) of the mesh skinned by DQS.
vertices: rest positions in the bind pose; weights: per vertex, a list of
(joint index, weight) pairs with nonnegative weights that sum to 1;
palette: the rigid skinning matrices P_j = M_j B_j^(-1).
"""
dqs = dq_palette(palette)
out_v = []
out_n = [] if normals is not None else None
for i, v in enumerate(vertices): # @line L2
c0, ce = blend(weights[i], dqs, align)
out_v.append(dq_apply(c0, ce, v))
if normals is not None:
out_n.append(q_rotate(c0, normals[i])) # @line L11
return out_v, out_n # @line L12
test_dual_quaternion_skinning.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dual-quaternion-skinning/. The authors are listed in prov/SVNNAZ.jsonl.
"""Tests of dual quaternion skinning.
They check the dual quaternion round trip, the bind pose, the agreement with
LBS (one rigid transform) when each vertex has one joint, the candy wrapper
check value, that every blended transform is rigid, the invariance under a
change of coordinates, that pure translations blend as in LBS, the lower
bound on the blended real part after the pivot alignment, and the failure of
the blend without alignment when the real part is zero.
"""
import math
import random
import pytest
import anim
from dual_quaternion_skinning import (
blend,
dq_apply,
dq_from_transform,
dq_palette,
dq_translation,
dual_quaternion_skinning,
)
def rand_q(rng):
return anim.q_normalize([rng.gauss(0.0, 1.0) for _ in range(4)])
def rand_T(rng, spread=2.0):
t = tuple(rng.uniform(-spread, spread) for _ in range(3))
return anim.make_T(anim.q_to_mat3(rand_q(rng)), t)
def rand_weights(rng, nj, k):
js = rng.sample(range(nj), k)
ws = [rng.random() + 0.05 for _ in js]
s = sum(ws)
return [(j, w / s) for j, w in zip(js, ws)]
def rand_points(rng, n):
return [tuple(rng.uniform(-1.0, 1.0) for _ in range(3)) for _ in range(n)]
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def rx(theta):
c, s = math.cos(theta), math.sin(theta)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def blended_matrix(c0, ce):
r = anim.q_to_mat3(c0)
return anim.make_T(r, dq_translation(c0, ce))
def test_round_trip():
rng = random.Random(1)
for _ in range(50):
m = rand_T(rng)
r, d = dq_from_transform(m)
back = blended_matrix(r, d)
assert all(close(a, b, 1e-12) for a, b in zip(m, back))
assert abs(anim.q_dot(r, d)) <= 1e-12
def test_bind_pose_gives_rest_mesh():
rng = random.Random(2)
pal = [anim.eye(4) for _ in range(5)]
verts = rand_points(rng, 40)
normals = [anim.normalize(p) for p in rand_points(rng, 40)]
weights = [rand_weights(rng, 5, 3) for _ in verts]
out_v, out_n = dual_quaternion_skinning(verts, weights, 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_agrees_with_lbs():
rng = random.Random(3)
pal = [rand_T(rng) for _ in range(4)]
verts = rand_points(rng, 60)
weights = [[(rng.randrange(4), 1.0)] for _ in verts]
out, _ = dual_quaternion_skinning(verts, weights, pal)
for v, wl, a in zip(verts, weights, out):
lbs = anim.T_apply(pal[wl[0][0]], v)
assert close(a, lbs, 1e-12)
def test_candy_wrapper_check_value():
pal = [anim.make_T(rx(0.0), (0.0, 0.0, 0.0)), anim.make_T(rx(math.pi), (0.0, 0.0, 0.0))]
out, _ = dual_quaternion_skinning([(0.0, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
assert close(out[0], (0.0, 0.0, 1.0), 1e-12)
assert abs(math.hypot(out[0][1], out[0][2]) - 1.0) <= 1e-12
for theta in [0.2 * k for k in range(16)]:
pal[1] = anim.make_T(rx(theta), (0.0, 0.0, 0.0))
out, _ = dual_quaternion_skinning([(0.3, 1.0, 0.0)], [[(0, 0.5), (1, 0.5)]], pal)
assert close(out[0], (0.3, math.cos(theta / 2.0), math.sin(theta / 2.0)), 1e-12)
def test_blend_is_rigid_and_normals_unit():
rng = random.Random(4)
dqs = dq_palette([rand_T(rng) for _ in range(6)])
for _ in range(200):
c0, ce = blend(rand_weights(rng, 6, 4), dqs)
assert abs(anim.q_dot(c0, c0) - 1.0) <= 1e-12
assert abs(anim.q_dot(c0, ce)) <= 1e-12
p, q = rand_points(rng, 2)
d0 = anim.norm(anim.sub(p, q))
d1 = anim.norm(anim.sub(dq_apply(c0, ce, p), dq_apply(c0, ce, q)))
assert abs(d0 - d1) <= 1e-12
n = anim.q_rotate(c0, anim.normalize(p))
assert abs(anim.norm(n) - 1.0) <= 1e-12
def test_coordinate_invariance():
rng = random.Random(5)
for _ in range(20):
pal = [rand_T(rng) for _ in range(4)]
g = rand_T(rng)
gi = anim.T_inv(g)
conj = [anim.T_mul(anim.T_mul(g, p), gi) for p in pal]
verts = rand_points(rng, 10)
weights = [rand_weights(rng, 4, 3) for _ in verts]
out, _ = dual_quaternion_skinning(verts, weights, pal)
out_g, _ = dual_quaternion_skinning([anim.T_apply(g, v) for v in verts], weights, conj)
for a, b in zip(out, out_g):
assert close(anim.T_apply(g, a), b, 1e-10)
def test_pure_translations_blend_like_lbs():
rng = random.Random(6)
pal = [anim.make_T(anim.eye(3), tuple(rng.uniform(-3.0, 3.0) for _ in range(3))) for _ in range(5)]
verts = rand_points(rng, 30)
weights = [rand_weights(rng, 5, 3) for _ in verts]
out, _ = dual_quaternion_skinning(verts, weights, pal)
for v, wl, a in zip(verts, weights, out):
lbs = [0.0, 0.0, 0.0]
for j, w in wl:
p = anim.T_apply(pal[j], v)
for k in range(3):
lbs[k] += w * p[k]
assert close(a, lbs, 1e-12)
def test_aligned_real_part_is_bounded_below():
rng = random.Random(7)
for _ in range(300):
rs = [rand_q(rng) for _ in range(4)]
wl = rand_weights(rng, 4, 4)
jp = max(wl, key=lambda jw: jw[1])[0]
b0 = [0.0] * 4
for j, w in wl:
s = -1.0 if anim.q_dot(rs[jp], rs[j]) < 0.0 else 1.0
for k in range(4):
b0[k] += s * w * rs[j][k]
assert anim.norm(b0) >= wl[[j for j, _ in wl].index(jp)][1] - 1e-15
def test_zero_real_part_without_alignment_raises():
# r and -r are the same rotation; the unaligned blend of them is zero
m = anim.make_T(rx(1.0), (0.0, 0.0, 0.0))
dqs = dq_palette([m, m])
r, d = dqs[1]
dqs[1] = (tuple(-x for x in r), tuple(-x for x in d))
with pytest.raises(ValueError):
blend([(0, 0.5), (1, 0.5)], dqs, align=False)
c0, ce = blend([(0, 0.5), (1, 0.5)], dqs)
assert close(anim.q_to_mat3(c0)[1], rx(1.0)[1], 1e-12)
def test_three_joints_no_consistent_signs_still_rigid():
# pairwise signs cannot all be made nonnegative: q1.q2 > 0, q1.q3 > 0, q2.q3 < 0
q1 = (1.0, 0.0, 0.0, 0.0)
q2 = anim.q_normalize((0.2, 1.0, 0.0, 0.0))
q3 = anim.q_normalize((0.2, -1.0, 0.0, 0.0))
assert anim.q_dot(q1, q2) > 0 and anim.q_dot(q1, q3) > 0 and anim.q_dot(q2, q3) < 0
pal = [anim.make_T(anim.q_to_mat3(q), (0.0, 0.0, 0.0)) for q in (q1, q2, q3)]
dqs = dq_palette(pal)
c0, ce = blend([(0, 0.4), (1, 0.3), (2, 0.3)], dqs)
assert abs(anim.q_dot(c0, c0) - 1.0) <= 1e-12
assert abs(anim.q_dot(c0, ce)) <= 1e-12
History
Dual quaternions were used in kinematics and robotics for screw motions long before skinning. Kavan and Žára (2005) first replaced the matrix blend of LBS by a quaternion blend about a center of rotation, in spherical blend skinning. Kavan, Collins, Žára and O'Sullivan (2007) gave dual quaternion skinning at I3D, and the 2008 journal version proved the coordinate invariance of the blend, compared it with ScLERP, and treated the signs and the non-rigid joints.
References
- Ladislav Kavan, Steven Collins, Jiří Žára and Carol O'Sullivan, Skinning with dual quaternions, Proceedings of the 2007 Symposium on Interactive 3D Graphics and Games (I3D), 39-46, 2007, the whole paper (dual quaternion skinning)
- Ladislav Kavan, Steven Collins, Jiří Žára and Carol O'Sullivan, Geometric skinning with approximate dual quaternion blending, ACM Transactions on Graphics 27(4), article 105, 2008, Section 3.3 (equation 11 and Lemma 2, coordinate invariance), Section 3.4 (comparison with ScLERP), Section 4 (Algorithm 1), Section 4.1 (antipodality, Algorithm 2 and Lemma 5) and Section 4.2 (scale and shear)
- Ladislav Kavan, Part I, Direct skinning methods and deformation primitives, in Alec Jacobson, Zhigang Deng, Ladislav Kavan and J. P. Lewis, Skinning, Real-time Shape Deformation, SIGGRAPH 2014 course, Section 4 (dual quaternion blending, the double cover, non-rigid transforms and the bulging artifact)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SVNNAZ Edit this page History Report an error Markdown