Algorithm Search⌘K

Algorithmresearch

Example-based facial rigging

Also called example-based blendshape generation.

Generate a personalized blendshape rig from a few example expressions of an actor by optimizing the targets with a generic rig as prior.

Time
O(I (T n (n + m) + n^3 + m n^2 K) + V^3 + n V^2) total
Space
O(T (n + m) + V^2 + n V) extra
Where
I = the number of alternations; K = the number of coordinate descent sweeps per weight step; T = the number of triangles; V = the number of vertices; m = the number of examples; n = the number of targets
Properties
deterministicnot exactofflineiterative

Example-based facial rigging builds a blendshape rig for one actor from a generic rig and a few scans of the actor's face. A good face rig has dozens of targets, such as "jaw open" or "left smile", and modeling them by hand for each actor takes days. A scan of the actor making an expression is easy to get, but a scan is a mix of many targets at once, not a single target. Li, Weise and Pauly (2010) start from the deformation transfer of a generic rig onto the actor's neutral face, and then change the targets so that suitable blends of them reproduce the scans, while each target stays close to its generic counterpart.

In plain words

A generic face rig knows what "open the jaw" or "smile" does to a face, but not how this actor does it. You have a few scans of the actor making faces, and a rough guess of how much of each target is in each scan. First, copy each generic target onto the actor with deformation transfer. Then improve two things in turn. Change the targets so that the blends with the current weights look like the scans, but do not let a target drift far from what the generic one does. Then change the weights so that the blends of the new targets fit the scans better, with every weight between 0 and 1. Repeat a few times. The work is done on how each triangle stretches and turns, and at the end one linear solve turns that back into vertex positions.

The problem

The input is:

  • a generic rig with the neutral face A0A_0 and the targets A1,…,AnA_1, \ldots, A_n;
  • the neutral face B0B_0 of the actor;
  • mm example expressions S1,…,SmS_1, \ldots, S_m of the actor;
  • a first guess αj0∈[0,1]n\alpha^0_j \in [0, 1]^n of the blend weights of each example.

All meshes share one triangulation, which the method needs, for example after a template is fitted to each scan. The output is the actor targets B1,…,BnB_1, \ldots, B_n and the weights αj\alpha_j of the examples.

For a triangle tt, the deformation gradient of a mesh XX relative to B0B_0 is the matrix Ft(X)F_t(X) that maps the edges of the triangle in B0B_0 to its edges in XX. Let Di,t=Ft(Bi)−ID_{i,t} = F_t(B_i) - I be the unknowns, Rj,t=Ft(Sj)−IR_{j,t} = F_t(S_j) - I the examples, and Hi,t=Gi,t−IH_{i,t} = G_{i,t} - I the prior, where Gi,tG_{i,t} is the gradient of the generic target AiA_i relative to A0A_0. The method minimizes

E(D,α)=∑j∑t∥∑iαijDi,t−Rj,t∥F2+β∑i∑t∥Di,t−Hi,t∥F2E(D, \alpha) = \sum_j \sum_t \Big\lVert \sum_i \alpha_{ij} D_{i,t} - R_{j,t} \Big\rVert_F^2 + \beta \sum_i \sum_t \lVert D_{i,t} - H_{i,t} \rVert_F^2

subject to 0≤αij≤10 \le \alpha_{ij} \le 1. The first term is the fit to the examples, and the second is the prior from the generic rig. With D=HD = H, each target changes its triangles like the generic target, which is deformation transfer for meshes with one triangulation.

The code in impl/python works on 2D triangle meshes and uses this energy only. The paper works on 3D face meshes, and its energy has more detail than this one, for example in how the prior is weighted; this page keeps the structure of the method.

The algorithm

  1. EXAMPLE-BASED-RIG(A₀ … Aₙ, B₀, S₁ … Sₘ, α⁰, β)
  2. 1H_i ← gradients of A_i relative to A₀, minus I; D ← H
  3. 2R_j ← gradients of S_j relative to B₀, minus I; α ← α⁰
  4. 3repeat a fixed number of times:
  5. 4D ← argmin_D E(D, α) (one linear solve)
  6. 5α_j ← argmin over [0, 1]ⁿ of E(D, α), for each j
  7. 6record E(D, α)
  8. 7B_i ← the mesh whose gradients fit I + D_i in least squares, with one vertex fixed
  9. 8return B₁ … Bₙ and α

Line L4 separates into one small problem per entry of the 2 by 2 (or 3 by 3) matrices. For an entry pp of triangle tt, the vector z=(D1[p],…,Dn[p])z = (D_{1}[p], \ldots, D_{n}[p]) solves

