Algorithm Search⌘K

Algorithmresearch

Smooth skinning decomposition with rigid bones

Also called SSDR.

Fit bone transforms and sparse convex skinning weights to a sequence of example meshes by alternating least squares, to compress mesh animation.

Time
O(n 2^B (B^3 + B^2 F) + B F n K) iteration
Space
O(n B + B F) extra
Where
B = the number of bones; F = the number of frames; K = the largest number of bones per vertex; n = the number of vertices
Properties
deterministicnot exactofflineiterative

Smooth skinning decomposition with rigid bones (SSDR) takes an animation given as a sequence of meshes and finds a skeleton-free linear blend skinning model that reproduces it. The output is a set of bones, one rigid transform per bone and frame, and skinning weights per vertex. The weights are nonnegative, sum to 1 and have only a few nonzero entries per vertex, so the model plays in any engine that supports linear blend skinning. Le and Deng (2012) fit the model by alternating least squares: fix the bones and solve for the weights, then fix the weights and solve for each bone. Uses are the compression of mesh animations, such as a cloth or a muscle simulation, and the conversion of such data to a rig that a game engine can play.

In plain words

You have a simulation that moves thousands of vertices in each frame, and you want to replay it cheaply. Linear blend skinning moves each vertex as a weighted average of a few rigid motions. If you can find a few rigid motions and a few weights per vertex that explain the data well, you store much less: one transform per bone and frame, and a few weights per vertex. SSDR finds them. It starts by grouping the vertices that move together, with k-means, and fits one rigid motion to each group. Then it repeats two steps. With the motions fixed, each vertex gets the best few weights. With the weights fixed, each bone gets the best rigid motion in each frame, which is a classic problem with a closed form solution. Each step can only lower the error.

The problem

The input is a rest mesh with vertices viv_i, i=1,…,ni = 1, \ldots, n, and FF example meshes with the vertices qf,iq_{f,i}. The unknowns are the rigid transforms (Rf,b,Tf,b)(R_{f,b}, T_{f,b}) for the bones b=1,…,Bb = 1, \ldots, B and the frames ff, and the weights wi,bw_{i,b}. The problem is

min⁡  E=∑f∑i∥qf,i−∑bwi,b(Rf,bvi+Tf,b)∥2\min \; E = \sum_{f} \sum_{i} \Big\lVert q_{f,i} - \sum_{b} w_{i,b} (R_{f,b} v_i + T_{f,b}) \Big\rVert^2

subject to wi,b≥0w_{i,b} \ge 0, ∑bwi,b=1\sum_b w_{i,b} = 1, at most KK nonzero wi,bw_{i,b} per vertex, and Rf,bR_{f,b} a rotation. The number of bones BB and the sparsity KK are inputs. The problem is not convex, and the sparsity constraint is combinatorial, so the method finds a local minimum.

The algorithm

  1. SSDR(rest v, frames q, bones B, sparsity K)
  2. 1cluster the vertex trajectories with k-means into B groups; fit one rigid transform per group and frame; give each vertex weight 1 for its group
  3. 2repeat
  4. 3for each vertex i: w_i ← the least squares weights over the simplex, using all bones
  5. 4keep the K largest entries of w_i and solve again on them only
  6. 5if the old weights of i give a smaller error, keep the old weights
  7. 6for each bone b and frame f: r_(f,i) ← q_(f,i) minus the part of the other bones, for every vertex i
  8. 7(R_(f,b), T_(f,b)) ← the weighted Procrustes fit of w_(i,b) v_i to r_(f,i)
  9. 8until the error decreases by less than a tolerance
  10. 9return the weights and the transforms

Line L3 is a small least squares problem per vertex: stack the positions Rf,bvi+Tf,bR_{f,b} v_i + T_{f,b} of vertex ii over all frames as one column per bone, and find the convex combination of the columns closest to the stacked targets. The paper solves it with an active set method for least squares with nonnegative weights that sum to 1. The code in impl/python is for a few bones, so it tries every support: on each support it solves the equality-constrained system of the KKT conditions and keeps the solution if it is nonnegative. This gives the exact minimizer over the simplex.

Line L4 makes the weights sparse. Line L5 is a safeguard that this code adds, not a step of the paper: the sparse solution is the best on its support but can be worse than the old weights, and the safeguard keeps the error monotone.

