Algorithmresearch
Implicit skinning
Also called implicit surface skinning.
Corrects linear or dual quaternion skinning by moving each vertex back to its rest value of a field built from one implicit surface per bone, which gives skin contact and bulges at joints.
- Solves
- Character skinning
- Time
- O(j + n (k + i j)) frame
- Space
- O(n + j) extra
- Where
- i = the number of projection steps per vertex; j = the number of joints; k = the largest number of joints per vertex; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Implicit skinning is a correction step that runs after a geometric skinning method such as linear blend skinning or dual quaternion skinning. In a precomputation it builds, for each bone, an implicit surface that fits the part of the mesh around the bone, and it composes these fields into one field of the whole character. Each vertex stores its value in the rest pose. In each frame the fields move rigidly with their bones, the mesh is skinned as usual, and each vertex then walks along the gradient of until it is back at its own value:
A vertex stops when the gradient turns sharply between two steps, which happens where the field of one bone meets that of another. So the skin on the inside of a bent elbow does not pass into itself, it forms a contact crease, and the outside keeps its shape. Vaillant and co-authors fit the field of each bone with Hermite radial basis functions, and compose them with operators that can make a bulge where two parts press together. The code on this page is a 2D toy of the method; it says so in its header.
In plain words
Plain skinning moves the skin with the bones, but where a limb bends, the skin on the inside sinks into the limb and passes through itself. Implicit skinning first builds a smooth invisible shape around each bone, like a sausage that fits the flesh of that bone. Each point of the skin remembers how deep it sat in these shapes before the animation. When the bones move, the shapes move with them. After the usual skinning, each point is pushed in or out until it sits at its old depth again. Where the inner sides of a bent elbow meet, the points stop, and the skin forms a fold instead of passing through itself.
The problem
The input is the rest mesh, the skinning weights, the rest transforms of the bones, and in each frame the skinning transforms of the pose (see bind pose). The output is the deformed mesh, with no self-intersection near the joints and with the shape of the rest pose kept where the parts do not touch. This is the character skinning problem with a correction for contact.
The algorithm
The field of bone is a function with values in that is on the surface of its part of the mesh, larger inside and 0 far away; in the paper it is an HRBF fit, changed to a compact support. In the pose, the field of the bone is , and the union of the bones is the maximum in the simplest composition.
IMPLICIT-SKINNING(V, W, bones, C)- 1
iso_i ← f(v_i) for each rest vertex ▷ precomputation - 2
v_i ← Σ_j w_ij C_j v_i for each vertex ▷ geometric skinning, here LBS - 3
for each vertex i - 4
PROJECT(v_i, iso_i): - 5
g_prev ← none - 6
repeat at most K times - 7
f, g ← the field and its gradient at v_i, with the bones in the pose - 8
if |f - iso_i| ≤ tol: stop - 9
if g_prev ≠ none and angle(g, g_prev) > α_max: stop ▷ contact - 10
v_i ← v_i + σ (iso_i - f) g / |g|²; g_prev ← g - 11
repeat R times: move each vertex along the surface toward a smooth spacing, then PROJECT it again - 12
return V
Line L10 is a damped Newton step for the scalar equation along the gradient (see Newton's method). Line L9 is the contact rule: where the vertex crosses into the region of another bone, the gradient of the union changes direction, and the vertex stops there. Line L11 is the relaxation: the projection moves each vertex on its own, so neighbors can bunch up; a tangential move toward a better spacing, followed by a new projection, evens them out. The paper also applies a Laplacian smoothing in this step.
The toy of the code is in the plane. The field of a bone with the rest radius is , with the distance to the segment of the bone and for and 0 beyond, so it is at the distance . The mesh is a closed polygon, and the relaxation moves each vertex along the chord of its two neighbors to the point with its rest parameter on that chord. The step , the angle , the cap of on the step length and the two rounds of relaxation are tuning values of the toy.
Example
Take the toy arm: two bones from to and from to with the radius , the outline of a stadium with 80 vertices, and the weight of bone 1 rising smoothly over . Bend bone 1 about the elbow .
| bend | nearest skin point to a bone, LBS | nearest skin point to a bone, implicit | vertices stopped at contact |
|---|---|---|---|
| 4 | |||
| 8 | |||
| 10 |
The rest skin is at the distance from the bones. All the vertices that converged are back at the field value within , so they are at least from both bones; the stopped vertices lie within of the line where the two fields are equal, on the inside of the elbow. These values come from the code of this page and are measurements of the toy.
Correctness
The proofs are in proofs/correctness.md; they are proved properties of the method in exact arithmetic, not of the HRBF fit.
- In the bind pose every vertex is at its iso value, the relaxation target is the vertex itself, and the mesh does not move.
- Under a common rigid motion of all the bones, the skinned mesh and the fields move together, so the vertices again do not move relative to the bones.
- Each step of line L10 changes by to first order, so for a small enough and a smooth field the error shrinks by about the factor per step.
- In the toy, a converged vertex with has the distance at least from every bone, because the union is the maximum.
- For one bone in the toy, the projection moves the vertex on the line from its nearest point on the bone, to the distance where the field has the value .
Proof: The projection of implicit skinning keeps the bind pose and rigid motions, reduces the field error, and keeps converged vertices outside the bones of the toyfull
We use the notation of the page. The arithmetic is exact, the weights of each vertex are nonnegative with the sum 1, and each is rigid. The field in the pose is , and the rest field is . These are properties of the method with given fields; how well an HRBF field fits a mesh is a separate question.
Bind pose and rigid motions
Lemma 1. In the bind pose, with all , the output is the rest mesh.
Proof. Line L2 gives , because the weights sum to 1. Then by line L1, so line L8 stops each projection at once. In the relaxation of the toy, the target of vertex is with the rest neighbors and , and the move is . Here , so the vertex does not move, and the new projection stops at once.
Lemma 2. If all for one rigid motion , the output is for every vertex.
Proof. Line L2 gives . , so and the projection stops at once. A rigid motion keeps dot products of differences, so the chord parameter of between and is , and the relaxation does not move it, as in Lemma 1.
The projection step
Lemma 3. Let be twice continuously differentiable near , with and . After the step , the new error is .
Proof. By Taylor's theorem, , since .
So for and a start close enough to the level set, where stays away from 0, the error shrinks by about the factor per step and the projection converges linearly; is Newton's method along the gradient. The cap on the step length of the toy only shortens steps, and a shorter step along still lowers the error to first order when .
The toy fields
The toy field of one bone is with on and beyond, where is the distance to the segment. on , so is strictly decreasing on , with , and .
Lemma 4. For one bone, a projection that starts at a point with , keeps at every step and converges, ends at , where is the nearest point of the segment to , , and is the unique distance with .
Proof. The gradient of the distance is , so and every step moves the point along the line from through . Every point with has the nearest point on the segment, because is normal to the segment at an inner point , and points away from the segment at an end point ; so the direction stays , the point stays of the form , and the field is . A converged point has , and is strictly decreasing, so .
Lemma 5. In the toy, a vertex that converges to the value has the distance at least from every bone.
Proof. is the maximum of the bone fields, so every bone field at is at most . A bone field at the distance is , because is strictly decreasing.
The contact rule
Where two bone fields of the toy are equal, the union switches from one to the other, and its gradient jumps from to . On the inside of a bend the two directions and point away from different bones, and the angle between them grows with the bend, so line L9 stops a vertex that crosses that line. This is a heuristic rule: the angle is a tuning value, and a vertex that stops is not at its iso value.
Complexity
The geometric skinning costs . A projection step evaluates the field; in the toy this costs for all the bones, and in practice only the few bones near a vertex count, because the fields have a compact support. With steps per vertex, the frame costs . The fit of the fields is a precomputation; the paper reports real-time rates for whole characters (a measurement of the paper).
Properties
- It keeps the rest shape where the parts of the mesh do not touch, and makes a contact crease where they do; LBS and DQS make neither.
- It is a correction: it needs a good geometric skinning as the start, because the projection only moves vertices along the gradient, a short way.
- The iso value of each vertex is stored, so the rest details of the mesh survive, unlike a projection onto one level of the field.
- The result depends on tuning values: the step, the angle of the contact stop, and the number of relaxation rounds (heuristics).
- It is not exact: the projection is iterative and stops after a fixed number of steps or at contact.
Variants and improvements
- Composition operators. Instead of the union by maximum, the paper composes the fields of neighbor bones with gradient-based operators, which can give a bulge where two parts press together.
- Tracking. A later paper of the same group tracks the iso level over time to handle large and fast motions more robustly.
- Delta mush. Delta mush also corrects a geometric skinning, by smoothing and stored details, with no fields and no contact.
- Centers of rotation. CoR skinning removes the collapse at joints with a better blend instead of a correction, but it does not model contact.
- Distance fields. In the simplest case the field is a function of a signed distance to each bone, as in the toy.
When to use it
Use it when the skin of a character must fold at the joints without passing through itself, as at the inside of an elbow or a knee, and a per-vertex iteration each frame is acceptable. For a fast game character with no visible contact, LBS or DQS with corrective shapes is cheaper.
Pitfalls
- Large motions. If the geometric skinning moves a vertex too far, the projection can reach the wrong part of the field or leave the support, where the gradient is zero; the toy stops such a vertex.
- Flat fields near the bone. Deep inside the field the gradient is small and a Newton step can be very long; cap the step, as the toy does.
- The contact angle. Too small an angle stops vertices that are not in contact, and too large an angle lets the skin pass through itself.
- Thin parts. The field of a bone must fit its part of the mesh well; for fingers and other thin parts the fit is hard.
- Relaxation drift. Without a target from the rest mesh, the relaxation moves vertices even in the bind pose; keep the rest pose a fixed point.
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
implicit_skinning.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-skinning/. The authors are listed in prov/KN8M9F.jsonl.
"""A 2D toy of implicit skinning (Vaillant et al. 2013).
This is a toy. The method of the paper fits a field to the mesh part of each
bone with Hermite radial basis functions (HRBF) and composes the fields with
gradient-based operators. Here each bone has a closed-form field of the
distance to its segment, the fields are composed by the union max, and the
mesh is a closed polygon in the plane. The steps of the method are the same:
1. In the rest pose, store the field value iso_i of each vertex.
2. In each frame, skin the vertices by linear blend skinning, and move the
field of each bone rigidly with the bone.
3. Project each vertex back to its own iso value by steps along the
gradient, v <- v + sigma (iso_i - f(v)) grad f / |grad f|^2, and stop the
vertex when the gradient turns by more than MAX_ANGLE between two steps,
which marks a contact between two parts of the skin.
4. Relax the vertices: move each one along the chord of its two neighbors
toward the point that has its rest position along the chord, and
project them again. The paper relaxes in the tangent plane of the
surface; the chord is the 2D stand-in of this toy.
The field of a bone with the rest radius r is f = t(d / (2 r)), where d is
the distance to the segment of the bone and t(u) = 1 - 3 u^2 + 2 u^3 for
u < 1 and 0 beyond. So f = 0.5 at the distance r, f decreases outward, and
the support is the distance 2 r. The field is flat near the bone, so a step
is cut to the length MAX_STEP. SIGMA, MAX_ANGLE, MAX_STEP, the relaxation
step and the number of rounds are tuning values of this toy.
"""
import math
from anim import add, dot, norm, scale, sub
SIGMA = 0.35
MAX_ANGLE = math.radians(55.0)
TOL = 1e-10
MAX_ITER = 200
RELAX = 0.3
MAX_STEP = 0.05
def apply2(m, p):
"""Apply a 3 by 3 homogeneous transform of the plane to a point."""
return (m[0][0] * p[0] + m[0][1] * p[1] + m[0][2], m[1][0] * p[0] + m[1][1] * p[1] + m[1][2])
def segment_distance(x, a, b):
"""Return the distance from x to the segment ab and its gradient in x."""
ab = sub(b, a)
t = dot(sub(x, a), ab) / dot(ab, ab)
t = 0.0 if t < 0.0 else 1.0 if t > 1.0 else t
d = sub(x, add(a, scale(ab, t)))
n = norm(d)
if n == 0.0:
return 0.0, (0.0, 0.0)
return n, scale(d, 1.0 / n)
def bone_field(x, bone):
"""Return (f, grad f) of one bone given as (a, b, r)."""
a, b, r = bone
d, gd = segment_distance(x, a, b)
u = d / (2.0 * r)
if u >= 1.0:
return 0.0, (0.0, 0.0)
f = 1.0 - 3.0 * u * u + 2.0 * u ** 3
df = (-6.0 * u + 6.0 * u * u) / (2.0 * r)
return f, scale(gd, df)
def field(x, bones):
"""Return (f, grad f) of the union max of the bone fields."""
best = (0.0, (0.0, 0.0))
for bone in bones:
fg = bone_field(x, bone)
if fg[0] > best[0]:
best = fg
return best
def pose_bones(bones, palette):
"""Move each bone (a, b, r) by its rigid transform."""
return [(apply2(m, a), apply2(m, b), r) for (a, b, r), m in zip(bones, palette)]
def project(x, iso, bones, sigma=SIGMA, max_angle=MAX_ANGLE, tol=TOL, max_iter=MAX_ITER, max_step=MAX_STEP):
"""Move x toward the level iso of the field. Return (x, reason)."""
g_prev = None # @line L5
for _ in range(max_iter): # @line L6
f, g = field(x, bones) # @line L7
gg = dot(g, g)
if abs(f - iso) <= tol: # @line L8
return x, "converged"
if gg == 0.0:
return x, "outside"
if g_prev is not None:
c = dot(g, g_prev) / math.sqrt(gg * dot(g_prev, g_prev))
if math.acos(max(-1.0, min(1.0, c))) > max_angle: # @line L9
return x, "contact"
step = scale(g, sigma * (iso - f) / gg)
ls = norm(step)
if ls > max_step: # near the bone the field is flat and the step is too long
step = scale(step, max_step / ls)
x = add(x, step) # @line L10
g_prev = g
return x, "max_iter"
def rest_iso(vertices, bones):
"""Return the field value of each rest vertex."""
return [field(v, bones)[0] for v in vertices]
def chord_params(vertices):
"""Return s_i, the position of the rest vertex i along the chord of its two neighbors.
The relaxation moves a vertex along the chord toward the point with the
same parameter, so the rest polygon is a fixed point.
"""
n = len(vertices)
out = []
for i in range(n):
a, b = vertices[i - 1], vertices[(i + 1) % n]
c = sub(b, a)
out.append(dot(sub(vertices[i], a), c) / dot(c, c))
return out
def lbs2(vertices, weights, palette):
out = []
for v, wi in zip(vertices, weights):
p = (0.0, 0.0)
for j, w in wi:
p = add(p, scale(apply2(palette[j], v), w))
out.append(p)
return out
def implicit_skinning(vertices, weights, bones, palette, iso=None, rounds=2, relax=RELAX, sigma=SIGMA, max_angle=MAX_ANGLE):
"""Return (positions, reasons) of a closed polygon skinned by the toy method.
vertices: the rest polygon in order; weights: lists of (joint, weight);
bones: rest bones (a, b, r), one per joint; palette: 3 by 3 rigid
transforms of the plane, one per joint.
"""
if iso is None:
iso = rest_iso(vertices, bones) # @line L1
posed = pose_bones(bones, palette)
pts = lbs2(vertices, weights, palette) # @line L2
n = len(pts)
reasons = [None] * n
for i in range(n): # @line L3
pts[i], reasons[i] = project(pts[i], iso[i], posed, sigma, max_angle) # @line L4
s = chord_params(vertices)
for _ in range(rounds): # @line L11
moved = []
for i in range(n):
a, b = pts[i - 1], pts[(i + 1) % n]
c = sub(b, a)
cc = dot(c, c)
target = add(a, scale(c, s[i]))
moved.append(add(pts[i], scale(c, relax * dot(sub(target, pts[i]), c) / cc)))
for i in range(n):
pts[i], reasons[i] = project(moved[i], iso[i], posed, sigma, max_angle)
return pts, reasons # @line L12
test_implicit_skinning.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-skinning/. The authors are listed in prov/KN8M9F.jsonl.
"""Tests of the 2D toy of implicit skinning.
They check the field and its gradient against central differences, the
projection against a bisection on the distance for one bone, the bind pose,
a common rigid motion, the bend of an arm (the skin stays out of the bones
where linear blend skinning lets it in), the per-vertex iso values of a
bumpy arm, and the contact stop.
"""
import math
import random
import anim
from implicit_skinning import (
bone_field,
field,
implicit_skinning,
lbs2,
pose_bones,
project,
rest_iso,
segment_distance,
)
R = 0.25
BONES = [((0.0, 0.0), (1.0, 0.0), R), ((1.0, 0.0), (2.0, 0.0), R)]
def smoothstep(x):
x = min(1.0, max(0.0, x))
return x * x * (3.0 - 2.0 * x)
def arm(n=80, r=R, bump=0.0):
"""The outline of a stadium around the two bones, counterclockwise."""
pts = []
length = 2.0
per = 2.0 * length + 2.0 * math.pi * r
for k in range(n):
s = per * k / n
if s < length:
p, nrm = (s, -r), (0.0, -1.0)
elif s < length + math.pi * r:
a = -math.pi / 2 + (s - length) / r
p, nrm = (length + r * math.cos(a), r * math.sin(a)), (math.cos(a), math.sin(a))
elif s < 2 * length + math.pi * r:
p, nrm = (length - (s - length - math.pi * r), r), (0.0, 1.0)
else:
a = math.pi / 2 + (s - 2 * length - math.pi * r) / r
p, nrm = (r * math.cos(a), r * math.sin(a)), (math.cos(a), math.sin(a))
pts.append(anim.add(p, anim.scale(nrm, bump * r * math.sin(7.0 * s))))
weights = []
for v in pts:
w1 = smoothstep((v[0] - 0.8) / 0.4)
weights.append([jw for jw in ((0, 1.0 - w1), (1, w1)) if jw[1] > 0.0])
return pts, weights
def bend(theta):
rot = anim.rot2(theta)
c = (1.0, 0.0)
return [anim.eye(3), anim.make_T(rot, anim.sub(c, anim.matvec(rot, c)))]
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def min_dist(p, bones):
return min(segment_distance(p, a, b)[0] for a, b, _ in bones)
def test_gradient_matches_central_differences():
rng = random.Random(1)
for _ in range(200):
x = (rng.uniform(-0.4, 2.4), rng.uniform(-0.45, 0.45))
if min_dist(x, BONES) < 0.02:
continue
f, g = field(x, BONES)
d0 = bone_field(x, BONES[0])[0]
d1 = bone_field(x, BONES[1])[0]
if abs(d0 - d1) < 1e-3:
continue # the union max has a kink there
num = anim.num_grad(lambda y: field(y, BONES)[0], x, h=1e-6)
assert close(g, num, 1e-6)
assert 0.0 <= f <= 1.0
def test_projection_matches_bisection_for_one_bone():
rng = random.Random(2)
bone = [((0.0, 0.0), (1.0, 0.3), R)]
for _ in range(50):
x = (rng.uniform(-0.3, 1.3), rng.uniform(-0.3, 0.6))
d, gd = segment_distance(x, bone[0][0], bone[0][1])
if d < 0.05 or d > 0.45:
continue
iso = rng.uniform(0.1, 0.9)
got, why = project(x, iso, bone)
assert why == "converged"
# reference: bisection on the distance for t(d / 2r) = iso
lo, hi = 0.0, 2.0 * R
for _ in range(200):
mid = 0.5 * (lo + hi)
u = mid / (2.0 * R)
if 1.0 - 3.0 * u * u + 2.0 * u ** 3 > iso:
lo = mid
else:
hi = mid
foot = anim.sub(x, anim.scale(gd, d))
assert close(got, anim.add(foot, anim.scale(gd, lo)), 1e-8)
def test_bind_pose_gives_rest_mesh():
pts, weights = arm(bump=0.2)
out, why = implicit_skinning(pts, weights, BONES, [anim.eye(3), anim.eye(3)])
for a, b in zip(out, pts):
assert close(a, b, 1e-12)
assert all(w == "converged" for w in why)
def test_common_rigid_motion():
rng = random.Random(3)
pts, weights = arm(bump=0.2)
g = anim.make_T(anim.rot2(rng.uniform(-3.0, 3.0)), (rng.uniform(-2.0, 2.0), rng.uniform(-2.0, 2.0)))
out, _ = implicit_skinning(pts, weights, BONES, [g, g])
for a, v in zip(out, pts):
assert close(a, anim.T_apply(g, v), 1e-9)
def test_bend_keeps_the_skin_out_of_the_bones():
pts, weights = arm()
for deg in (60.0, 100.0, 130.0):
pal = bend(math.radians(deg))
posed = pose_bones(BONES, pal)
out, why = implicit_skinning(pts, weights, BONES, pal)
lbs = lbs2(pts, weights, pal)
assert min(min_dist(p, posed) for p in out) > min(min_dist(p, posed) for p in lbs)
for p, w in zip(out, why):
if w == "converged":
assert abs(field(p, posed)[0] - 0.5) < 1e-9
assert min_dist(p, posed) > R - 1e-8
else:
assert w == "contact"
# a stopped vertex lies near the plane where the two fields meet
d0 = segment_distance(p, *posed[0][:2])[0]
d1 = segment_distance(p, *posed[1][:2])[0]
assert abs(d0 - d1) < 0.05
if deg >= 100.0:
assert "contact" in why
def test_bumpy_arm_keeps_each_iso_value():
pts, weights = arm(bump=0.2)
iso = rest_iso(pts, BONES)
assert max(iso) - min(iso) > 0.1
pal = bend(math.radians(45.0))
posed = pose_bones(BONES, pal)
out, why = implicit_skinning(pts, weights, BONES, pal, iso=iso)
for p, w, s in zip(out, why, iso):
if w == "converged":
assert abs(field(p, posed)[0] - s) < 1e-9
def test_contact_stop():
# two bones at a right angle; a point inside the corner is pushed by one
# field across the line where the other takes over
bones = [((0.0, 0.0), (1.0, 0.0), R), ((0.0, 0.0), (0.0, 1.0), R)]
x = (0.2, 0.18)
_, why = project(x, 0.5, bones)
assert why == "contact"
_, why = project(x, 0.5, bones, max_angle=math.pi)
assert why != "contact"
History
Rodolphe Vaillant, Loïc Barthe, Gaël Guennebaud, Marie-Paule Cani, Damien Rohmer, Brian Wyvill, Olivier Gourmel and Mathias Paulin presented implicit skinning at SIGGRAPH 2013. It joined the line of work on implicit surfaces in modeling, with composition operators of fields, and the line of work on skinning methods that correct LBS and DQS.
References
- Rodolphe Vaillant, Loïc Barthe, Gaël Guennebaud, Marie-Paule Cani, Damien Rohmer, Brian Wyvill, Olivier Gourmel and Mathias Paulin, Implicit skinning, real-time skin deformation with contact modeling, ACM Transactions on Graphics 32(4), article 125, 2013 (SIGGRAPH 2013), the fields of the bones (HRBF and compact support), the composition operators, and the projection of the vertices with the gradient stop and the relaxation
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 KN8M9F Edit this page History Report an error Markdown