Algorithm Search⌘K

Algorithmadvanced

Meshless shape matching

Also called shape matching deformation.

Pull particles toward goal positions given by the best rigid or linear transform of the rest shape, found by polar decomposition each step.

Time
Θ(n) precompute · step
Space
Θ(n) step
Where
n = the number of particles of a body
Properties
angular momentum conservingdeterministicnot exactlinear momentum conservingnot needs mesh
Origin
Matthias Müller, Bruno Heidelberger, Matthias Teschner, Markus Gross, 2005

Meshless shape matching moves a soft body made of particles without a mesh and without elastic forces. In each step it finds the rotation and translation that best map the rest shape onto the current particles, in the mass weighted least squares sense, and pulls each particle a fraction α\alpha of the way toward its place in that rigid copy. Müller, Heidelberger, Teschner and Gross (2005) proposed it for games: a step costs Θ(n)\Theta(n), the pull never overshoots the goal, and with a fixed goal the motion neither grows nor decays for any Δt\Delta t. A linear or quadratic fit instead of the rotation gives softer bodies.

In plain words

Keep a photo of the object in its rest shape. In each frame, lay the photo over the particles: slide it and turn it until it covers them as well as possible, with heavy particles counting more. The place of each particle on the photo is its goal. Then give each particle a push toward its goal, so that it would cover the fraction α\alpha of the gap in one frame, and let it move. A dent pops back out because the photo has no dent. With α=1\alpha = 1 the body snaps back at once and acts rigid. With a small α\alpha it wobbles like jelly. If the photo may also stretch and shear, not only slide and turn, the body can keep some of its deformation.

The problem

The input is one body with nn particles: masses mim_i, rest positions xi0\mathbf x^0_i, current positions xi\mathbf x_i and velocities vi\mathbf v_i, external forces fi\mathbf f_i, a stiffness α∈[0,1]\alpha \in [0, 1] and a step Δt\Delta t. The output is the state after one step. The rest shape must not lie on a line, so that S0=∑miqiqiTS_0 = \sum m_i \mathbf q_i \mathbf q_i^T is invertible. There is no material law to solve: the method is a model of its own, chosen for speed and robustness. The page uses 2D, yy up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s²; the paper works in 3D, and the 2D code is a version of it.

The algorithm

Let qi=xi0−xcm0\mathbf q_i = \mathbf x^0_i - \mathbf x^0_{cm} be the rest positions about the rest center of mass, computed once with S0−1S_0^{-1}.

  1. SHAPE-MATCH-STEP(x, v, m, q, S0⁻¹, α, Δt, mode, β)
  2. 1x_cm <- Σ m_i x_i / Σ m_i; p_i <- x_i - x_cm
  3. 2A_pq <- Σ m_i p_i q_iᵀ ▷ 2 by 2
  4. 3R <- rotation factor of the polar decomposition of A_pq
  5. 4G <- R, or in the linear mode G <- β A~ + (1 - β) R ▷ A~ = A/√det A, A = A_pq S0⁻¹
  6. 5for each particle i: g_i <- G q_i + x_cm ▷ goal
  7. 6for each particle i: v_i <- v_i + α (g_i - x_i)/Δt + Δt f_i/m_i
  8. 7for each particle i: x_i <- x_i + Δt v_i

The best rotation (L1 to L3). The rotation RR and translation t\mathbf t that minimize ∑mi∣Rqi+t−xi∣2\sum m_i |R\mathbf q_i + \mathbf t - \mathbf x_i|^2 are t=xcm\mathbf t = \mathbf x_{cm} and the rotation that maximizes tr⁡(RTApq)\operatorname{tr}(R^T A_{pq}). This is the weighted orthogonal Procrustes problem that the Kabsch algorithm solves, and its answer is the rotation factor of the polar decomposition Apq=RSA_{pq} = RS (Section 3.3, equations (5) to (8)). The paper computes S=(ApqTApq)1/2S = (A_{pq}^T A_{pq})^{1/2} by a diagonalization and R=ApqS−1R = A_{pq} S^{-1}. In 2D there is a closed form, R=R(θ)R = R(\theta) with θ=atan2⁡(a10−a01,a00+a11)\theta = \operatorname{atan2}(a_{10} - a_{01}, a_{00} + a_{11}), which the code uses through the shared polar helper. It is always a rotation; the formula ApqS−1A_{pq} S^{-1} is a reflection when det⁡Apq<0\det A_{pq} < 0, for example after a body is pushed inside out. In 3D, a singular value decomposition gives the same rotation with a sign fix.

Linear deformation (L4). The best linear map is A=ApqS0−1A = A_{pq} S_0^{-1} (Section 4.2). Dividing by det⁡A\sqrt{\det A} in 2D, or by det⁡A3\sqrt[3]{\det A} in 3D, keeps the area or the volume. The blend βA~+(1−β)R\beta\tilde A + (1 - \beta)R lets the body keep a part of its stretch and shear. The code falls back to RR when det⁡A≤0\det A \le 0.

Integration (L6, L7). Equation (9) of the paper adds the pull α(gi−xi)/Δt\alpha(\mathbf g_i - \mathbf x_i)/\Delta t to the velocity and then moves the particles with the new velocity, as in symplectic Euler. The pull is a velocity, not a force, so it does not depend on the mass, and with α≤1\alpha \le 1 a particle at rest never passes its goal in one step.