(A⊤A+βI)z=A⊤(R1[p],…,Rm[p])+β(H1[p],…,Hn[p]),(A^\top A + \beta I) z = A^\top (R_1[p], \ldots, R_m[p]) + \beta (H_1[p], \ldots, H_n[p]),

where AA is the mm by nn matrix of the weights. The matrix A⊤A+βIA^\top A + \beta I is the same for every entry, so the code solves it once with all entries as right hand sides.

Line L5 is a least squares problem with bounds, one per example, with the Gram matrix of the targets. The code solves it by cyclic coordinate descent: it sets each weight to its exact minimizer, clipped to [0,1][0, 1], until no weight moves.

Line L7 is the Poisson step of deformation transfer: the vertex positions of BiB_i minimize ∑t∥Ft(Bi)−(I+Di,t)∥F2\sum_t \lVert F_t(B_i) - (I + D_{i,t}) \rVert_F^2, which is a sparse Poisson type system whose matrix depends only on B0B_0.

Example

The tests use a strip of six vertices and four triangles. The generic rig has a target "open", which stretches the top row up by 50 percent, and a target "smile", which shears the right side. The actor has a different neutral face and true targets that differ from the transferred generic ones. There are three examples, made with the true weights (1,0)(1, 0), (0,1)(0, 1) and (0.6,0.5)(0.6, 0.5), and the first guesses are (0.9,0.1)(0.9, 0.1), (0.1,0.8)(0.1, 0.8) and (0.5,0.5)(0.5, 0.5).

With β=0.1\beta = 0.1 and 30 alternations, EE falls from 1.5231.523 at the start to 0.1750.175 after the first step and to 0.0770.077 at the end. The largest vertex error of the targets is:

target deformation transfer example-based rig
open 0.286 0.026
smile 0.347 0.032

The weights become (1,0.021)(1, 0.021), (0,1)(0, 1) and (0.625,0.534)(0.625, 0.534), close to the true ones.

Two check values. For one target, one example and one entry, line L4 gives z=(αr+βh)/(α2+β)z = (\alpha r + \beta h) / (\alpha^2 + \beta); with α=0.5\alpha = 0.5 and β=0.25\beta = 0.25, this is z=r+h/2z = r + h / 2. For one target, line L5 gives the weight clip⁡(d⊤r/d⊤d,0,1)\operatorname{clip}(d^\top r / d^\top d, 0, 1); with d=(1,0,0,0)d = (1, 0, 0, 0), the entries r1=2r_1 = 2, 0.30.3 and −0.4-0.4 give the weights 1, 0.3 and 0.

Correctness

The proofs are in proofs/correctness.md.

  • Line L4 is exact. For β>0\beta > 0, A⊤A+βIA^\top A + \beta I is positive definite, so the step is the unique minimizer of EE in DD for the fixed weights.
  • Line L5 does not increase EE, and converges to the minimizer. Each coordinate update is an exact minimization of a convex function of one variable on [0,1][0, 1], and coordinate descent on a convex quadratic with box constraints reaches the minimizer. The tests compare it with a brute force search over all faces of the box.
  • EE never increases. Both steps minimize EE in one block of variables, so the sequence of values is nonincreasing, and it converges, because E≥0E \ge 0.
  • The generic rig is a fixed point. If the actor is the generic face and the examples are exact blends of the generic targets with the given weights, then E=0E = 0 at the start, and the method returns the generic targets and the given weights.
  • Line L7 is exact for exact gradients. If the gradients come from a mesh, the least squares solution is that mesh, up to the fixed vertex.

The method finds a local minimum of a nonconvex problem in (D,α)(D, \alpha), and the result depends on the first guess of the weights.

Proof: Each step of example-based facial rigging minimizes the energy in one block, so the energy never increasesfull

We use the notation of the page. Flatten each DiD_i, RjR_j and HiH_i over all triangles and entries into vectors di,rj,hi∈RPd_i, r_j, h_i \in \mathbb{R}^P. Then E(D,α)=∑j∥∑iαijdi−rj∥2+β∑i∥di−hi∥2E(D, \alpha) = \sum_j \lVert \sum_i \alpha_{ij} d_i - r_j \rVert^2 + \beta \sum_i \lVert d_i - h_i \rVert^2, with β>0\beta > 0. The arithmetic is exact.

The blendshape step

Theorem 1. For fixed weights, line L4 returns the unique minimizer of EE in DD.

Proof. EE is a sum over the entries p=1,…,Pp = 1, \ldots, P of terms that each depend only on zp=(d1[p],…,dn[p])z_p = (d_1[p], \ldots, d_n[p]):

E=∑p(∥Azp−ρp∥2+β∥zp−ηp∥2),E = \sum_p \left( \lVert A z_p - \rho_p \rVert^2 + \beta \lVert z_p - \eta_p \rVert^2 \right),