Lines L6 and L7 update one bone with all other bones and all weights fixed. With v~i=wi,bvi\tilde v_i = w_{i,b} v_i, the problem is min⁡∑i∥rf,i−wi,bT−Rv~i∥2\min \sum_i \lVert r_{f,i} - w_{i,b} T - R \tilde v_i \rVert^2, a Kabsch problem with weights. The centers are pˉ=∑iwi,b2vi/∑iwi,b2\bar p = \sum_i w_{i,b}^2 v_i / \sum_i w_{i,b}^2 and qˉ=∑iwi,brf,i/∑iwi,b2\bar q = \sum_i w_{i,b} r_{f,i} / \sum_i w_{i,b}^2, the rotation comes from the singular value decomposition of the cross covariance of wi,b(vi−pˉ)w_{i,b} (v_i - \bar p) and rf,i−wi,bqˉr_{f,i} - w_{i,b} \bar q, and T=qˉ−RpˉT = \bar q - R \bar p. In 2D the rotation angle is atan2⁡\operatorname{atan2} of the sums of the cross and dot products, so the code needs no SVD.

The code works in 2D with rigid transforms (θ,t)(\theta, t). The paper also re-initializes bones that end up with too few vertices; the code does not need this for its test data.

Example

The weight step for one vertex with two bones and one 2D frame: let the two candidate positions be (1,0)(1, 0) for bone 1 and (0,1)(0, 1) for bone 2.

target weights squared error
(0.5,0.5)(0.5, 0.5) (0.5,0.5)(0.5, 0.5) 0
(1,1)(1, 1) (0.5,0.5)(0.5, 0.5) 0.5
(2,0)(2, 0) (1,0)(1, 0) 1

The target (0.5,0.5)(0.5, 0.5) is on the segment between the two positions, so the error is zero. The target (1,1)(1, 1) projects onto the middle of the segment, and the distance is 0.5\sqrt{0.5}. The target (2,0)(2, 0) projects onto the line beyond (1,0)(1, 0), at the weights (1.5,−0.5)(1.5, -0.5), which are not allowed, so the best convex weights are (1,0)(1, 0) with the squared error 11.

In the tests, a strip of 39 vertices is skinned to a chain of three bones in six poses, with blended weights near the two joints. From the k-means start, the error goes from 0.0798 to 4.3×10−84.3 \times 10^{-8} in 40 iterations with K=2K = 2, and it never increases. With K=1K = 1, every vertex follows one bone, and the error stops at 0.0753.

Correctness

The proofs are in proofs/correctness.md.

  • The weight step is exact. The minimizer over the simplex is the solution of the KKT system on its support, so trying every support and keeping the best nonnegative solution gives the minimizer.
  • The bone step is exact. The weighted Procrustes formula gives the global minimizer over rotations and translations of the error of one bone in one frame, with the rest fixed.
  • The error does not increase. Line L5 makes the weight step at least as good as the old weights, and each bone step is exact, so it is at least as good as the old transform.
  • The ground truth is a fixed point. If the data come from linear blend skinning with weights and bones of the allowed form, the true weights and bones give the error zero, and no step can leave the zero error.

A monotone error that is bounded below converges, but the limit can be a poor local minimum, and nothing bounds its distance to the global one. Le and Deng show convergence in their experiments, not in a proof.

Proof: Each step of the skinning decomposition is an exact minimization, and the error does not increasefull

We use the notation of the page. For one vertex ii, let ab∈RdFa_b \in \mathbb{R}^{dF} be the stacked positions Rf,bvi+Tf,bR_{f,b} v_i + T_{f,b} over the frames, and y∈RdFy \in \mathbb{R}^{dF} the stacked targets qf,iq_{f,i}, with d=2d = 2 in the code. The error of vertex ii is e(w)=∥Aw−y∥2e(w) = \lVert A w - y \rVert^2 with A=(a1,…,aB)A = (a_1, \ldots, a_B), and E=∑ieiE = \sum_i e_i. The arithmetic is exact.

The weight step

Let ΔS={w:w≥0,∑bwb=1,wb=0 for b∉S}\Delta_S = \{ w : w \ge 0, \sum_b w_b = 1, w_b = 0 \text{ for } b \notin S \} for a set SS of bones.

Lemma 1. For a support T⊆ST \subseteq S, if the matrix

MT=(2AT⊤AT11⊤0)M_T = \begin{pmatrix} 2 A_T^\top A_T & \mathbf{1} \\ \mathbf{1}^\top & 0 \end{pmatrix}

is invertible, its solution (u,λ)(u, \lambda) of MT(u,λ)=(2AT⊤y,1)M_T (u, \lambda) = (2 A_T^\top y, 1) gives the unique minimizer uu of ee over the affine set {w:∑bwb=1,wb=0 for b∉T}\{ w : \sum_b w_b = 1, w_b = 0 \text{ for } b \notin T \}, when ATA_T has full column rank.