Example

A stretched square by hand. Four particles of mass 1 rest at (±1,±1)(\pm 1, \pm 1). Now they are at (±2,±1)(\pm 2, \pm 1), stretched along xx, at rest. The center of mass is the origin, so pi=(2a,b)\mathbf p_i = (2a, b) for qi=(a,b)\mathbf q_i = (a, b) with a,b=±1a, b = \pm 1, and Apq=∑piqiT=diag⁡(8,4)A_{pq} = \sum \mathbf p_i \mathbf q_i^T = \operatorname{diag}(8, 4). Then θ=atan2⁡(0,12)=0\theta = \operatorname{atan2}(0, 12) = 0 and R=IR = I, so the goals are the rest positions. With α=0.5\alpha = 0.5, Δt=0.1\Delta t = 0.1 and no gravity, the corner at (2,1)(2, 1) gets the velocity 0.5⋅(1−2)/0.1=−50.5 \cdot (1 - 2)/0.1 = -5 along xx and moves to (1.5,1)(1.5, 1). In the linear mode, S0=diag⁡(4,4)S_0 = \operatorname{diag}(4, 4), so A=diag⁡(2,1)A = \operatorname{diag}(2, 1), det⁡A=2\det A = 2 and A~=diag⁡(2,1/2)\tilde A = \operatorname{diag}(\sqrt 2, 1/\sqrt 2). With β=1\beta = 1 the goal of that corner is (1.414,0.707)(1.414, 0.707): the stretch is turned into an area preserving shape.

The oscillation does not decay (measured). The same square, started at (±2,±1)(\pm 2, \pm 1) with Δt=0.01\Delta t = 0.01 in the rigid mode, oscillates about its rest shape. Over 3000 steps:

α\alpha period in steps (measured) 2π/arccos⁡(1−α/2)2\pi / \arccos(1 - \alpha/2) largest gap, steps 1 to 300 largest gap, steps 2701 to 3000
0.05 28.04 28.04 1.0062 1.0056
0.2 13.93 13.93 1.0260 1.0260
0.5 8.69 8.69 1.0690 1.0690

The gap is the distance of the corner from its goal along xx. The period in steps matches the eigenvalue angle of the fixed goal model (claim 6), and the size of the oscillation stays the same. The period does not depend on Δt\Delta t when it is counted in steps, so in seconds it is proportional to Δt\Delta t: the stiffness that α\alpha gives changes with the step size.

Correctness

The claims are proved in proofs/correctness.md.

  1. Best rigid fit (proved). The translation xcm\mathbf x_{cm} and the rotation of L3 minimize ∑mi∣Rqi+t−xi∣2\sum m_i |R\mathbf q_i + \mathbf t - \mathbf x_i|^2 over all rotations. The test compares the rotation with a scan of 720 angles.
  2. Best linear fit (proved). A=ApqS0−1A = A_{pq} S_0^{-1} is the least squares linear map, and it recovers FF exactly when xi=Fxi0+t\mathbf x_i = F\mathbf x^0_i + \mathbf t. The test checks A~=F/det⁡F\tilde A = F/\sqrt{\det F} for random FF.
  3. No pull at a rigid pose (proved). If the particles are a rotated and moved copy of the rest shape, every goal equals its particle, in all modes.
  4. Momentum (proved). With no external force, a step keeps the linear and the angular momentum exactly, in the rigid and the linear mode, because the pull sums to zero and has zero torque. The test checks both to 10−1010^{-10} over 200 steps.
  5. Snap to the goals (proved). With α=1\alpha = 1 and zero velocity, one step puts every particle on its goal.
  6. Fixed goal model (proved). For a particle with a fixed goal the step is the matrix of equation (11), whose eigenvalues have magnitude 1 for 0<α<40 < \alpha < 4. This is the sense in which the paper calls the method unconditionally stable. It does not cover the real case, where the goals move with the particles; the table above measures that case for one body.
  7. Gravity (proved). Under gravity the center of mass moves by symplectic Euler; the test checks the value −5.3955-5.3955 m after 10 steps of 0.10.1 s.
Proof: The goals are the best rigid or linear fit of the rest shape, and the step keeps linear and angular momentum exactlyfull

We use the notation of the page, in 2D. A body has nn particles with masses mi>0m_i > 0, total mass M=∑miM = \sum m_i, rest positions xi0\mathbf x^0_i and current positions xi\mathbf x_i. Let xcm\mathbf x_{cm} and xcm0\mathbf x^0_{cm} be the centers of mass, qi=xi0−xcm0\mathbf q_i = \mathbf x^0_i - \mathbf x^0_{cm} and pi=xi−xcm\mathbf p_i = \mathbf x_i - \mathbf x_{cm}, so ∑miqi=∑mipi=0\sum m_i \mathbf q_i = \sum m_i \mathbf p_i = 0. Let Apq=∑mipiqiTA_{pq} = \sum m_i \mathbf p_i \mathbf q_i^T and S0=∑miqiqiTS_0 = \sum m_i \mathbf q_i \mathbf q_i^T, which we assume invertible (the rest shape does not lie on a line). The goal positions are gi=Gqi+xcm\mathbf g_i = G \mathbf q_i + \mathbf x_{cm} for a 2×22 \times 2 matrix GG, and the step of lines L6 and L7 is