where Aji=αijA_{ji} = \alpha_{ij}, ρp=(r1[p],…,rm[p])\rho_p = (r_1[p], \ldots, r_m[p]) and ηp=(h1[p],…,hn[p])\eta_p = (h_1[p], \ldots, h_n[p]). Each term is a quadratic in zpz_p with the Hessian 2(A⊤A+βI)2 (A^\top A + \beta I), which is positive definite, because A⊤A⪰0A^\top A \succeq 0 and β>0\beta > 0. So each term has a unique minimizer, where the gradient 2A⊤(Azp−ρp)+2β(zp−ηp)2 A^\top (A z_p - \rho_p) + 2 \beta (z_p - \eta_p) vanishes, that is, (A⊤A+βI)zp=A⊤ρp+βηp(A^\top A + \beta I) z_p = A^\top \rho_p + \beta \eta_p. This is the system that blendshape_step solves, with one right hand side per entry. □\square

The weight step

For one example, drop the index jj and write φ(a)=∥Ma−r∥2=a⊤Ga−2b⊤a+∥r∥2\varphi(a) = \lVert M a - r \rVert^2 = a^\top G a - 2 b^\top a + \lVert r \rVert^2, with M=(d1,…,dn)M = (d_1, \ldots, d_n), G=M⊤MG = M^\top M and b=M⊤rb = M^\top r. EE is the sum of the φ\varphi of the examples plus a term that does not depend on α\alpha, and the examples do not share weights, so minimizing EE in α\alpha is minimizing each φ\varphi on [0,1]n[0, 1]^n.

Lemma 1. A coordinate update with Gii>0G_{ii} > 0 sets aia_i to the minimizer of φ\varphi over ai∈[0,1]a_i \in [0, 1] with the other coordinates fixed, and if it moves aia_i from uu to vv, then φ\varphi decreases by at least Gii(u−v)2G_{ii} (u - v)^2.

Proof. As a function of aia_i, φ\varphi is q(x)=Giix2−2cx+constq(x) = G_{ii} x^2 - 2 c x + \text{const} with c=bi−∑k≠iGikakc = b_i - \sum_{k \ne i} G_{ik} a_k. Its minimizer on R\mathbb{R} is c/Giic / G_{ii}, and since qq is a convex parabola, its minimizer on [0,1][0, 1] is the clipped value vv, which the code computes. At vv, the optimality on the interval gives q′(v)(u−v)≥0q'(v) (u - v) \ge 0 for every u∈[0,1]u \in [0, 1]. Then q(u)=q(v)+q′(v)(u−v)+Gii(u−v)2≥q(v)+Gii(u−v)2q(u) = q(v) + q'(v)(u - v) + G_{ii} (u - v)^2 \ge q(v) + G_{ii} (u - v)^2. □\square

If Gii=0G_{ii} = 0, then di=0d_i = 0, φ\varphi does not depend on aia_i, and the code leaves aia_i unchanged.

Theorem 2. The weights of line L5 are in [0,1][0, 1], φ\varphi never increases during the sweeps, and every limit point of the sweeps minimizes φ\varphi on [0,1]n[0, 1]^n. If GG is positive definite, the sweeps converge to the unique minimizer.

Proof. The start is clipped to [0,1][0, 1] and every update is clipped, so the weights stay in the box. By Lemma 1, φ\varphi never increases. Let aka^k be the point after sweep kk, and let Π\Pi be the map of one sweep, which is continuous as a composition of affine maps and clipping. The sum over all updates of Gii(u−v)2G_{ii} (u - v)^2 is at most φ(a0)−min⁡φ\varphi(a^0) - \min \varphi, which is finite, so the moves go to 0, and ∥Π(ak)−ak∥→0\lVert \Pi(a^k) - a^k \rVert \to 0. The box is compact, so a subsequence converges to some a∗a^*, and by continuity Π(a∗)=a∗\Pi(a^*) = a^*. A fixed point of Π\Pi is left unchanged by its first update, so a1∗a^*_1 is the minimizer of φ\varphi in a1a_1; then the second update sees the same point, and so on for every coordinate. So for every ii, ai∗a^*_i minimizes φ\varphi in aia_i on [0,1][0, 1], which means ∂iφ(a∗)≥0\partial_i \varphi(a^*) \ge 0 if ai∗=0a^*_i = 0, ≤0\le 0 if ai∗=1a^*_i = 1, and =0= 0 otherwise. These are the KKT conditions of a convex function on a box, so a∗a^* is a minimizer. If G≻0G \succ 0, the minimizer is unique, every convergent subsequence has the same limit, and the whole sequence converges to it. □\square

The code stops when no coordinate moves by more than 10−1410^{-14}, which is a fixed point of Π\Pi up to rounding.

