Algorithmadvanced
Direct manipulation of blendshapes
Also called blendshape direct manipulation.
Solve for blendshape weights that move dragged vertices to target positions, regularized toward the current weights to keep edits predictable.
- Solves
- Shape deformation
- Time
- O(m k) dragO(m k^2 + k^3) setupO(k^2) sweep
- Space
- O(m k + k^2) extra
- Where
- k = the number of targets; m = the number of pinned and dragged vertices; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
Direct manipulation of blendshapes lets an animator edit a blendshape face by dragging points of the mesh instead of moving sliders. The animator picks a vertex and drags it to a goal, and may pin other vertices so that they stay where they are. The method finds the weights that bring the picked vertices as close as possible to their goals while they stay close to the current weights. This is a small regularized least squares problem, and it has a closed-form solution, or a box-constrained quadratic program if the weights must stay in . Lewis and Anjyo (2010) gave the method and showed that the regularization term is what makes the edits predictable.
In plain words
A face rig has many sliders, often dozens or more. To get a shape, an animator must know which sliders move which part of the face. Here the animator grabs the face itself, for example the corner of the mouth, and pulls it. The system then asks: which small change of the sliders moves this point to where the mouse is? Many slider changes can do it, because the targets overlap. So the system takes the one that changes the sliders the least from their current values. That choice keeps the rest of the face calm while the animator drags. The animator can pin points that must not move, and the system treats them as goals that do not move.
The problem
The rig is the delta form , with the neutral , the delta matrix and the weights . The input is the current weights , and a set of picked vertices with goals , both pinned and dragged. Let be the rows of at the picked vertices, and let be the goals minus the neutral at those vertices, . The output is the weights
optionally subject to (usually ). The constants and are tuning. The paper uses and , for meshes and weights in the units of its own rigs.
The algorithm
DRAG(D, b₀, goals, w₀, α, μ, bounded)- 1
for each picked vertex i with goal pᵢ: append its 3 rows of D to S, and pᵢ - b₀,ᵢ to m - 2
A ← SᵀS + (α + μ) I - 3
c ← Sᵀm + α w₀ - 4
if not bounded: return solve(A, c) ▷ the free minimizer - 5
w ← clamp(w₀, 0, t) - 6
repeat - 7
for j ← 1 to k: wⱼ ← clamp((cⱼ - Σ_{l≠j} A_jl w_l) / A_jj, 0, t) - 8
until no weight changed by more than tol - 9
return w
Lines L2 and L3 come from the gradient . Line L4 solves , which is equation 4 of the paper in the form with and . While the user drags one vertex, the picked set does not change, so and are computed once and each mouse move costs one matrix-vector product. Lines L5 to L8 are projected Gauss-Seidel: each step minimizes exactly in one coordinate over the interval . The paper solves the bounded problem with a general QP solver; any correct solver gives the same minimizer, because it is unique.
Example
Take one vertex at and two targets with the deltas and at that vertex. The current weights are , and .
Drag the vertex to . Then , and , with .
| quantity | value |
|---|---|
| free weights | |
| vertex | |
| weights as | , which reaches the goal |
The regularization pulls the weights a little toward , so the vertex stops short of the goal. This is intended: the user keeps dragging, and the next solve starts from the new .
Now drag the vertex to , so . The free solution is , and is above 1. With the bound , sits on its bound and . The gradient of the energy in there is , so the energy would decrease if could grow, which the KKT conditions allow at an upper bound. The vertex goes to . The tests check these values.
Correctness
The proofs are in proofs/correctness.md; they hold in exact arithmetic.
- A unique minimizer. If , the Hessian is symmetric positive definite, so is strictly convex and has exactly one minimizer over and exactly one over the box. This is a proved property.
- The free solution. if and only if , so line L4 returns the free minimizer.
- The bounded solution. A point of the box is the minimizer if and only if it meets the KKT conditions: for each , if , if , and if .
- Projected Gauss-Seidel. Each step of line L7 does not increase the energy, and lowers it by at least when changes by . The iterates converge to the minimizer of the box problem. This is also a proved property.
The tests check the free solution against a numerical gradient and random perturbations, and the bounded solution against a brute force that tries every split of the weights into free, at 0 and at 1.
Proof: Direct manipulation of blendshapes returns the unique minimizer of the regularized energy, with and without boundsfull
We use the notation of the page. , , , or with , and
Let and , as in lines L2 and L3. The arithmetic is exact.
The energy
Lemma 1. , so and .
Proof. Expand the three squares: , , and . Collect the quadratic terms into and the linear terms into .
Lemma 2. is symmetric positive definite, so is strictly convex.
Proof. is symmetric and . So for .
The free problem
Theorem 1. Line L4 returns the unique minimizer of over .
Proof. By Lemma 2, is invertible, so has exactly one solution . For any , Lemma 1 gives , because . This is positive for by Lemma 2.
The bounded problem
Let , which is up to a constant, and let .
Lemma 3 (KKT). A point minimizes over if and only if, with , for every : if , if , and if . There is exactly one such point.
Proof. is convex and is convex, so is a minimizer if and only if for all . Because is a product of intervals, this splits into for all and each , which is the stated sign condition. is compact, so a minimizer exists; it is unique because is strictly convex.
Lemma 4 (one step). Fix all coordinates but , and let be replaced by , as in line L7. Then minimizes in the coordinate over , and .
Proof. As a function of alone, with and . Its unconstrained minimum is at , and on an interval the minimum of a convex parabola is at the clamped point. Let and . By the one-dimensional case of Lemma 3, for all . Then . Take .
Theorem 2. The iterates of lines L5 to L8 stay in , does not increase, and the iterates converge to the unique minimizer of over .
Proof. Line L5 and every step of line L7 clamp into , so every iterate is in . By Lemma 4, does not increase at any step. is bounded below on the compact set , so the total decrease is finite. By Lemma 4 the sum over all steps of is finite, where is the change of the step, and . So the changes tend to 0, and the change of a whole sweep tends to 0.
Let be a limit point of the iterates at the ends of sweeps, which exists because is compact. The map that performs one step of line L7 is continuous in . Along the subsequence that tends to , the change of each step tends to 0, so by continuity each coordinate of is a fixed point of its own step. A fixed point of the step for meets the sign condition of Lemma 3 for , by the one-dimensional case of that lemma. So meets all the conditions of Lemma 3, and . Every limit point is and the iterates are in a compact set, so the whole sequence converges to .
The stopping rule of line L8 ends the loop after finitely many sweeps, because the change of a sweep tends to 0. At that point the iterate is close to but not equal to it in general; the test compares it with a brute force over all splits of the coordinates into free, at 0 and at , with the tolerance .
The check values
In the example of the page, , , and . For , and . By Cramer's rule, . For , and the free solution is , with . The point has and with , so by Lemma 3 it is the bounded minimizer.
Complexity
The cost is in the real RAM model, with picked vertices and targets. Lines L1 to L3 cost , and the solve of line L4 costs . During a drag of one vertex with a fixed picked set, a new goal changes only , so the new weights cost with the precomputed . One sweep of lines L6 to L8 costs . The number of sweeps depends on the conditioning of and is not bounded here; on the 15 random problems of the brute force test (4 targets, tolerance ) it is at most 22, which is a measurement of those tests only. The extra space is . Building the mesh from the new weights costs , as for any blendshape model.
Properties
- Deterministic, with a unique answer when .
- Interactive: one small dense solve per edit, independent of the mesh size except through the final evaluation.
- With the problem is underdetermined when , and the plain least squares solution is not unique; the regularization fixes that.
- Pins and drags are the same kind of constraint. A pinned vertex is a goal at its current position.
- The constraints are soft. A goal is met exactly only in the limit and only if it is reachable.
Variants and improvements
- Hard constraints. Equation 1 of the paper keeps exactly and minimizes with a Lagrange multiplier. The soft form is preferred because a drag can ask for an unreachable point, and then the hard form has no solution.
- Weight decay. The term pulls weights toward 0 and keeps them from growing over a long edit session.
- Bounds. The bounded form is a convex QP with a box. Projected gradient descent, active set methods and projected Gauss-Seidel all solve it.
- Sparse weights. An term instead of prefers edits that move few sliders. That is a variant from later work, not from this paper.
- Fitting to captured markers. The same energy with many goals from motion capture markers fits weights to a performance, and the term then gives temporal smoothness. Example-based facial rigging solves weights in a similar bounded way inside a larger fit.
When to use it
Use direct manipulation as an editing mode next to the sliders of a face rig. It works best for fine edits near the current pose, where the linear model and the small regularization give the change the user expects. For large changes, or for posing from a blank face, sliders or a pose library are often faster, because many weight vectors reach one dragged point.
Pitfalls
- Too small an . The targets overlap, so is badly conditioned. With a tiny , small mouse moves give large weight changes of opposite sign. Raise , or add the bounds.
- No bounds. The free solution can leave , as the example shows, and a rig that clamps weights at evaluation time then shows a different face from the one the solver found. Solve with the bounds if the rig has them.
- The linear term of the QP. For this energy the QP is with . Check the sign and the factors when you copy the QP from a paper.
- Vertices that no target moves. Their rows in are zero, so a drag there has no effect. Tell the user, or pick from vertices with nonzero rows only.
- Units. compares squared distances with squared weights, so its useful value depends on the scale of the mesh. A value tuned on one rig does not carry over to another.
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
blendshape_direct_manipulation.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blendshape-direct-manipulation/. The authors are listed in prov/RFBXKQ.jsonl.
"""Direct manipulation of blendshapes (Lewis and Anjyo 2010).
The rig is the delta form v = b_0 + D w, where D has one column per target
and three rows per vertex. The user pins or drags some vertices to goals p_i.
The rows of D at those vertices form the matrix S, and m = p - b_0 at them.
The weights minimize
E(w) = |S w - m|^2 + alpha |w - w0|^2 + mu |w|^2,
where w0 are the current weights. The minimizer solves the linear system
(S^T S + (alpha + mu) I) w = S^T m + alpha w0.
With the bound 0 <= w <= t the problem is a convex quadratic program with
box constraints. This file solves it by projected Gauss-Seidel (cyclic
coordinate descent with clamping), which converges to the unique minimizer
because the matrix is symmetric positive definite when alpha + mu > 0.
The paper uses a general QP solver; the minimizer is the same.
"""
from anim import solve
ALPHA = 0.1 # the value in the paper, a tuning choice
MU = 0.001 # the value in the paper, a tuning choice
def constraint_rows(deltas, b0, goals):
"""Return (S, m) for goals {vertex index: goal point}.
deltas[k][i] is the offset of target k at vertex i (a 3-tuple).
"""
s, m = [], []
for i, p in goals.items(): # @line L1
for c in range(len(p)):
s.append([d[i][c] for d in deltas])
m.append(p[c] - b0[i][c])
return s, m
def normal_system(s, m, w0, alpha, mu):
"""Return (A, c) with A = S^T S + (alpha + mu) I and c = S^T m + alpha w0."""
k = len(w0)
a = [[sum(row[p] * row[q] for row in s) for q in range(k)] for p in range(k)] # @line L2
for p in range(k):
a[p][p] += alpha + mu
c = [sum(row[p] * mi for row, mi in zip(s, m)) + alpha * w0[p] for p in range(k)] # @line L3
return a, c
def energy(s, m, w, w0, alpha, mu):
"""Return E(w) of the module docstring."""
r = sum((sum(a * b for a, b in zip(row, w)) - mi) ** 2 for row, mi in zip(s, m))
return r + alpha * sum((a - b) ** 2 for a, b in zip(w, w0)) + mu * sum(a * a for a in w)
def box_qp(a, c, lo, hi, w_start, tol=1e-13, max_sweeps=100000):
"""Minimize w^T A w / 2 - c^T w subject to lo <= w <= hi by projected Gauss-Seidel."""
w = [min(hi, max(lo, x)) for x in w_start] # @line L5
for _ in range(max_sweeps): # @line L6
big = 0.0
for k in range(len(w)): # @line L7
r = c[k] - sum(a[k][l] * w[l] for l in range(len(w)) if l != k)
new = min(hi, max(lo, r / a[k][k]))
big = max(big, abs(new - w[k]))
w[k] = new
if big <= tol: # @line L8
return w
raise RuntimeError("projected Gauss-Seidel did not converge")
def manipulate(deltas, b0, goals, w0, alpha=ALPHA, mu=MU, bound=None):
"""Return the new weights for the goals, the current weights w0 and the tuning alpha, mu.
bound is None for free weights, or t for the box 0 <= w <= t.
"""
if alpha + mu <= 0.0:
raise ValueError("alpha + mu must be positive")
s, m = constraint_rows(deltas, b0, goals)
a, c = normal_system(s, m, w0, alpha, mu)
if bound is None:
return solve(a, c) # @line L4
return box_qp(a, c, 0.0, bound, w0) # @line L9
def evaluate(deltas, b0, w):
"""Return the mesh b_0 + sum_k w_k d_k."""
out = []
for i, p in enumerate(b0):
out.append(tuple(p[c] + sum(wk * d[i][c] for wk, d in zip(w, deltas)) for c in range(len(p))))
return out
test_blendshape_direct_manipulation.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blendshape-direct-manipulation/. The authors are listed in prov/RFBXKQ.jsonl.
"""Tests of direct manipulation of blendshapes.
The free solution has a zero gradient and beats random perturbations. The
bounded solution equals a brute force over all active sets of the box and
meets the KKT conditions. A large alpha keeps the current weights, and with
a tiny alpha a reachable goal is met. The check value of the page holds.
"""
import itertools
import random
import anim
from blendshape_direct_manipulation import (
box_qp,
constraint_rows,
energy,
evaluate,
manipulate,
normal_system,
)
def make_rig(rng, n=8, k=4):
b0 = [tuple(rng.uniform(-1, 1) for _ in range(3)) for _ in range(n)]
deltas = []
for _ in range(k):
d = [(0.0, 0.0, 0.0)] * n
for i in rng.sample(range(n), 4):
d[i] = tuple(rng.uniform(-0.5, 0.5) for _ in range(3))
deltas.append(d)
return b0, deltas
def goals_for(rng, b0, n_goals=2):
idx = rng.sample(range(len(b0)), n_goals)
return {i: tuple(x + rng.uniform(-0.4, 0.4) for x in b0[i]) for i in idx}
def brute_box(a, c, lo, hi):
"""Exact minimizer by trying every split of the variables into free, low and high."""
k = len(c)
best, best_val = None, float("inf")
for state in itertools.product((0, 1, 2), repeat=k):
free = [i for i in range(k) if state[i] == 0]
w = [lo if s == 1 else hi if s == 2 else 0.0 for s in state]
if free:
sub = [[a[i][j] for j in free] for i in free]
rhs = [c[i] - sum(a[i][j] * w[j] for j in range(k) if state[j] != 0) for i in free]
x = anim.solve(sub, rhs)
if any(v < lo - 1e-12 or v > hi + 1e-12 for v in x):
continue
for i, v in zip(free, x):
w[i] = v
val = 0.5 * sum(w[i] * a[i][j] * w[j] for i in range(k) for j in range(k)) - sum(
ci * wi for ci, wi in zip(c, w)
)
if val < best_val:
best, best_val = w, val
return best
def test_free_solution_has_zero_gradient():
rng = random.Random(1)
b0, deltas = make_rig(rng)
goals = goals_for(rng, b0)
w0 = [rng.uniform(0, 1) for _ in deltas]
w = manipulate(deltas, b0, goals, w0)
s, m = constraint_rows(deltas, b0, goals)
g = anim.num_grad(lambda x: energy(s, m, x, w0, 0.1, 0.001), w)
assert max(abs(x) for x in g) < 1e-7
def test_free_solution_beats_perturbations():
rng = random.Random(2)
b0, deltas = make_rig(rng)
goals = goals_for(rng, b0, 3)
w0 = [rng.uniform(0, 1) for _ in deltas]
w = manipulate(deltas, b0, goals, w0)
s, m = constraint_rows(deltas, b0, goals)
e = energy(s, m, w, w0, 0.1, 0.001)
for _ in range(200):
wp = [x + rng.gauss(0, 0.05) for x in w]
assert energy(s, m, wp, w0, 0.1, 0.001) >= e
def test_bounded_solution_equals_brute_force():
rng = random.Random(3)
for _ in range(15):
b0, deltas = make_rig(rng)
goals = {i: tuple(x + rng.uniform(-1.5, 1.5) for x in b0[i]) for i in rng.sample(range(8), 2)}
w0 = [rng.uniform(0, 1) for _ in deltas]
w = manipulate(deltas, b0, goals, w0, bound=1.0)
s, m = constraint_rows(deltas, b0, goals)
a, c = normal_system(s, m, w0, 0.1, 0.001)
ref = brute_box(a, c, 0.0, 1.0)
assert max(abs(x - y) for x, y in zip(w, ref)) < 1e-9
def test_bounded_solution_meets_kkt():
rng = random.Random(4)
b0, deltas = make_rig(rng, k=5)
goals = {i: tuple(x + rng.uniform(-2, 2) for x in b0[i]) for i in range(3)}
w0 = [0.5] * 5
w = manipulate(deltas, b0, goals, w0, bound=1.0)
s, m = constraint_rows(deltas, b0, goals)
a, c = normal_system(s, m, w0, 0.1, 0.001)
grad = [sum(a[k][l] * w[l] for l in range(5)) - c[k] for k in range(5)]
for wk, gk in zip(w, grad):
assert -1e-12 <= wk <= 1.0 + 1e-12
if 1e-9 < wk < 1.0 - 1e-9:
assert abs(gk) < 1e-9
elif wk <= 1e-9:
assert gk >= -1e-9
else:
assert gk <= 1e-9
def test_large_alpha_keeps_current_weights():
rng = random.Random(5)
b0, deltas = make_rig(rng)
goals = goals_for(rng, b0)
w0 = [0.2, 0.4, 0.6, 0.8]
w = manipulate(deltas, b0, goals, w0, alpha=1e9, mu=0.0)
assert max(abs(x - y) for x, y in zip(w, w0)) < 1e-6
def test_reachable_goal_is_met_with_tiny_alpha():
rng = random.Random(6)
b0, deltas = make_rig(rng, n=6, k=6)
w_true = [rng.uniform(0, 1) for _ in deltas]
v_true = evaluate(deltas, b0, w_true)
goals = {1: v_true[1], 3: v_true[3]}
w = manipulate(deltas, b0, goals, [0.0] * 6, alpha=1e-10, mu=0.0)
v = evaluate(deltas, b0, w)
for i, p in goals.items():
assert max(abs(x - y) for x, y in zip(v[i], p)) < 1e-6
def test_projected_gauss_seidel_on_a_known_box_qp():
a = [[2.0, 0.0], [0.0, 2.0]]
c = [4.0, -2.0]
assert box_qp(a, c, 0.0, 1.0, [0.5, 0.5]) == [1.0, 0.0]
def test_check_value_of_the_page():
b0 = [(0.0, 0.0, 0.0)]
deltas = [[(1.0, 0.0, 0.0)], [(1.0, 1.0, 0.0)]]
w = manipulate(deltas, b0, {0: (1.0, 0.5, 0.0)}, [0.0, 0.0], alpha=0.1, mu=0.0)
assert abs(w[0] - 0.6 / 1.31) < 1e-12
assert abs(w[1] - 0.65 / 1.31) < 1e-12
wf = manipulate(deltas, b0, {0: (2.0, 1.5, 0.0)}, [0.0, 0.0], alpha=0.1, mu=0.0)
assert abs(wf[1] - 1.85 / 1.31) < 1e-12
wb = manipulate(deltas, b0, {0: (2.0, 1.5, 0.0)}, [0.0, 0.0], alpha=0.1, mu=0.0, bound=1.0)
assert abs(wb[0] - 1.0 / 1.1) < 1e-12
assert abs(wb[1] - 1.0) < 1e-12
History
Lewis and Anjyo (2010) gave the form of this page: the soft goals, the regularization toward the current weights, an argument for why that term makes edits predictable, and the bounded QP. Their paper also discusses earlier drag interfaces for faces; this page does not list them, because their details were not checked here. Lewis and others (2014) place the method among the ways to solve for blendshape weights in their survey.
References
- J. P. Lewis and Ken Anjyo, Direct manipulation blendshapes, IEEE Computer Graphics and Applications 30(4), 2010, 42-50, equation 1 (the hard constraint form), equation 2 (the regularized energy with alpha = 0.1), equation 3 (the weight decay mu = 0.001), equation 4 (the solution as w = X m + k) and the bounded quadratic program
- J. P. Lewis, Ken Anjyo, Taehyun Rhee, Mengjie Zhang, Fred Pighin and Zhigang Deng, Practice and theory of blendshape facial models, Eurographics 2014 State of the Art Reports, 199-218, the sections on direct manipulation and on solving for weights (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RFBXKQ Edit this page History Report an error Markdown