vi′=vi+αΔt(gi−xi)+Δt fimi,xi′=xi+Δt vi′,\mathbf v_i' = \mathbf v_i + \frac{\alpha}{\Delta t}(\mathbf g_i - \mathbf x_i) + \Delta t\, \frac{\mathbf f_i}{m_i}, \qquad \mathbf x_i' = \mathbf x_i + \Delta t\, \mathbf v_i' ,

equation (9) of Müller et al. (2005). The cross product of two vectors in the plane is the number a×b=axby−aybx\mathbf a \times \mathbf b = a_x b_y - a_y b_x.

The goals are best fits

Lemma 1 (rigid fit). Among all rotations RR and translations t\mathbf t, the sum ∑mi∣Rqi+t−xi∣2\sum m_i |R\mathbf q_i + \mathbf t - \mathbf x_i|^2 is smallest for t=xcm\mathbf t = \mathbf x_{cm} and for the rotation R(θ)R(\theta) with θ=atan2⁡((Apq)10−(Apq)01, (Apq)00+(Apq)11)\theta = \operatorname{atan2}\big((A_{pq})_{10} - (A_{pq})_{01},\ (A_{pq})_{00} + (A_{pq})_{11}\big), which line L3 computes. The rotation is unique unless both arguments of atan2 are zero.

Proof. The sum is a convex quadratic in t\mathbf t with gradient 2∑mi(Rqi+t−xi)=2M(t−xcm)2\sum m_i(R\mathbf q_i + \mathbf t - \mathbf x_i) = 2M(\mathbf t - \mathbf x_{cm}), because ∑miqi=0\sum m_i \mathbf q_i = 0. So t=xcm\mathbf t = \mathbf x_{cm} for every RR. Then the sum is ∑mi∣Rqi−pi∣2=∑mi∣qi∣2+∑mi∣pi∣2−2∑mipi⋅Rqi\sum m_i |R\mathbf q_i - \mathbf p_i|^2 = \sum m_i |\mathbf q_i|^2 + \sum m_i |\mathbf p_i|^2 - 2\sum m_i \mathbf p_i \cdot R\mathbf q_i, and ∑mipi⋅Rqi=tr⁡(RTApq)\sum m_i \mathbf p_i \cdot R\mathbf q_i = \operatorname{tr}(R^T A_{pq}). For R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ)R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix}, tr⁡(RTApq)=cos⁡θ (a00+a11)+sin⁡θ (a10−a01)\operatorname{tr}(R^T A_{pq}) = \cos\theta\,(a_{00} + a_{11}) + \sin\theta\,(a_{10} - a_{01}). This is ρcos⁡(θ−θ∗)\rho\cos(\theta - \theta^*) with ρ=∣(a00+a11,a10−a01)∣\rho = |(a_{00} + a_{11}, a_{10} - a_{01})| and θ∗\theta^* the angle of the formula, so it is largest exactly at θ∗\theta^* when ρ>0\rho > 0. □\square

When det⁡Apq>0\det A_{pq} > 0 this is the rotation factor RR of the polar decomposition Apq=RSA_{pq} = RS with SS symmetric positive definite, the formula of Section 3.3 of the paper. When det⁡Apq<0\det A_{pq} < 0 the paper's formula Apq(ApqTApq)−1/2A_{pq}(A_{pq}^T A_{pq})^{-1/2} would be a reflection, while the formula above is still the best rotation. In both cases RTApqR^T A_{pq} is symmetric: with c=cos⁡θ∗c = \cos\theta^* and s=sin⁡θ∗s = \sin\theta^*, (RTApq)01−(RTApq)10=c a01+s a11−(c a10−s a00)=s(a00+a11)−c(a10−a01)=ρ(sin⁡θ∗cos⁡θ∗−cos⁡θ∗sin⁡θ∗)=0(R^T A_{pq})_{01} - (R^T A_{pq})_{10} = c\,a_{01} + s\,a_{11} - (c\,a_{10} - s\,a_{00}) = s(a_{00} + a_{11}) - c(a_{10} - a_{01}) = \rho(\sin\theta^*\cos\theta^* - \cos\theta^*\sin\theta^*) = 0. We write S=RTApqS = R^T A_{pq} for this symmetric matrix.

Lemma 2 (linear fit). The matrix A=ApqS0−1A = A_{pq} S_0^{-1} minimizes ∑mi∣Aqi−pi∣2\sum m_i |A\mathbf q_i - \mathbf p_i|^2 over all 2×22 \times 2 matrices. If xi=Fxi0+t\mathbf x_i = F\mathbf x^0_i + \mathbf t for all ii, then A=FA = F.