The energy never increases

Theorem 3. The values of EE recorded at line L6 and after line L4 are nonincreasing, and they converge.

Proof. Line L4 replaces DD by the minimizer of E(⋅,α)E(\cdot, \alpha), which is at most the value at the old DD, by Theorem 1. Line L5 starts the sweeps of each example at the current weights, and by Theorem 2 the sweeps do not increase φ\varphi, so they do not increase EE. A nonincreasing sequence of numbers with E≥0E \ge 0 converges. □\square

The fixed point

Theorem 4. Let B0=A0B_0 = A_0, let each example be the exact blend Sj=A0+∑iαij0(Ai−A0)S_j = A_0 + \sum_i \alpha^0_{ij} (A_i - A_0) with αj0∈[0,1]n\alpha^0_j \in [0, 1]^n, and let h1,…,hnh_1, \ldots, h_n be linearly independent. Then the method returns α=α0\alpha = \alpha^0 and Bi=AiB_i = A_i, up to the fixed vertex.

Proof. The gradient of a triangle is linear in the deformed positions for a fixed rest mesh, so rj=∑iαij0hir_j = \sum_i \alpha^0_{ij} h_i. At the start, D=HD = H and α=α0\alpha = \alpha^0, so both terms of EE are 0. E≥0E \ge 0, so this point minimizes EE in DD, and by the uniqueness of Theorem 1, line L4 returns D=HD = H. With D=HD = H, φj(αj0)=0\varphi_j(\alpha^0_j) = 0, which is the minimum, and GG is the Gram matrix of independent vectors, so it is positive definite and the minimizer is unique. The sweeps start at αj0\alpha^0_j, and by Lemma 1 no update moves a minimizer, so line L5 keeps α0\alpha^0. By induction, every alternation keeps (H,α0)(H, \alpha^0), and line L7 gets the gradients I+HiI + H_i, which are the gradients of AiA_i relative to A0=B0A_0 = B_0, so by Theorem 5 it returns AiA_i. □\square

The Poisson step

Theorem 5. On a connected mesh, if the target gradients I+Di,tI + D_{i,t} are the gradients Ft(X)F_t(X) of a mesh XX, line L7 returns XX translated so that the fixed vertex is at its rest position.

Proof. The objective ∑t∥Ft(Y)−Ft(X)∥F2\sum_t \lVert F_t(Y) - F_t(X) \rVert_F^2 is at least 0, and it is 0 at Y=X+cY = X + c for the translation cc that moves the fixed vertex to its rest position, because a translation does not change edges. It remains to show that this zero is unique. If YY and Y′Y' both give 0 with the same fixed vertex, then W=Y−Y′W = Y - Y' satisfies [wb−wa,wc−wa]Qt=0[w_b - w_a, w_c - w_a] Q_t = 0 for every triangle, where QtQ_t is the inverse of the rest edge matrix, so wa=wb=wcw_a = w_b = w_c. Neighboring triangles share vertices, so on a connected mesh WW is constant, and it is 0 at the fixed vertex. □\square

For gradients that do not come from a mesh, line L7 returns the least squares fit, which is the deformation transfer step.

The check values

For n=m=1n = m = 1 and one entry, Theorem 1 gives (α2+β)z=αr+βh(\alpha^2 + \beta) z = \alpha r + \beta h. With α=0.5\alpha = 0.5 and β=0.25\beta = 0.25, α2+β=0.5\alpha^2 + \beta = 0.5, so z=(0.5r+0.25h)/0.5=r+h/2z = (0.5 r + 0.25 h) / 0.5 = r + h / 2. For n=1n = 1 and d=(1,0,0,0)d = (1, 0, 0, 0), Lemma 1 gives a=clip⁡(d⊤r/d⊤d,0,1)=clip⁡(r1,0,1)a = \operatorname{clip}(d^\top r / d^\top d, 0, 1) = \operatorname{clip}(r_1, 0, 1), which is 1, 0.3 and 0 for r1=2r_1 = 2, 0.30.3 and −0.4-0.4.

Complexity

The costs are in the real RAM model. One step of line L4 costs O(Tnm)O(T n m) to form the right hand sides, O(n3)O(n^3) to factor the matrix and O(Tn2)O(T n^2) to solve for all entries. One step of line L5 costs O(Tn2)O(T n^2) for the Gram matrix, O(Tnm)O(T n m) for the right hand sides and O(mn2K)O(m n^2 K) for KK sweeps of coordinate descent. Line L7 factors one matrix of size VV once and solves for the nn targets. The code uses dense matrices, which gives O(V3+nV2)O(V^3 + n V^2) for line L7; with a sparse factorization, as in practice, this is much less.