Proof. On this set, ee is a convex quadratic in uu, and the Lagrange conditions of min⁡∥ATu−y∥2\min \lVert A_T u - y \rVert^2 subject to 1⊤u=1\mathbf{1}^\top u = 1 are 2AT⊤(ATu−y)+λ1=02 A_T^\top (A_T u - y) + \lambda \mathbf{1} = 0 and 1⊤u=1\mathbf{1}^\top u = 1, which is the system above up to the sign of λ\lambda. For a convex problem with linear constraints, these conditions are sufficient, and the minimizer is unique when AT⊤ATA_T^\top A_T is positive definite. □\square

Theorem 1. simplex_lsq(A, y, S) returns a minimizer of ee over ΔS\Delta_S, when every ATA_T with T⊆ST \subseteq S has full column rank.

Proof. ΔS\Delta_S is compact and ee is continuous, so a minimizer w∗w^* exists. Let TT be the support of w∗w^*. Then w∗w^* minimizes ee over the relative interior of ΔT\Delta_T, which is open in the affine set of Lemma 1, so it is a local and therefore a global minimizer of the convex ee over that affine set. By Lemma 1, the code finds w∗w^* when it tries the support TT, and w∗w^* is nonnegative, so it is a candidate. Every other candidate is a point of ΔS\Delta_S, so its error is at least e(w∗)e(w^*), and the code returns a point with the error e(w∗)e(w^*). □\square

If a matrix MTM_T is singular, the code skips TT. The minimizer over ΔS\Delta_S then still has a support with an invertible MTM_T whenever ASA_S has full column rank, because a subset of independent columns is independent. For the tests, the columns are random or come from distinct rigid motions, and the rank condition holds.

Corollary. Line L3 gives the minimizer over all of the simplex, and line L4 gives the minimizer over ΔS\Delta_S for the set SS of the KK largest entries, which has at most KK nonzero entries. Line L5 then returns the weights wineww^{\text{new}}_i with ei(winew)≤ei(wiold)e_i(w^{\text{new}}_i) \le e_i(w^{\text{old}}_i). The old weights are feasible: they are one-hot after line L1, and every later value comes from line L4 or line L5.

The bone step

Theorem 2. Fix all weights, all bones except bb, and the frame ff. Let ui=wi,bu_i = w_{i,b}, pˉ=∑iui2vi/∑iui2\bar p = \sum_i u_i^2 v_i / \sum_i u_i^2 and qˉ=∑iuiri/∑iui2\bar q = \sum_i u_i r_i / \sum_i u_i^2, with rir_i from line L6, and assume ∑iui2>0\sum_i u_i^2 > 0. Then (R,T)(R, T) of line L7 minimizes G(R,T)=∑i∥ri−ui(Rvi+T)∥2G(R, T) = \sum_i \lVert r_i - u_i (R v_i + T) \rVert^2 over all rotations RR and translations TT.

Proof. The error of frame ff is ∑i∥qf,i−∑cwi,c(Rf,cvi+Tf,c)∥2=G(Rf,b,Tf,b)\sum_i \lVert q_{f,i} - \sum_c w_{i,c} (R_{f,c} v_i + T_{f,c}) \rVert^2 = G(R_{f,b}, T_{f,b}), by the definition of rir_i. For fixed RR, GG is a convex quadratic in TT with the gradient −2∑iui(ri−uiRvi−uiT)-2 \sum_i u_i (r_i - u_i R v_i - u_i T). It is zero at T=qˉ−RpˉT = \bar q - R \bar p, which is the minimizer in TT. With this TT, ri−ui(Rvi+T)=(ri−uiqˉ)−R ui(vi−pˉ)r_i - u_i (R v_i + T) = (r_i - u_i \bar q) - R\, u_i (v_i - \bar p). Let xi=ui(vi−pˉ)x_i = u_i (v_i - \bar p) and zi=ri−uiqˉz_i = r_i - u_i \bar q. Then G=∑i∥zi∥2+∑i∥xi∥2−2∑izi⊤RxiG = \sum_i \lVert z_i \rVert^2 + \sum_i \lVert x_i \rVert^2 - 2 \sum_i z_i^\top R x_i, because RR keeps lengths. So minimizing GG over RR is maximizing ∑izi⊤Rxi\sum_i z_i^\top R x_i. In 2D, with RR the rotation by θ\theta, ∑izi⊤Rxi=cos⁡θ∑ixi⋅zi+sin⁡θ∑ixi×zi\sum_i z_i^\top R x_i = \cos\theta \sum_i x_i \cdot z_i + \sin\theta \sum_i x_i \times z_i, where ×\times is the scalar cross product. This is ρcos⁡(θ−φ)\rho \cos(\theta - \varphi) with φ=atan2⁡(∑ixi×zi,∑ixi⋅zi)\varphi = \operatorname{atan2}(\sum_i x_i \times z_i, \sum_i x_i \cdot z_i), which is largest at θ=φ\theta = \varphi, the angle of line L7. Every rotation has this form, so (R,T)(R, T) is the global minimizer. □\square