Proof. The sum is a convex quadratic in AA with gradient 2∑mi(Aqi−pi)qiT=2(AS0−Apq)2\sum m_i (A\mathbf q_i - \mathbf p_i)\mathbf q_i^T = 2(A S_0 - A_{pq}), which is zero exactly at A=ApqS0−1A = A_{pq} S_0^{-1}. If xi=Fxi0+t\mathbf x_i = F\mathbf x^0_i + \mathbf t, then xcm=Fxcm0+t\mathbf x_{cm} = F\mathbf x^0_{cm} + \mathbf t, so pi=Fqi\mathbf p_i = F\mathbf q_i, Apq=FS0A_{pq} = F S_0 and A=FA = F. □\square

The volume preserving matrix of line L4 is A~=A/det⁡A\tilde A = A/\sqrt{\det A} when det⁡A>0\det A > 0, with det⁡A~=1\det \tilde A = 1 in 2D; the code uses RR when det⁡A≤0\det A \le 0. Line L4 uses G=βA~+(1−β)RG = \beta\tilde A + (1 - \beta)R (Section 4.2 of the paper).

Lemma 3 (no pull at a rigid pose). If xi=Qxi0+t\mathbf x_i = Q\mathbf x^0_i + \mathbf t for a rotation QQ, then gi=xi\mathbf g_i = \mathbf x_i for all ii, in the rigid mode and in the linear mode for every β\beta.

Proof. Here pi=Qqi\mathbf p_i = Q\mathbf q_i and Apq=QS0A_{pq} = Q S_0. For any rotation RR, tr⁡(RTQS0)=tr⁡(US0)\operatorname{tr}(R^T Q S_0) = \operatorname{tr}(U S_0) with the rotation U=RTQU = R^T Q, and tr⁡(US0)≤tr⁡(S0)\operatorname{tr}(U S_0) \le \operatorname{tr}(S_0) because S0S_0 is symmetric positive definite and the diagonal entries of UU in the eigenbasis of S0S_0 are at most 1. Equality holds for U=IU = I, and by Lemma 1 the maximizer is unique since ρ=tr⁡S0>0\rho = \operatorname{tr} S_0 > 0. So R=QR = Q. By Lemma 2, A=QA = Q, which has determinant 1, so A~=Q\tilde A = Q and G=QG = Q in every mode. Then gi=Qqi+xcm=pi+xcm=xi\mathbf g_i = Q\mathbf q_i + \mathbf x_{cm} = \mathbf p_i + \mathbf x_{cm} = \mathbf x_i. □\square

Momentum

Lemma 4. For every GG, ∑mi(gi−xi)=0\sum m_i (\mathbf g_i - \mathbf x_i) = 0.

Proof. ∑mi(Gqi+xcm−xcm−pi)=G∑miqi−∑mipi=0\sum m_i (G\mathbf q_i + \mathbf x_{cm} - \mathbf x_{cm} - \mathbf p_i) = G\sum m_i\mathbf q_i - \sum m_i \mathbf p_i = 0. □\square

Lemma 5. If GApqTG A_{pq}^T is symmetric, then ∑mixi×(gi−xi)=0\sum m_i \mathbf x_i \times (\mathbf g_i - \mathbf x_i) = 0. This holds for G=RG = R, G=AG = A, G=A~G = \tilde A and every G=βA~+(1−β)RG = \beta\tilde A + (1 - \beta)R.

Proof. Write xi=xcm+pi\mathbf x_i = \mathbf x_{cm} + \mathbf p_i and gi−xi=Gqi−pi\mathbf g_i - \mathbf x_i = G\mathbf q_i - \mathbf p_i. Then the sum is xcm×∑mi(Gqi−pi)+∑mipi×Gqi−∑mipi×pi\mathbf x_{cm} \times \sum m_i (G\mathbf q_i - \mathbf p_i) + \sum m_i \mathbf p_i \times G\mathbf q_i - \sum m_i \mathbf p_i \times \mathbf p_i. The first term is zero by Lemma 4 and the last term is zero. For the middle term, p×Gq=(Gq pT)10−(Gq pT)01\mathbf p \times G\mathbf q = (G\mathbf q\,\mathbf p^T)_{10} - (G\mathbf q\,\mathbf p^T)_{01}, and ∑miGqipiT=GApqT\sum m_i G\mathbf q_i \mathbf p_i^T = G A_{pq}^T. So the middle term is the difference of the off-diagonal entries of GApqTG A_{pq}^T, which is zero when this matrix is symmetric. Now RApqT=RSTRT=RSRTR A_{pq}^T = R S^T R^T = R S R^T is symmetric because S=RTApqS = R^T A_{pq} is (Lemma 1). AApqT=ApqS0−1ApqTA A_{pq}^T = A_{pq} S_0^{-1} A_{pq}^T is symmetric because S0−1S_0^{-1} is. A~\tilde A is a multiple of AA, and a combination of matrices with the property has it. □\square

Theorem 6. With no external forces, one step keeps P=∑mivi\mathbf P = \sum m_i \mathbf v_i and L=∑mixi×viL = \sum m_i \mathbf x_i \times \mathbf v_i exactly, in the rigid and in the linear mode, for every α\alpha and Δt\Delta t.