Properties

  • Personal: the targets follow the actor's examples, not only the generic rig.
  • Semantic: each target keeps the meaning of its generic counterpart, so the rig works with the same controls and the same animation data.
  • Few examples: the prior fills in what the examples do not show, so a few scans are enough.
  • Bounded weights: the weights of the examples stay in [0,1][0, 1], as in a blendshape rig.
  • Local: the method is an alternating minimization, so it finds a local minimum.

Variants and improvements

  • Without the prior. With β=0\beta = 0, the targets fit the examples only, and with fewer examples than targets the problem has many solutions. The prior is what makes few examples enough.
  • More examples. With many examples, the fit term dominates and the targets approach the true targets of the actor.
  • Weighted prior. Weight the prior per triangle, so that a target may change more in some regions than in others.
  • Online adaptation. Later work on real-time face tracking adapts the rig to the user during tracking instead of in a separate step.

When to use it

Use example-based facial rigging when you have a good generic face rig and must make a rig for a new actor or character with the same targets, from a few scans or sculpts. If the new face is a different character with no examples at all, deformation transfer alone gives a first rig. If you must edit an existing rig to hit a pose, blendshape direct manipulation solves for the weights instead.

Pitfalls

  • Correspondence. All meshes must share one triangulation. The scans must be fitted with a template first, and errors in that fit go into the targets.
  • Bad first guesses. The weights of each example start from a guess, and the method finds a local minimum near it. A guess that names the wrong targets gives wrong targets.
  • The value of β\beta. A large β\beta keeps the generic targets and ignores the examples; a small one overfits the examples, and with few examples the targets can become strange where no example constrains them. On the toy face of the example, β=0.01\beta = 0.01 gives a larger error on the open target than β=0.1\beta = 0.1, 0.055 against 0.026.
  • Scale ambiguity. Without the prior, a target scaled by cc with its weights divided by cc fits the same examples. The prior fixes the scale.
  • Rigid motion. The examples must be aligned with the neutral face, because a head motion in a scan changes every gradient.

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.

anim.pyI0RawGitHub
# 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
example_based_facial_rigging.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/example-based-facial-rigging/. The authors are listed in prov/3M9YWE.jsonl.
"""Example-based facial rigging (after Li, Weise and Pauly 2010), on 2D triangle meshes.

The input is a generic blendshape rig (a neutral A0 and targets A1..An), the
neutral B0 of an actor, m example expressions S1..Sm of the actor, and a
first guess of the blend weights of each example. All meshes share one
triangulation. The output is a blendshape rig of the actor: targets B1..Bn
and the weights of the examples.

The method works with deformation gradients. For triangle t, the gradient
of a mesh X relative to the actor neutral is the 2 by 2 matrix
F = [x_b - x_a, x_c - x_a] [b_b - b_a, b_c - b_a]^(-1). Let D_i = F(B_i) - I
for the unknown targets, R_j = F(S_j) - I for the examples, and H_i =
G_i - I for the gradients G_i of the generic target i relative to the
generic neutral. The energy is

    E(D, alpha) = sum_j sum_t |sum_i alpha_ij D_i - R_j|_F^2
                  + beta sum_i sum_t |D_i - H_i|_F^2.

The first term asks the rig to reproduce the examples. The second is the
prior: each actor target should change its triangles like the generic
target, which is deformation transfer when the two meshes share a
triangulation. The start is D = H, the deformation transfer of the generic
rig. The method alternates an exact least squares step in D and a bounded
least squares step in alpha, with 0 <= alpha <= 1, and at the end recovers
the vertex positions of each target by a Poisson (least squares) solve.

The paper works on 3D meshes, weights the prior per triangle, and has
further terms; this file keeps the structure of the method only.
"""

from anim import inv, solve, sub


def gradient(rest, deformed, tri):
    """Return the 2 by 2 deformation gradient of one triangle."""
    a, b, c = tri
    e1, e2 = sub(rest[b], rest[a]), sub(rest[c], rest[a])
    f1, f2 = sub(deformed[b], deformed[a]), sub(deformed[c], deformed[a])
    q = inv([[e1[0], e2[0]], [e1[1], e2[1]]])
    return [[f1[r] * q[0][k] + f2[r] * q[1][k] for k in range(2)] for r in range(2)]


def flat_offsets(rest, deformed, tris):
    """Return the list over triangles of the 4 entries of F - I, flattened."""
    out = []
    for tri in tris:
        g = gradient(rest, deformed, tri)
        out.extend([g[0][0] - 1.0, g[0][1], g[1][0], g[1][1] - 1.0])
    return out