In 3D, the same reduction gives the Kabsch problem max⁡tr⁡(R⊤∑izixi⊤)\max \operatorname{tr}(R^\top \sum_i z_i x_i^\top), which the SVD solves. If ∑iui2=0\sum_i u_i^2 = 0, the bone has no influence, GG does not depend on (R,T)(R, T), and any value is a minimizer; the code returns the identity.

The error does not increase

Theorem 3. The values errors[k] returned by ssdr are nonincreasing in kk.

Proof. One iteration first replaces the weights of every vertex. EE is the sum of the eie_i, and each eie_i depends only on the weights of vertex ii for fixed bones, so by the Corollary EE does not increase. Then it replaces bone b=1,…,Bb = 1, \ldots, B in turn. For fixed weights and other bones, EE is the sum over the frames of the GG of Theorem 2, and the transforms of bone bb in different frames appear in different terms, so the new transforms minimize EE over bone bb, and the old transforms are feasible. So EE does not increase in any step. □\square

E≥0E \ge 0, so the values converge. The theorem does not say that the limit is a global minimum, or that the weights and bones converge.

The ground truth is a fixed point

Theorem 4. If qf,i=∑bwi,b∘(Rf,b∘vi+Tf,b∘)q_{f,i} = \sum_b w^\circ_{i,b} (R^\circ_{f,b} v_i + T^\circ_{f,b}) with wi∘∈Δw^\circ_i \in \Delta and at most KK nonzero entries per vertex, then from (w∘,R∘,T∘)(w^\circ, R^\circ, T^\circ) one iteration keeps E=0E = 0.

Proof. E≥0E \ge 0 and E=0E = 0 at the start, and by Theorem 3 EE does not increase. □\square

The check values

With a1=(1,0)a_1 = (1, 0) and a2=(0,1)a_2 = (0, 1), the set {w1a1+w2a2:w∈Δ}\{ w_1 a_1 + w_2 a_2 : w \in \Delta \} is the segment from (1,0)(1, 0) to (0,1)(0, 1). For y=(0.5,0.5)y = (0.5, 0.5), the point w=(0.5,0.5)w = (0.5, 0.5) gives yy, so e=0e = 0. For y=(1,1)y = (1, 1), the support {1,2}\{1, 2\} gives 2w1+λ=22 w_1 + \lambda = 2, 2w2+λ=22 w_2 + \lambda = 2 and w1+w2=1w_1 + w_2 = 1, so w=(0.5,0.5)w = (0.5, 0.5), and e=0.52+0.52=0.5e = 0.5^2 + 0.5^2 = 0.5. For y=(2,0)y = (2, 0), the support {1,2}\{1, 2\} gives 2w1+λ=42 w_1 + \lambda = 4, 2w2+λ=02 w_2 + \lambda = 0, so w1−w2=2w_1 - w_2 = 2 and w=(1.5,−0.5)w = (1.5, -0.5), which is not allowed. The support {1}\{1\} gives e=∥(1,0)−(2,0)∥2=1e = \lVert (1, 0) - (2, 0) \rVert^2 = 1, and the support {2}\{2\} gives e=4+1=5e = 4 + 1 = 5, so the result is w=(1,0)w = (1, 0) with e=1e = 1.

Complexity

The costs are in the real RAM model, for one iteration. The weight step of the code solves up to 2B2^B systems of size at most B+1B + 1 per vertex, each built from dot products of length 2F2F, so it costs O(n2B(B3+B2F))O(n 2^B (B^3 + B^2 F)). The active set method of the paper replaces the factor 2B2^B by the number of its iterations, which is small in practice. Each bone step costs O(FnK)O(F n K), because each vertex has at most KK nonzero weights, so all bones cost O(BFnK)O(B F n K). The extra space is O(nB)O(n B) for the weights and O(BF)O(B F) for the transforms.

Properties

  • Output fits standard pipelines: the result is plain linear blend skinning with rigid bones and convex, sparse weights.
  • Monotone in this code: the error does not increase over the iterations.
  • Local: the result depends on the k-means start and can be a local minimum.
  • No hierarchy: the bones are free rigid transforms, not a skeleton with joints.
  • Lossy: with few bones, the error of a nonrigid motion, such as cloth, does not go to zero.