Proof. By Lemma 4, P′=P+αΔt∑mi(gi−xi)=P\mathbf P' = \mathbf P + \frac{\alpha}{\Delta t}\sum m_i (\mathbf g_i - \mathbf x_i) = \mathbf P. For LL, xi′×vi′=(xi+Δtvi′)×vi′=xi×vi′\mathbf x_i' \times \mathbf v_i' = (\mathbf x_i + \Delta t\mathbf v_i') \times \mathbf v_i' = \mathbf x_i \times \mathbf v_i', so L′=∑mixi×vi+αΔt∑mixi×(gi−xi)=LL' = \sum m_i \mathbf x_i \times \mathbf v_i + \frac{\alpha}{\Delta t}\sum m_i \mathbf x_i \times (\mathbf g_i - \mathbf x_i) = L by Lemma 5. □\square

Corollary 7. Under uniform gravity, fi=mig\mathbf f_i = m_i\mathbf g, the center of mass moves by symplectic Euler: vcm′=vcm+Δt g\mathbf v_{cm}' = \mathbf v_{cm} + \Delta t\,\mathbf g and xcm′=xcm+Δt vcm′\mathbf x_{cm}' = \mathbf x_{cm} + \Delta t\,\mathbf v_{cm}'.

Proof. Multiply the step by mim_i, sum and divide by MM; the goal terms cancel by Lemma 4. □\square

Stability with a fixed goal

Lemma 8. For one particle with a fixed goal g\mathbf g and no external force, the pair (v,e)(\mathbf v, \mathbf e) with e=x−g\mathbf e = \mathbf x - \mathbf g evolves by the matrix E=(1−α/ΔtΔt1−α)E = \begin{pmatrix} 1 & -\alpha/\Delta t \\ \Delta t & 1 - \alpha \end{pmatrix} in each coordinate (equation (11) of the paper). For 0<α<40 < \alpha < 4 its eigenvalues are e±iθe^{\pm i\theta} with cos⁡θ=1−α/2\cos\theta = 1 - \alpha/2, so they have magnitude 1, and the motion is a rotation of (v,e)(\mathbf v, \mathbf e) in a fixed elliptic norm: it neither grows nor decays.

Proof. The step gives v′=v−αΔte\mathbf v' = \mathbf v - \frac{\alpha}{\Delta t}\mathbf e and e′=e+Δtv′=Δtv+(1−α)e\mathbf e' = \mathbf e + \Delta t\mathbf v' = \Delta t\mathbf v + (1 - \alpha)\mathbf e, which is EE. Its determinant is (1−α)+α=1(1 - \alpha) + \alpha = 1 and its trace is 2−α2 - \alpha. The eigenvalues solve λ2−(2−α)λ+1=0\lambda^2 - (2 - \alpha)\lambda + 1 = 0. For ∣2−α∣<2|2 - \alpha| < 2 the discriminant is negative, so the two roots are complex conjugates whose product is 1, hence both have magnitude 1, and Re⁡λ=1−α/2=cos⁡θ\operatorname{Re}\lambda = 1 - \alpha/2 = \cos\theta. The roots are distinct, so EE is diagonalizable over C\mathbb C and is similar to a rotation by θ\theta. □\square

The paper calls this unconditionally stable. It is a statement about the model with a fixed goal; the real goals move with the particles. The period is 2π/θ2\pi/\theta steps for every Δt\Delta t, so the stiffness that α\alpha gives depends on Δt\Delta t: a spring with the same period has ωΔt=θ\omega\Delta t = \theta.

Lemma 9. If α=1\alpha = 1, vi=0\mathbf v_i = 0 and fi=0\mathbf f_i = 0, one step gives xi′=gi\mathbf x_i' = \mathbf g_i.

Proof. vi′=(gi−xi)/Δt\mathbf v_i' = (\mathbf g_i - \mathbf x_i)/\Delta t, so xi′=xi+(gi−xi)=gi\mathbf x_i' = \mathbf x_i + (\mathbf g_i - \mathbf x_i) = \mathbf g_i. □\square

Cost

Lemma 10. A step costs Θ(n)\Theta(n) time and memory, after a Θ(n)\Theta(n) precomputation of xcm0\mathbf x^0_{cm}, the qi\mathbf q_i and S0−1S_0^{-1}.

Proof. Lines L1, L2, L5, L6 and L7 are sums or maps over the particles with O(1)O(1) work each. Lines L3 and L4 work on 2×22 \times 2 matrices in O(1)O(1). □\square

Complexity

A step costs Θ(n)\Theta(n) time: two sums over the particles (L1, L2), work on 2×22 \times 2 or 3×33 \times 3 matrices (L3, L4) and two maps over the particles (L5 to L7). The rest data qi\mathbf q_i and S0−1S_0^{-1} cost Θ(n)\Theta(n) once. The memory is Θ(n)\Theta(n). With overlapping clusters, each particle is in a bounded number of clusters and the cost is linear in the total cluster size.

Properties

  • Robust. The pull is toward a valid shape, so a body recovers from any deformation, even an inverted one, and a step cannot blow up with α≤1\alpha \le 1 in the fixed goal model.
  • No mesh. Only the particles and their rest positions are needed; the connectivity does not matter.
  • Not a material model. α\alpha is a tuning value, and the stiffness it gives depends on Δt\Delta t and on the size of the body. Measured periods depend only on α\alpha when counted in steps.
  • No damping of its own. The oscillation keeps its size; damping must be added, for example by the rigid body damping of PBD.
  • Exact momentum. Linear and angular momentum are kept exactly without external forces.
  • Global stiffness. One cluster can only deform by a single rotation or linear map, so a long object cannot bend. Clusters fix this.