def energy(d, alpha, r, h, beta):
    """Return E(D, alpha) for flattened D_i, R_j and H_i."""
    e = 0.0
    for j, rj in enumerate(r):
        for p in range(len(rj)):
            s = sum(alpha[j][i] * d[i][p] for i in range(len(d))) - rj[p]
            e += s * s
    for di, hi in zip(d, h):
        e += beta * sum((x - y) ** 2 for x, y in zip(di, hi))
    return e


def blendshape_step(alpha, r, h, beta):
    """Return the D that minimizes E for fixed alpha.

    For each entry p, the vector (D_1[p], ..., D_n[p]) solves
    (A^T A + beta I) z = A^T (R_1[p], ..., R_m[p]) + beta (H_1[p], ..., H_n[p]),
    where A is the m by n matrix of the weights. The matrix is the same for
    every entry, so it is solved once with all entries as right hand sides.
    """
    n, m, size = len(h), len(r), len(h[0])
    mat = [[sum(alpha[j][a] * alpha[j][b] for j in range(m)) + (beta if a == b else 0.0) for b in range(n)] for a in range(n)]
    rhs = [[sum(alpha[j][a] * r[j][p] for j in range(m)) + beta * h[a][p] for p in range(size)] for a in range(n)]
    z = solve(mat, rhs)
    return [list(row) for row in z]


def bounded_lsq(gram, lin, start, tol=1e-14, max_iter=100000):
    """Minimize a^T G a - 2 b^T a over the box [0, 1]^n by cyclic coordinate descent.

    Each coordinate is set to its exact minimizer, clipped to [0, 1]. The
    objective never increases. The loop stops when no coordinate moves by
    more than tol.
    """
    a = [min(1.0, max(0.0, x)) for x in start]
    n = len(a)
    for _ in range(max_iter):
        move = 0.0
        for i in range(n):
            if gram[i][i] <= 0.0:
                continue
            v = (lin[i] - sum(gram[i][k] * a[k] for k in range(n) if k != i)) / gram[i][i]
            v = min(1.0, max(0.0, v))
            move = max(move, abs(v - a[i]))
            a[i] = v
        if move <= tol:
            break
    return a


def weight_step(d, r, alpha):
    """Return the weights that minimize E for fixed D, each in [0, 1]."""
    n = len(d)
    gram = [[sum(x * y for x, y in zip(d[a], d[b])) for b in range(n)] for a in range(n)]
    out = []
    for j, rj in enumerate(r):
        lin = [sum(x * y for x, y in zip(d[a], rj)) for a in range(n)]
        out.append(bounded_lsq(gram, lin, alpha[j]))
    return out


def poisson_reconstruct(rest, tris, grads, fixed=0):
    """Return the meshes whose triangle gradients fit grads in least squares.

    grads[k] is the list over triangles of 2 by 2 matrices for mesh k. The
    vertex fixed keeps its rest position. The normal matrix depends only on
    the rest mesh, so it is built once for all meshes and both coordinates.
    """
    nv = len(rest)
    free = [v for v in range(nv) if v != fixed]
    col = {v: i for i, v in enumerate(free)}
    qs = []
    for a, b, c in tris:
        e1, e2 = sub(rest[b], rest[a]), sub(rest[c], rest[a])
        qs.append(inv([[e1[0], e2[0]], [e1[1], e2[1]]]))
    size = len(free)
    ata = [[0.0] * size for _ in range(size)]
    atb = [[0.0] * (2 * len(grads)) for _ in range(size)]
    fp = rest[fixed]
    for t, (a, b, c) in enumerate(tris):
        q = qs[t]
        for k in range(2):
            coef = {b: q[0][k], c: q[1][k]}
            coef[a] = coef.get(a, 0.0) - q[0][k] - q[1][k]
            items = [(col[v], w) for v, w in coef.items() if v != fixed]
            shift = coef.get(fixed, 0.0)
            for i, wi in items:
                for j, wj in items:
                    ata[i][j] += wi * wj
            for g, gk in enumerate(grads):
                for r in range(2):
                    val = gk[t][r][k] - shift * fp[r]
                    for i, wi in items:
                        atb[i][2 * g + r] += wi * val
    x = solve(ata, atb)
    meshes = []
    for g in range(len(grads)):
        meshes.append([tuple(fp) if v == fixed else (x[col[v]][2 * g], x[col[v]][2 * g + 1]) for v in range(nv)])
    return meshes


def unflatten(dvec, ntri):
    """Return the list of 2 by 2 matrices I + D for one flattened D."""
    return [[[1.0 + dvec[4 * t], dvec[4 * t + 1]], [dvec[4 * t + 2], 1.0 + dvec[4 * t + 3]]] for t in range(ntri)]