Variants and improvements

  • Skinning mesh animations. James and Twigg (2005) also fit a skinning model to mesh animations, starting from groups of triangles that rotate together.
  • Skeleton extraction. Later work fits a hierarchy of bones with joints, so that the result is a skeleton an animator can use.
  • Better weights. Instead of the per vertex simplex fit, one can add smoothness of the weights over the mesh, which helps when the examples do not cover all motions.
  • Corrections. Residual errors can be stored as per pose corrections, as in pose space deformation.
  • Other skinning models. The same alternating fit works with dual quaternion skinning, with a harder bone step.
  • Linear compression. Principal component analysis of the frames is the main alternative for the compression of mesh animations, but its output is not a rig.

When to use it

Use SSDR when you have an animation as a sequence of meshes, for example from a simulation or a capture, and you want to play it in a real-time engine that supports only linear blend skinning. It is also useful to compress such data, and to start a rig from examples. If the deformation is far from rigid pieces, such as a wave on water, a skinning model with few bones fits poorly. If you already have a skeleton and want weights for it, use automatic rigging or bounded biharmonic weights instead.

Pitfalls

  • The number of bones. It is an input. Too few bones give a large error, and too many give bones with few vertices that fit noise.
  • The start. k-means can split a rigid part into two clusters or join two parts. Run with several seeds and keep the best fit.
  • Sparse weights can be worse. Keeping the KK largest weights of the full solution does not give the best weights with KK entries. Without a safeguard such as line L5, the error can increase.
  • Rounding of the weights. On a support of one bone, the weight is exactly 1 in theory, but a linear solve can give 1±10−161 \pm 10^{-16}. The code sets it to 1, so the tests that compare the weights exactly pass.
  • Bones with too few vertices. A bone with fewer than three vertices of weight is not determined in 3D. The paper re-initializes such bones.
  • Few frames. With few example frames, the weights are not determined, and the result does not generalize to new poses.

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
skinning_decomposition.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skinning-decomposition/. The authors are listed in prov/H700TR.jsonl.
"""Smooth skinning decomposition with rigid bones (SSDR, Le and Deng 2012), in 2D.

Input: rest vertices v_i and example meshes q_(f,i) for the frames f. Output:
weights w_(i,b) and one rigid transform (R_(f,b), T_(f,b)) per frame and bone,
so that linear blend skinning reproduces the examples:

    E = sum_f sum_i | q_(f,i) - sum_b w_(i,b) (R_(f,b) v_i + T_(f,b)) |^2.

The weights are nonnegative, sum to 1 and have at most K nonzero entries per
vertex. The method alternates two steps.

- Weights, per vertex: least squares over the simplex. This code solves it
  exactly for a few bones by trying every support (the equality-constrained
  solution on each support, kept if it is nonnegative), then keeps the K
  largest weights and solves again on them. If the sparse weights give a
  larger error than the old weights of the vertex, the old ones are kept;
  this safeguard is ours, not the paper's.
- Bones, one at a time with the others fixed, per frame: a weighted
  Procrustes problem with a closed form solution.

The initial bones come from k-means on the vertex trajectories and a rigid
fit per cluster.
"""

import itertools
import math
import random

from anim import cross2, dot, solve


def transform(rt, v):
    """Apply (theta, (tx, ty)) to a 2D point."""
    theta, t = rt
    c, s = math.cos(theta), math.sin(theta)
    return (c * v[0] - s * v[1] + t[0], s * v[0] + c * v[1] + t[1])


def skin(rest, weights, bones, f):
    """Return the skinned mesh of frame f; bones[b][f] = (theta, t)."""
    out = []
    for v, w in zip(rest, weights):
        x = y = 0.0
        for b, wb in enumerate(w):
            if wb != 0.0:
                p = transform(bones[b][f], v)
                x += wb * p[0]
                y += wb * p[1]
        out.append((x, y))
    return out


def error(rest, frames, weights, bones):
    """Return E, the sum of squared distances over all frames and vertices."""
    e = 0.0
    for f, q in enumerate(frames):
        for p, r in zip(skin(rest, weights, bones, f), q):
            e += (p[0] - r[0]) ** 2 + (p[1] - r[1]) ** 2
    return e