Variants and improvements

  • Quadratic deformation. Section 4.3 fits a 2×52 \times 5 (in 3D 3×93 \times 9) map on quadratic terms of q\mathbf q, which allows bending and twisting of a single cluster.
  • Clusters. Section 4.4 divides the particles into overlapping clusters, matches each one, and averages the goals of a particle over its clusters, so that the body can bend.
  • Plasticity. Section 4.5 updates the rest shape from the linear part of the fit when the deformation is large, so the body keeps a dent.
  • Lattice shape matching. Rivers and James (2007) matched many small regions of a regular lattice, with fast summation over the regions, for detailed soft bodies.
  • As a PBD constraint. Shape matching is often projected as one constraint in a PBD or XPBD solver, together with distance and collision constraints.
  • Related energies. The same best rotation appears in the as-rigid-as-possible energy, in corotational FEM and in the local step of projective dynamics.

When to use it

Use shape matching for soft objects in games and interactive tools that must never fail and must cost little: jelly, rubber toys, soft props and objects made of many particles without a mesh. It is also a simple way to make a set of particles behave as a rigid body (α=1\alpha = 1 with one cluster).

Do not use it when the material must have a physical stiffness or must behave the same at different step sizes; use corotational FEM or projective dynamics then. One cluster cannot bend; use clusters or the quadratic mode for long objects.

Pitfalls

  • Reflections. The paper's formula Apq(ApqTApq)−1/2A_{pq}(A_{pq}^T A_{pq})^{-1/2} gives a reflection when det⁡Apq<0\det A_{pq} < 0, which turns the body inside out. Use the best rotation, as the code does in 2D, or fix the sign of the SVD in 3D.
  • Degenerate rest shapes. If the rest particles lie on a line (in 3D, a plane), S0S_0 is singular and the linear mode fails. The rotation can still be undefined when ApqA_{pq} is close to zero.
  • Volume normalization. Without dividing by the root of det⁡A\det A the linear mode lets the body grow or shrink; with det⁡A≤0\det A \le 0 the root is not defined and the code falls back to RR.
  • Step size changes the look. Changing Δt\Delta t with the same α\alpha changes the period in seconds.
  • No damping. Without added damping, a body that was hit keeps wobbling.

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
meshless_shape_matching.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meshless-shape-matching/. The authors are listed in prov/CV2R4Y.jsonl.

"""Meshless shape matching (Mueller, Heidelberger, Teschner and Gross 2005), in 2D.

A body is a set of particles with masses m_i and rest positions x0_i. In each
step the goal positions are the best rigid (or linear) map of the rest shape
onto the current positions x_i, in the mass weighted least squares sense:

    q_i = x0_i - x0_cm,  p_i = x_i - x_cm,  A_pq = sum m_i p_i q_i^T,
    R = the rotation factor of the polar decomposition of A_pq,
    g_i = G q_i + x_cm  with G = R (rigid) or G = beta A~ + (1 - beta) R (linear),

where A = A_pq (sum m_i q_i q_i^T)^(-1) and A~ = A / sqrt(det A) has det 1 in
2D (if det A <= 0 the code uses R instead of A~). The step is equation (9)
of the paper:

    v_i <- v_i + alpha (g_i - x_i) / dt + dt f_ext,i / m_i,   x_i <- x_i + dt v_i.

The 2D rotation is the closed form of anim.polar, the rotation that maximizes
trace(R^T A_pq). It is always a rotation, also when det A_pq < 0. A step
costs Theta(n) time and the memory is Theta(n) for n particles.
"""

import math

from anim import det, inv, mul, polar

GRAVITY = (0.0, -9.81)


def center(x, m):
    total = sum(m)
    return (sum(mi * p[0] for mi, p in zip(m, x)) / total, sum(mi * p[1] for mi, p in zip(m, x)) / total)


def outer_sum(m, a, b):
    """sum m_i a_i b_i^T as a 2 by 2 list of rows."""
    s = [[0.0, 0.0], [0.0, 0.0]]
    for mi, u, w in zip(m, a, b):
        for r in range(2):
            for c in range(2):
                s[r][c] += mi * u[r] * w[c]
    return s


class RestShape:
    """The rest positions with their center of mass, the vectors q_i and (sum m q q^T)^(-1)."""

    def __init__(self, x0, m):
        self.m = list(m)
        self.cm = center(x0, m)
        self.q = [(p[0] - self.cm[0], p[1] - self.cm[1]) for p in x0]
        self.aqq = inv(outer_sum(self.m, self.q, self.q))


def match(rest, x, mode="rigid", beta=0.0):
    """Return (G, x_cm): the matrix of the goal map and the current center of mass."""
    m = rest.m
    xcm = center(x, m)  # @line L1
    p = [(u[0] - xcm[0], u[1] - xcm[1]) for u in x]
    apq = outer_sum(m, p, rest.q)  # @line L2
    r, _ = polar(apq)  # @line L3
    if mode == "rigid":
        return r, xcm
    a = mul(apq, rest.aqq)
    d = det(a)
    if d <= 0.0:
        a_vol = r
    else:
        s = 1.0 / math.sqrt(d)
        a_vol = [[s * a[0][0], s * a[0][1]], [s * a[1][0], s * a[1][1]]]
    g = [[beta * a_vol[i][j] + (1.0 - beta) * r[i][j] for j in range(2)] for i in range(2)]  # @line L4
    return g, xcm