def facial_rig(generic, actor_neutral, examples, alpha0, tris, beta=0.1, iterations=20):
    """Return (targets, alpha, history).

    generic is [A0, A1, ..., An], actor_neutral is B0, examples is
    [S1, ..., Sm], and alpha0[j] is the first guess of the weights of
    example j. history holds E after the start and after each step.
    """
    a0 = generic[0]
    h = [flat_offsets(a0, ai, tris) for ai in generic[1:]]  # @line L1
    r = [flat_offsets(actor_neutral, s, tris) for s in examples]  # @line L2
    d = [list(x) for x in h]
    alpha = [[min(1.0, max(0.0, x)) for x in row] for row in alpha0]
    history = [energy(d, alpha, r, h, beta)]
    for _ in range(iterations):  # @line L3
        d = blendshape_step(alpha, r, h, beta)  # @line L4
        history.append(energy(d, alpha, r, h, beta))
        alpha = weight_step(d, r, alpha)  # @line L5
        history.append(energy(d, alpha, r, h, beta))  # @line L6
    grads = [unflatten(di, len(tris)) for di in d]
    targets = poisson_reconstruct(actor_neutral, tris, grads)  # @line L7
    return targets, alpha, history  # @line L8
test_example_based_facial_rigging.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/example-based-facial-rigging/. The authors are listed in prov/3M9YWE.jsonl.
"""Tests of example-based facial rigging.

If the actor is the generic face, the generic rig is a fixed point. The
energy never increases. The blendshape step is the minimizer in D, and the
weight step matches a brute force search over the faces of the box. The
Poisson step recovers a mesh from its own gradients. On a toy face, the
rig fits the actor much better than deformation transfer alone, and the
weights come close to the true ones. The check values of the page hold.
"""

import itertools
import random

from anim import solve
from example_based_facial_rigging import (
    blendshape_step,
    energy,
    facial_rig,
    flat_offsets,
    gradient,
    poisson_reconstruct,
    unflatten,
    weight_step,
)

V = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (0.0, 1.0), (1.0, 1.0), (2.0, 1.0)]
TRIS = [(0, 1, 4), (0, 4, 3), (1, 2, 5), (1, 5, 4)]
A1 = [(x, 1.5 * y) for x, y in V]  # generic "open"
A2 = [(x + 0.2 * x * y, y) for x, y in V]  # generic "smile"
B0 = [(1.2 * x + 0.1 * y, 0.9 * y + 0.05 * x * x) for x, y in V]
B1 = [(x, y + 0.7 * (y - 0.05 * x * x) / 0.9 * (1.0 + 0.1 * x)) for x, y in B0]
B2 = [(x + 0.3 * x * y, y - 0.05 * x) for x, y in B0]
TRUE_ALPHA = [(1.0, 0.0), (0.0, 1.0), (0.6, 0.5)]
GUESS = [(0.9, 0.1), (0.1, 0.8), (0.5, 0.5)]


def blend(base, targets, weights):
    return [tuple(base[v][k] + sum(w * (t[v][k] - base[v][k]) for w, t in zip(weights, targets)) for k in range(2)) for v in range(len(base))]


EXAMPLES = [blend(B0, [B1, B2], a) for a in TRUE_ALPHA]


def dist(m, n):
    return max(abs(p[k] - q[k]) for p, q in zip(m, n) for k in range(2))


def test_generic_rig_is_a_fixed_point_for_the_generic_actor():
    examples = [blend(V, [A1, A2], a) for a in TRUE_ALPHA]
    targets, alpha, hist = facial_rig([V, A1, A2], V, examples, TRUE_ALPHA, TRIS, beta=0.1, iterations=3)
    assert dist(targets[0], A1) < 1e-10 and dist(targets[1], A2) < 1e-10
    assert max(abs(a - b) for r, s in zip(alpha, TRUE_ALPHA) for a, b in zip(r, s)) < 1e-10
    assert max(hist) < 1e-20


def test_energy_never_increases_and_weights_stay_in_the_box():
    for beta in (1.0, 0.1, 0.01):
        _, alpha, hist = facial_rig([V, A1, A2], B0, EXAMPLES, GUESS, TRIS, beta=beta, iterations=15)
        assert all(hist[i + 1] <= hist[i] + 1e-12 for i in range(len(hist) - 1))
        assert hist[-1] < 0.5 * hist[0]
        assert all(0.0 <= a <= 1.0 for row in alpha for a in row)


def test_blendshape_step_is_the_minimizer():
    rng = random.Random(3)
    n, m, size, beta = 3, 4, 8, 0.2
    alpha = [[rng.random() for _ in range(n)] for _ in range(m)]
    r = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(m)]
    h = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(n)]
    d = blendshape_step(alpha, r, h, beta)
    e = energy(d, alpha, r, h, beta)
    for _ in range(50):
        d2 = [[x + rng.uniform(-1e-3, 1e-3) for x in row] for row in d]
        assert energy(d2, alpha, r, h, beta) > e
    eps = 1e-6
    for i in range(n):
        for p in range(size):
            dp = [row[:] for row in d]
            dm = [row[:] for row in d]
            dp[i][p] += eps
            dm[i][p] -= eps
            assert abs(energy(dp, alpha, r, h, beta) - energy(dm, alpha, r, h, beta)) / (2 * eps) < 1e-7