def weighted_procrustes(points, targets, w):
    """Return (theta, t) minimizing sum_i |targets_i - w_i (R points_i + t)|^2."""
    sw2 = sum(x * x for x in w)
    if sw2 == 0.0:
        return 0.0, (0.0, 0.0)
    pbar = tuple(sum(x * x * p[k] for x, p in zip(w, points)) / sw2 for k in range(2))
    qbar = tuple(sum(x * r[k] for x, r in zip(w, targets)) / sw2 for k in range(2))
    sc = sd = 0.0
    for x, p, r in zip(w, points, targets):
        pt = (x * (p[0] - pbar[0]), x * (p[1] - pbar[1]))
        qt = (r[0] - x * qbar[0], r[1] - x * qbar[1])
        sc += cross2(pt, qt)
        sd += dot(pt, qt)
    theta = math.atan2(sc, sd)
    c, s = math.cos(theta), math.sin(theta)
    t = (qbar[0] - (c * pbar[0] - s * pbar[1]), qbar[1] - (s * pbar[0] + c * pbar[1]))
    return theta, t


def simplex_lsq(cols, target, allowed):
    """Return the w >= 0 with sum 1 and support in allowed minimizing |sum_b w_b cols_b - target|^2.

    cols[b] is a vector; every support inside allowed is tried.
    """
    best, best_e = None, math.inf
    for r in range(1, len(allowed) + 1):
        for sup in itertools.combinations(allowed, r):
            k = len(sup)
            a = [[0.0] * (k + 1) for _ in range(k + 1)]
            rhs = [0.0] * (k + 1)
            for i, bi in enumerate(sup):
                for j, bj in enumerate(sup):
                    a[i][j] = 2.0 * dot(cols[bi], cols[bj])
                a[i][k] = a[k][i] = 1.0
                rhs[i] = 2.0 * dot(cols[bi], target)
            rhs[k] = 1.0
            try:
                sol = solve(a, rhs)
            except ValueError:
                continue
            if min(sol[:k]) < 0.0:
                continue
            w = [0.0] * len(cols)
            if k == 1:
                sol[0] = 1.0  # the only point of a one-bone simplex, without rounding
            for i, bi in enumerate(sup):
                w[bi] = sol[i]
            res = [-t for t in target]
            for b in sup:
                res = [x + w[b] * y for x, y in zip(res, cols[b])]
            e = dot(res, res)
            if e < best_e:
                best, best_e = w, e
    return best, best_e


def vertex_columns(v, bones, nframes):
    """Return, per bone, the stacked positions of v under the bone over all frames."""
    cols = []
    for bone in bones:
        col = []
        for f in range(nframes):
            col.extend(transform(bone[f], v))
        cols.append(col)
    return cols


def update_weights(rest, frames, weights, bones, k_max):
    """Return the new weights of every vertex (the weight step)."""
    nb = len(bones)
    out = []
    for i, v in enumerate(rest):
        cols = vertex_columns(v, bones, len(frames))
        target = [c for q in frames for c in q[i]]
        w, _ = simplex_lsq(cols, target, list(range(nb)))  # @line L3
        keep = sorted(range(nb), key=lambda b: -w[b])[:k_max]
        w, e = simplex_lsq(cols, target, sorted(keep))  # @line L4
        old = weights[i]
        res = [-t for t in target]
        for b in range(nb):
            if old[b] != 0.0:
                res = [x + old[b] * y for x, y in zip(res, cols[b])]
        if dot(res, res) < e:  # @line L5
            w = list(old)
        out.append(w)
    return out


def update_bone(rest, frames, weights, bones, b):
    """Return the new transforms of bone b for all frames, with the others fixed."""
    w = [weights[i][b] for i in range(len(rest))]
    new = []
    for f, q in enumerate(frames):
        targets = []
        for i, v in enumerate(rest):  # @line L6
            r = list(q[i])
            for c, wc in enumerate(weights[i]):
                if c != b and wc != 0.0:
                    p = transform(bones[c][f], v)
                    r[0] -= wc * p[0]
                    r[1] -= wc * p[1]
            targets.append(tuple(r))
        new.append(weighted_procrustes(rest, targets, w))  # @line L7
    return new


def kmeans(points, k, rng, iters=100):
    """Return the cluster index of each point (Lloyd's algorithm, k-means++ seeding)."""
    centers = [points[rng.randrange(len(points))]]
    while len(centers) < k:
        d = [min(sum((a - b) ** 2 for a, b in zip(p, c)) for c in centers) for p in points]
        r = rng.random() * sum(d)
        acc = 0.0
        for p, x in zip(points, d):
            acc += x
            if acc >= r:
                centers.append(p)
                break
    labels = None
    for _ in range(iters):
        new = [min(range(k), key=lambda j: sum((a - b) ** 2 for a, b in zip(p, centers[j]))) for p in points]
        if new == labels:
            break
        labels = new
        for j in range(k):
            members = [p for p, lab in zip(points, labels) if lab == j]
            if members:
                centers[j] = tuple(sum(c) / len(members) for c in zip(*members))
    return labels