def goals(rest, x, mode="rigid", beta=0.0):
    g, xcm = match(rest, x, mode, beta)
    return [(g[0][0] * q[0] + g[0][1] * q[1] + xcm[0], g[1][0] * q[0] + g[1][1] * q[1] + xcm[1])
            for q in rest.q]  # @line L5


def step(rest, x, v, alpha, dt, mode="rigid", beta=0.0, gravity=GRAVITY):
    """One step of equation (9). Return (x, v)."""
    g = goals(rest, x, mode, beta)
    v_new = [(u[0] + alpha * (gi[0] - xi[0]) / dt + dt * gravity[0], u[1] + alpha * (gi[1] - xi[1]) / dt + dt * gravity[1])
             for u, gi, xi in zip(v, g, x)]  # @line L6
    x_new = [(xi[0] + dt * u[0], xi[1] + dt * u[1]) for xi, u in zip(x, v_new)]  # @line L7
    return x_new, v_new


def momentum(x, v, m):
    """Return (P_x, P_y, L) with L = sum m x cross v about the origin."""
    px = sum(mi * u[0] for mi, u in zip(m, v))
    py = sum(mi * u[1] for mi, u in zip(m, v))
    ang = sum(mi * (xi[0] * u[1] - xi[1] * u[0]) for mi, xi, u in zip(m, x, v))
    return px, py, ang


def fit_error(rest, x, g):
    """sum m_i |G q_i + x_cm - x_i|^2 for a 2 by 2 matrix G."""
    xcm = center(x, rest.m)
    e = 0.0
    for mi, q, xi in zip(rest.m, rest.q, x):
        gx = g[0][0] * q[0] + g[0][1] * q[1] + xcm[0] - xi[0]
        gy = g[1][0] * q[0] + g[1][1] * q[1] + xcm[1] - xi[1]
        e += mi * (gx * gx + gy * gy)
    return e


def amplification(alpha, dt):
    """The matrix of equation (11) for one particle and a fixed goal, on (v, x - g)."""
    return [[1.0, -alpha / dt], [dt, 1.0 - alpha]]
test_meshless_shape_matching.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/meshless-shape-matching/. The authors are listed in prov/CV2R4Y.jsonl.

"""Tests of shape matching against an angle scan, closed forms and conservation laws."""

import cmath
import math
import random

from anim import rot2
import meshless_shape_matching as sm


def random_body(rng, count):
    x0 = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(count)]
    m = [rng.uniform(0.5, 2.0) for _ in range(count)]
    return x0, m


def apply(f, t, pts):
    return [(f[0][0] * p[0] + f[0][1] * p[1] + t[0], f[1][0] * p[0] + f[1][1] * p[1] + t[1]) for p in pts]


def test_example_square():
    x0 = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
    rest = sm.RestShape(x0, [1.0] * 4)
    x = [(2.0 * p[0], p[1]) for p in x0]
    g = sm.goals(rest, x)
    assert max(math.dist(a, b) for a, b in zip(g, x0)) < 1e-15
    x1, v1 = sm.step(rest, x, [(0.0, 0.0)] * 4, 0.5, 0.1, gravity=(0.0, 0.0))
    assert math.dist(x1[2], (1.5, 1.0)) < 1e-14 and math.dist(v1[2], (-5.0, 0.0)) < 1e-13
    gl = sm.goals(rest, x, "linear", 1.0)
    assert math.dist(gl[2], (math.sqrt(2.0), 1.0 / math.sqrt(2.0))) < 1e-14


def test_rotation_is_the_best_rigid_fit():
    """The polar rotation of A_pq beats every angle of a fine scan."""
    rng = random.Random(21)
    for _ in range(30):
        x0, m = random_body(rng, 6)
        rest = sm.RestShape(x0, m)
        x = [(p[0] + rng.gauss(0, 0.5), p[1] + rng.gauss(0, 0.5)) for p in x0]
        r, _ = sm.match(rest, x)
        best = sm.fit_error(rest, x, r)
        assert abs(r[0][0] * r[1][1] - r[0][1] * r[1][0] - 1.0) < 1e-12
        for k in range(720):
            assert best <= sm.fit_error(rest, x, rot2(2.0 * math.pi * k / 720)) + 1e-12


def test_rigid_pose_has_no_pull():
    rng = random.Random(22)
    for _ in range(50):
        x0, m = random_body(rng, 5)
        rest = sm.RestShape(x0, m)
        x = apply(rot2(rng.uniform(-math.pi, math.pi)), (rng.uniform(-3, 3), rng.uniform(-3, 3)), x0)
        for mode in ("rigid", "linear"):
            g = sm.goals(rest, x, mode, rng.uniform(0.0, 1.0))
            assert max(math.dist(a, b) for a, b in zip(g, x)) < 1e-12