def brute_force_box(d, rj):
    n = len(d)

    def obj(a):
        return sum((sum(a[i] * d[i][p] for i in range(n)) - rj[p]) ** 2 for p in range(len(rj)))

    best = None
    for faces in itertools.product((0.0, 1.0, None), repeat=n):
        free = [i for i in range(n) if faces[i] is None]
        a = [0.0 if f is None else f for f in faces]
        if free:
            res = [rj[p] - sum(a[i] * d[i][p] for i in range(n)) for p in range(len(rj))]
            g = [[sum(d[i][p] * d[k][p] for p in range(len(rj))) for k in free] for i in free]
            b = [sum(d[i][p] * res[p] for p in range(len(rj))) for i in free]
            for i, v in zip(free, solve(g, b)):
                a[i] = v
        if all(-1e-12 <= x <= 1.0 + 1e-12 for x in a):
            v = obj(a)
            if best is None or v < best[0]:
                best = (v, a)
    return best


def test_weight_step_against_brute_force():
    rng = random.Random(11)
    for _ in range(30):
        n, size = rng.choice((2, 3)), 8
        d = [[rng.uniform(-1, 1) for _ in range(size)] for _ in range(n)]
        r = [[rng.uniform(-1.5, 1.5) for _ in range(size)] for _ in range(2)]
        alpha = weight_step(d, r, [[0.5] * n, [0.0] * n])
        for aj, rj in zip(alpha, r):
            want, _ = brute_force_box(d, rj)
            got = sum((sum(aj[i] * d[i][p] for i in range(n)) - rj[p]) ** 2 for p in range(size))
            assert abs(got - want) < 1e-10
            assert all(0.0 <= a <= 1.0 for a in aj)


def test_poisson_recovers_a_mesh_from_its_gradients():
    grads = [[gradient(B0, mesh, t) for t in TRIS] for mesh in (B1, B2)]
    out = poisson_reconstruct(B0, TRIS, grads)
    for mesh, rec in zip((B1, B2), out):
        shift = (B0[0][0] - mesh[0][0], B0[0][1] - mesh[0][1])
        assert dist([(x + shift[0], y + shift[1]) for x, y in mesh], rec) < 1e-12


def test_rig_beats_deformation_transfer_on_the_toy_face():
    targets, alpha, _ = facial_rig([V, A1, A2], B0, EXAMPLES, GUESS, TRIS, beta=0.1, iterations=30)
    transfer = poisson_reconstruct(B0, TRIS, [unflatten(flat_offsets(V, a, TRIS), len(TRIS)) for a in (A1, A2)])
    for got, dt, want in zip(targets, transfer, (B1, B2)):
        assert dist(got, want) < 0.05
        assert dist(dt, want) > 0.25
    assert max(abs(a - b) for r, s in zip(alpha, TRUE_ALPHA) for a, b in zip(r, s)) < 0.05


def test_check_values_of_the_page():
    d = blendshape_step([[0.5]], [[0.4, 0.0, -0.2, 1.0]], [[0.2, 0.6, 0.0, -1.0]], 0.25)
    want = [0.4 + 0.1, 0.0 + 0.3, -0.2 + 0.0, 1.0 - 0.5]
    assert max(abs(a - b) for a, b in zip(d[0], want)) < 1e-12
    w = weight_step([[1.0, 0.0, 0.0, 0.0]], [[2.0, 0, 0, 0], [0.3, 5, 0, 0], [-0.4, 0, 0, 0]], [[0.5]] * 3)
    assert w == [[1.0], [0.3], [0.0]]

History

Blendshape rigs for faces were modeled by hand for a long time, often with the Facial Action Coding System as a guide for the targets. Sumner and Popović (2004) gave deformation transfer, which copies the targets of one face onto another, but the copies show how the source face moves, not how the new face moves. Li, Weise and Pauly (2010) added examples of the actor and optimized the targets in the space of deformation gradients, with the transferred generic rig as the prior. Later work on real-time face tracking adapted the rig to the user during tracking.

References

  1. Hao Li, Thibaut Weise and Mark Pauly, Example-based facial rigging, ACM Transactions on Graphics 29(4), SIGGRAPH 2010, article 32, the optimization of the actor targets in deformation gradients with the generic rig as a prior, the alternation with the blend weights of the examples, and the reconstruction of the vertex positions

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example