def initialize(rest, frames, nbones, rng):
    """Return (weights, bones) from k-means on the trajectories and a rigid fit per cluster."""
    traj = [tuple(c for q in frames for c in q[i]) for i in range(len(rest))]
    labels = kmeans(traj, nbones, rng)
    weights = [[1.0 if labels[i] == b else 0.0 for b in range(nbones)] for i in range(len(rest))]
    bones = []
    for b in range(nbones):
        w = [weights[i][b] for i in range(len(rest))]
        bones.append([weighted_procrustes(rest, q, w) for q in frames])
    return weights, bones


def ssdr(rest, frames, nbones, k_max=2, iters=30, seed=0, tol=1e-12):
    """Return (weights, bones, errors), errors[0] being the error after initialization."""
    rng = random.Random(seed)
    weights, bones = initialize(rest, frames, nbones, rng)  # @line L1
    errors = [error(rest, frames, weights, bones)]
    for _ in range(iters):  # @line L2
        weights = update_weights(rest, frames, weights, bones, k_max)
        for b in range(nbones):
            bones[b] = update_bone(rest, frames, weights, bones, b)
        errors.append(error(rest, frames, weights, bones))
        if errors[-2] - errors[-1] <= tol * (1.0 + errors[-2]):  # @line L8
            break
    return weights, bones, errors  # @line L9
test_skinning_decomposition.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skinning-decomposition/. The authors are listed in prov/H700TR.jsonl.
"""Tests of smooth skinning decomposition with rigid bones.

The weight step is checked against a brute force search over a grid of the
simplex and against the KKT conditions, and the bone step against a brute
force search over the angle. The error does not increase over the
iterations, the ground truth is a fixed point, and data made by linear blend
skinning is fitted closely from the k-means start. The weights are
nonnegative, sum to 1 and have at most K nonzero entries. The check values of
the page hold.
"""

import math
import random

from skinning_decomposition import (
    error,
    simplex_lsq,
    skin,
    ssdr,
    transform,
    update_bone,
    update_weights,
    weighted_procrustes,
)

REST = [(0.25 * k, y) for k in range(13) for y in (-0.2, 0.0, 0.2)]


def true_weights(x):
    if x <= 0.75:
        return [1.0, 0.0, 0.0]
    if x < 1.25:
        t = (x - 0.75) / 0.5
        return [1.0 - t, t, 0.0]
    if x <= 1.75:
        return [0.0, 1.0, 0.0]
    if x < 2.25:
        t = (x - 1.75) / 0.5
        return [0.0, 1.0 - t, t]
    return [0.0, 0.0, 1.0]


def chain(a, b, c):
    def child(theta, pivot, parent):
        pt = transform(parent, pivot)
        th = parent[0] + theta
        co, si = math.cos(th), math.sin(th)
        return (th, (pt[0] - (co * pivot[0] - si * pivot[1]), pt[1] - (si * pivot[0] + co * pivot[1])))

    b0 = (a, (0.0, 0.0))
    b1 = child(b, (1.0, 0.0), b0)
    return [b0, b1, child(c, (2.0, 0.0), b1)]


POSES = [(0, 0, 0), (0.3, 0.5, -0.4), (-0.2, 0.8, 0.6), (0.5, -0.6, 0.9), (0.1, 1.0, -0.8), (-0.4, -0.3, 0.3)]
W_TRUE = [true_weights(v[0]) for v in REST]
B_TRUE = [[chain(*p)[b] for p in POSES] for b in range(3)]
FRAMES = [skin(REST, W_TRUE, B_TRUE, f) for f in range(len(POSES))]


def sq(cols, w, target):
    r = [-t for t in target]
    for b, wb in enumerate(w):
        r = [x + wb * y for x, y in zip(r, cols[b])]
    return sum(x * x for x in r)


def test_simplex_lsq_against_a_grid():
    rng = random.Random(1)
    for _ in range(20):
        cols = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(3)]
        target = [rng.gauss(0, 1) for _ in range(6)]
        w, e = simplex_lsq(cols, target, [0, 1, 2])
        assert all(x >= 0.0 for x in w) and abs(sum(w) - 1.0) < 1e-12
        assert abs(e - sq(cols, w, target)) < 1e-9
        steps = 60
        best = min(
            sq(cols, (i / steps, j / steps, 1 - (i + j) / steps), target)
            for i in range(steps + 1)
            for j in range(steps + 1 - i)
        )
        assert e <= best + 1e-12