def test_linear_mode_recovers_the_affine_map():
    """For x = F x0 + t with det F > 0, A = F and A~ = F / sqrt(det F)."""
    rng = random.Random(23)
    for _ in range(50):
        x0, m = random_body(rng, 5)
        rest = sm.RestShape(x0, m)
        f = [[rng.uniform(0.5, 2.0), rng.uniform(-0.5, 0.5)], [rng.uniform(-0.5, 0.5), rng.uniform(0.5, 2.0)]]
        d = f[0][0] * f[1][1] - f[0][1] * f[1][0]
        x = apply(f, (rng.uniform(-1, 1), rng.uniform(-1, 1)), x0)
        g, _ = sm.match(rest, x, "linear", 1.0)
        for i in range(2):
            for j in range(2):
                assert abs(g[i][j] - f[i][j] / math.sqrt(d)) < 1e-10


def test_momentum_is_kept_exactly():
    rng = random.Random(24)
    for mode, beta in (("rigid", 0.0), ("linear", 0.5), ("linear", 1.0)):
        x0, m = random_body(rng, 8)
        rest = sm.RestShape(x0, m)
        x = [(p[0] + rng.gauss(0, 0.3), p[1] + rng.gauss(0, 0.3)) for p in x0]
        v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in x0]
        p0 = sm.momentum(x, v, m)
        for _ in range(200):
            x, v = sm.step(rest, x, v, 0.3, 0.02, mode, beta, gravity=(0.0, 0.0))
        p1 = sm.momentum(x, v, m)
        scale = sum(mi * math.hypot(*u) for mi, u in zip(m, v)) * (1.0 + max(math.hypot(*p) for p in x))
        assert max(abs(a - b) for a, b in zip(p0, p1)) < 1e-10 * scale


def test_alpha_one_reaches_the_goals():
    rng = random.Random(25)
    x0, m = random_body(rng, 6)
    rest = sm.RestShape(x0, m)
    x = [(p[0] + rng.gauss(0, 0.3), p[1] + rng.gauss(0, 0.3)) for p in x0]
    g = sm.goals(rest, x)
    x1, _ = sm.step(rest, x, [(0.0, 0.0)] * 6, 1.0, 0.05, gravity=(0.0, 0.0))
    assert max(math.dist(a, b) for a, b in zip(x1, g)) < 1e-14


def test_fixed_goal_amplification_has_unit_eigenvalues():
    for alpha in (0.01, 0.1, 0.5, 0.9, 1.0):
        for dt in (1e-3, 0.01, 0.1, 1.0):
            a = sm.amplification(alpha, dt)
            tr = a[0][0] + a[1][1]
            dt_ = a[0][0] * a[1][1] - a[0][1] * a[1][0]
            disc = cmath.sqrt(tr * tr - 4.0 * dt_)
            for lam in ((tr + disc) / 2.0, (tr - disc) / 2.0):
                assert abs(abs(lam) - 1.0) < 1e-12


def test_oscillation_neither_grows_nor_decays():
    """A stretched square keeps the size of its oscillation over 2000 steps (measured)."""
    x0 = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]
    rest = sm.RestShape(x0, [1.0] * 4)
    x = [(2.0 * p[0], p[1]) for p in x0]
    v = [(0.0, 0.0)] * 4
    amp = []
    for n in range(2000):
        x, v = sm.step(rest, x, v, 0.2, 0.01, gravity=(0.0, 0.0))
        amp.append(max(math.dist(a, b) for a, b in zip(x, sm.goals(rest, x))))
    first = max(amp[:200])
    last = max(amp[-200:])
    assert 0.95 < last / first < 1.05


def test_center_of_mass_falls_as_symplectic_euler():
    rng = random.Random(26)
    x0, m = random_body(rng, 5)
    rest = sm.RestShape(x0, m)
    x = [(p[0] + rng.gauss(0, 0.2), p[1] + rng.gauss(0, 0.2)) for p in x0]
    c0 = sm.center(x, m)
    v = [(0.0, 0.0)] * 5
    for _ in range(10):
        x, v = sm.step(rest, x, v, 0.4, 0.1)
    c1 = sm.center(x, m)
    assert abs(c1[1] - c0[1] + 5.3955) < 1e-12 and abs(c1[0] - c0[0]) < 1e-12

History

Müller, Heidelberger, Teschner and Gross introduced meshless shape matching at SIGGRAPH 2005, with the rigid, linear and quadratic modes, clusters and plasticity. The best rotation of two point sets goes back to the orthogonal Procrustes problem and to Kabsch (1976). Rivers and James (2007) extended the idea to lattice shape matching, and later position based solvers took shape matching in as one more kind of constraint.

References

  1. Matthias Müller, Bruno Heidelberger, Matthias Teschner and Markus Gross, Meshless deformations based on shape matching, ACM Transactions on Graphics 24(3), 471-478, 2005 (SIGGRAPH 2005), Section 3.3 (the optimal rotation, equations (5) to (8)), Section 3.4 (the integration, equations (9) to (11)), Section 4 (linear and quadratic deformations, clusters and plasticity)

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.precompute
  • a full proof of time.step
  • a full proof of space.step
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
  • at least three sources
  • a scene preset for the example