def test_simplex_lsq_kkt():
    rng = random.Random(2)
    for _ in range(20):
        cols = [[rng.gauss(0, 1) for _ in range(8)] for _ in range(4)]
        target = [rng.gauss(0, 1) for _ in range(8)]
        w, _ = simplex_lsq(cols, target, [0, 1, 2, 3])
        r = [-t for t in target]
        for b in range(4):
            r = [x + w[b] * y for x, y in zip(r, cols[b])]
        g = [2.0 * sum(x * y for x, y in zip(c, r)) for c in cols]
        lam = min(g[b] for b in range(4) if w[b] > 1e-12)
        for b in range(4):
            if w[b] > 1e-12:
                assert abs(g[b] - lam) < 1e-8
            else:
                assert g[b] >= lam - 1e-8


def test_weighted_procrustes_against_an_angle_search():
    rng = random.Random(3)
    pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
    tg = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
    w = [rng.uniform(0, 1) for _ in range(10)]

    def cost(theta, t):
        return sum(
            (r[0] - x * transform((theta, t), p)[0]) ** 2 + (r[1] - x * transform((theta, t), p)[1]) ** 2
            for x, p, r in zip(w, pts, tg)
        )

    def best_t(theta):
        sw2 = sum(x * x for x in w)
        c, s = math.cos(theta), math.sin(theta)
        return tuple(
            sum(x * (r[k] - x * (c * p[0] - s * p[1] if k == 0 else s * p[0] + c * p[1])) for x, p, r in zip(w, pts, tg))
            / sw2
            for k in range(2)
        )

    theta, t = weighted_procrustes(pts, tg, w)
    e = cost(theta, t)
    grid = min(cost(a, best_t(a)) for a in (2 * math.pi * i / 3600 for i in range(3600)))
    assert e <= grid + 1e-12


def test_ground_truth_is_a_fixed_point():
    w = update_weights(REST, FRAMES, W_TRUE, B_TRUE, 2)
    assert error(REST, FRAMES, w, B_TRUE) < 1e-20
    bones = [list(b) for b in B_TRUE]
    for b in range(3):
        bones[b] = update_bone(REST, FRAMES, w, bones, b)
    assert error(REST, FRAMES, w, bones) < 1e-20


def test_error_does_not_increase_and_fit_is_close():
    w, bones, errs = ssdr(REST, FRAMES, 3, k_max=2, iters=40, seed=0)
    assert all(errs[i + 1] <= errs[i] + 1e-12 for i in range(len(errs) - 1))
    assert errs[-1] < 1e-5 * errs[0]
    for row in w:
        assert all(x >= 0.0 for x in row)
        assert abs(sum(row) - 1.0) < 1e-12
        assert sum(1 for x in row if x > 0.0) <= 2


def test_sparsity_one_bone_per_vertex():
    w, _, errs = ssdr(REST, FRAMES, 3, k_max=1, iters=10, seed=0)
    assert all(sorted(row) == [0.0, 0.0, 1.0] for row in w)
    assert all(errs[i + 1] <= errs[i] + 1e-12 for i in range(len(errs) - 1))


def test_check_values_of_the_page():
    cols = [[1.0, 0.0], [0.0, 1.0]]
    for target, want, e_want in (
        ([0.5, 0.5], [0.5, 0.5], 0.0),
        ([1.0, 1.0], [0.5, 0.5], 0.5),
        ([2.0, 0.0], [1.0, 0.0], 1.0),
    ):
        w, e = simplex_lsq(cols, target, [0, 1])
        assert all(abs(a - b) < 1e-12 for a, b in zip(w, want))
        assert abs(e - e_want) < 1e-12

History

Fitting a skinning model to examples was studied before SSDR, for example by James and Twigg (2005). Bones that are general affine maps can fit more motions, but many engines expect rigid bones, and weights without constraints are hard to edit. Le and Deng (2012) kept the bones rigid and the weights convex and sparse, and showed that alternating least squares with these constraints fits many mesh animations with a small number of bones. The method is now a common way to convert simulations to rigs for games.

References

  1. Binh Huy Le and Zhigang Deng, Smooth skinning decomposition with rigid bones, ACM Transactions on Graphics 31(6), SIGGRAPH Asia 2012, article 199, the formulation of the fit as linear blend skinning with rigid bones and nonnegative, affine and sparse weights, the k-means initialization, the weight update and the bone update by weighted Procrustes (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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.iteration
  • 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