Algorithm Search⌘K

Algorithmadvanced

Cumulative B-spline quaternion curve

Also called Kim-Kim-Shin quaternion curve.

Build a C2 curve of unit quaternions by writing a B-spline in cumulative form and replacing each scaled difference of control points by a power of a relative rotation.

Time
Θ(n) buildΘ(1) query
Space
Θ(n) extra
Where
n = the number of control quaternions
Properties
deterministicnot exactofflineiterative

The cumulative B-spline quaternion curve of Kim, Kim and Shin (1995) is a smooth curve of unit quaternions controlled by a sequence q0,…,qn−1q_0, \dots, q_{n-1} of orientations. It starts from the B-spline written in cumulative form, p(t)=p0B~0(t)+∑i≥1(pi−pi−1) B~i(t)p(t) = p_0 \tilde B_0(t) + \sum_{i \ge 1} (p_i - p_{i-1})\,\tilde B_i(t), where B~i=∑j≥iBj\tilde B_i = \sum_{j \ge i} B_j. Each sum becomes a product and each scaled difference becomes a power of a relative rotation:

q(t)=q0B~0(t)∏i=1n−1exp⁡(ωiB~i(t)),ωi=log⁡(qi−1−1qi).q(t) = q_0^{\tilde B_0(t)} \prod_{i = 1}^{n-1} \exp\bigl(\omega_i \tilde B_i(t)\bigr), \qquad \omega_i = \log(q_{i-1}^{-1} q_i).

For the uniform cubic B-spline the curve is C2C^2, its derivatives have short closed forms, and like a B-spline it does not pass through its control points.

In plain words

A B-spline is a smooth curve that follows a row of control points without touching them. You can build it step by step: start at the first point, then add a part of each step to the next point. How much of each step you add depends on the time, through smooth weight functions. For orientations, a step is a turn from one control orientation to the next. This method does a part of each turn, in order, and the weights are the same as for the B-spline. Because the weights change smoothly, the turning speed and the turning acceleration also change smoothly. The price is that the curve passes near the control orientations, not through them.

The problem

The input is a sequence of unit quaternions q0,…,qn−1q_0, \dots, q_{n-1}, n≥4n \ge 4, in the Hamilton convention with the scalar first. The output is a curve q(t)q(t) of unit quaternions for t∈[0,n−3]t \in [0, n - 3] that is C2C^2, so that the body angular velocity and its derivative are continuous, and that depends only on the rotations, not on the coordinates. A key interpolating curve such as squad is only C1C^1. The logarithm of a unit quaternion (cos⁡φ,sin⁡φ u^)(\cos\varphi, \sin\varphi\,\hat u) is (0,φu^)(0, \varphi\hat u), and exp⁡\exp is its inverse on pure quaternions.

The algorithm

On segment j∈{0,…,n−4}j \in \{0, \dots, n - 4\} with the local parameter u∈[0,1]u \in [0, 1], only four basis functions are active. The factors before them are exp⁡(ωi)=qi−1−1qi\exp(\omega_i) = q_{i-1}^{-1} q_i, whose product telescopes to qjq_j, and the factors after them are 1. So the segment is

q(u)=qjexp⁡(B~1(u) ωj+1)exp⁡(B~2(u) ωj+2)exp⁡(B~3(u) ωj+3)q(u) = q_j \exp\bigl(\tilde B_1(u)\,\omega_{j+1}\bigr) \exp\bigl(\tilde B_2(u)\,\omega_{j+2}\bigr) \exp\bigl(\tilde B_3(u)\,\omega_{j+3}\bigr)

with the cumulative uniform cubic basis

B~1=16(5+3u−3u2+u3),B~2=16(1+3u+3u2−2u3),B~3=16u3.\tilde B_1 = \tfrac16(5 + 3u - 3u^2 + u^3), \quad \tilde B_2 = \tfrac16(1 + 3u + 3u^2 - 2u^3), \quad \tilde B_3 = \tfrac16 u^3.
  1. KKS(q₀, ..., qₙ₋₁; j, u) ▷ control quaternions; the point of segment j at u
  2. 1for k ← 1 to n - 1: if qₖ₋₁ · qₖ < 0 then
  3. 2qₖ ← -qₖ ▷ the same rotation, near the previous one
  4. 3for k ← 1 to n - 1: ωₖ ← log(qₖ₋₁* qₖ) ▷ half the rotation vector of each step
  5. 4(B̃₁, B̃₂, B̃₃) ← the cumulative basis at u
  6. 5q ← qⱼ
  7. 6for k ← 1 to 3 do
  8. 7q ← q exp(B̃ₖ ωⱼ₊ₖ) ▷ a part of the k-th step
  9. 8return q

Lines L1 to L3 run once for the sequence. Lines L4 to L8 are the query; for a global parameter tt, use j=⌊t⌋j = \lfloor t \rfloor and u=t−ju = t - j. The factors of line L7 must be applied in this order, since quaternion products do not commute.

Example

Take four control orientations: q0=(1,0,0,0)q_0 = (1, 0, 0, 0); q1=(0.70711,0,0,0.70711)q_1 = (0.70711, 0, 0, 0.70711), a turn by 90 degrees about zz; q2=(0.5,0.5,0.5,0.5)q_2 = (0.5, 0.5, 0.5, 0.5), a further turn by 90 degrees about the body xx axis; and q3=(0,0.70711,0,0.70711)q_3 = (0, 0.70711, 0, 0.70711), a further turn by 90 degrees about the body zz axis.

  • Lines L1 and L2: all adjacent dot products are 0.707110.70711, so no sign changes.
  • Line L3: ω1=(0,0,0,0.7854)\omega_1 = (0, 0, 0, 0.7854), ω2=(0,0.7854,0,0)\omega_2 = (0, 0.7854, 0, 0) and ω3=(0,0,0,0.7854)\omega_3 = (0, 0, 0, 0.7854).
  • At u=0u = 0 the basis is (56,16,0)(\frac56, \frac16, 0), and q(0)=(0.78657,0.10355,0.07946,0.60355)q(0) = (0.78657, 0.10355, 0.07946, 0.60355), a rotation by 1.33114 radians. The key q1q_1 is a rotation by π/2=1.5708\pi/2 = 1.5708, so the curve does not pass through it.
  • At u=0.5u = 0.5 the basis is (0.97917,0.5,0.02083)(0.97917, 0.5, 0.02083), and q(0.5)=(0.65328,0.27931,0.26160,0.65328)q(0.5) = (0.65328, 0.27931, 0.26160, 0.65328), close to the midpoint (0.65328,0.27060,0.27060,0.65328)(0.65328, 0.27060, 0.27060, 0.65328) of the slerp from q1q_1 to q2q_2.
  • At u=1u = 1 the basis is (1,56,16)(1, \frac56, \frac16), and q(1)=(0.48296,0.48296,0.37059,0.62941)q(1) = (0.48296, 0.48296, 0.37059, 0.62941).

The body angular velocity at u=0.5u = 0.5 is (1.18201,0.10022,0.33519)(1.18201, 0.10022, 0.33519) radians per unit of uu.

Correctness

In the global form, each cumulative basis function B~i=∑j≥iBj\tilde B_i = \sum_{j \ge i} B_j is a sum of C2C^2 cubic B-splines, so it is C2C^2. The map x↦exp⁡(x ωi)x \mapsto \exp(x\,\omega_i) is smooth, so each factor exp⁡(ωiB~i(t))\exp(\omega_i \tilde B_i(t)) is a C2C^2 curve of unit quaternions. A product of finitely many C2C^2 curves is C2C^2, so q(t)q(t) is C2C^2. Each factor has length 1, so q(t)q(t) is a unit quaternion.

The segment form of line L7 is the global form: on segment jj, B~i=1\tilde B_i = 1 for i≤ji \le j and B~i=0\tilde B_i = 0 for i>j+3i > j + 3, by the partition of unity and the supports of the B-splines. Then ∏i≤jexp⁡(ωi)=∏i≤jqi−1−1qi=q0−1qj\prod_{i \le j}\exp(\omega_i) = \prod_{i \le j} q_{i-1}^{-1} q_i = q_0^{-1} q_j. If all control quaternions are rotations about one fixed axis, the factors commute, and the angle is the scalar B-spline of the key angles. The proof gives the details.

Proof: The cumulative B-spline quaternion curve is a C2 curve of unit quaternionsfull

We use the notation of the page. Quaternions are in the Hamilton convention, scalar first. For a pure quaternion ω=(0,φu^)\omega = (0, \varphi\hat u) with a unit vector u^\hat u, exp⁡(xω)=(cos⁡xφ,sin⁡xφ u^)\exp(x\omega) = (\cos x\varphi, \sin x\varphi\,\hat u) for real xx, which is a unit quaternion and a smooth function of xx. The uniform cubic B-splines B0,…,Bn−1B_0, \dots, B_{n-1} are C2C^2 piecewise cubics on the knots …,−1,0,1,…\dots, -1, 0, 1, \dots, numbered so that on [j,j+1][j, j + 1] the active ones are Bj,…,Bj+3B_j, \dots, B_{j+3}, with Bj+k(j+u)=bk(u)B_{j+k}(j + u) = b_k(u) for

b0=16(1−u)3,b1=16(3u3−6u2+4),b2=16(−3u3+3u2+3u+1),b3=16u3.b_0 = \tfrac16(1 - u)^3, \quad b_1 = \tfrac16(3u^3 - 6u^2 + 4), \quad b_2 = \tfrac16(-3u^3 + 3u^2 + 3u + 1), \quad b_3 = \tfrac16 u^3.

They sum to 1 on [0,n−3][0, n - 3].

The cumulative basis

Lemma 1. Let B~i=∑l≥iBl\tilde B_i = \sum_{l \ge i} B_l. On [j,j+1][j, j + 1], B~i=1\tilde B_i = 1 for i≤ji \le j, B~i=0\tilde B_i = 0 for i≥j+4i \ge j + 4, and B~j+k(j+u)=∑l≥kbl(u)\tilde B_{j+k}(j + u) = \sum_{l \ge k} b_l(u) for k=1,2,3k = 1, 2, 3, which gives the three polynomials B~1,B~2,B~3\tilde B_1, \tilde B_2, \tilde B_3 of the page.

Proof. On [j,j+1][j, j + 1] only Bj,…,Bj+3B_j, \dots, B_{j+3} are nonzero. For i≤ji \le j the sum contains all of them, so it is 1. For i≥j+4i \ge j + 4 it contains none of them. For i=j+ki = j + k it is ∑l=k3bl\sum_{l = k}^{3} b_l. Adding the polynomials gives b3=16u3b_3 = \frac16u^3, b2+b3=16(1+3u+3u2−2u3)b_2 + b_3 = \frac16(1 + 3u + 3u^2 - 2u^3) and b1+b2+b3=1−b0=16(5+3u−3u2+u3)b_1 + b_2 + b_3 = 1 - b_0 = \frac16(5 + 3u - 3u^2 + u^3). □\square

Lemma 2. Each B~i\tilde B_i is C2C^2 on [0,n−3][0, n - 3].

Proof. It is a finite sum of C2C^2 functions. □\square

The segment form

Lemma 3. After lines L1 to L3, exp⁡(ωk)=qk−1∗qk\exp(\omega_k) = q_{k-1}^* q_k for each kk.

Proof. Line L2 makes qk−1⋅qk≥0q_{k-1}\cdot q_k \ge 0, so qk−1∗qkq_{k-1}^* q_k has a scalar part qk−1⋅qk≥0q_{k-1}\cdot q_k \ge 0 and its angle φ\varphi is in [0,π/2][0, \pi/2]. On such unit quaternions, exp⁡(log⁡p)=p\exp(\log p) = p. □\square

Lemma 4. On [j,j+1][j, j + 1] the global curve q(t)=q0∏i=1n−1exp⁡(ωiB~i(t))q(t) = q_0 \prod_{i=1}^{n-1}\exp(\omega_i\tilde B_i(t)) equals the segment form of lines L4 to L8 with u=t−ju = t - j.

Proof. By Lemma 1 the factors with i≤ji \le j are exp⁡(ωi)=qi−1∗qi\exp(\omega_i) = q_{i-1}^* q_i by Lemma 3, and the factors with i≥j+4i \ge j + 4 are exp⁡(0)=1\exp(0) = 1. The product q0∏i=1jqi−1∗qiq_0 \prod_{i=1}^{j} q_{i-1}^* q_i telescopes to qjq_j, because qiqi∗=1q_i q_i^* = 1. The remaining factors are those of line L7, in the same order. □\square

Smoothness and unit length

Theorem. q(t)q(t) is a unit quaternion for every t∈[0,n−3]t \in [0, n - 3], and qq is C2C^2.

Proof. Each factor is a unit quaternion, and a product of unit quaternions has length 1. The factor exp⁡(ωiB~i(t))\exp(\omega_i\tilde B_i(t)) is the composition of the smooth map x↦exp⁡(xωi)x \mapsto \exp(x\omega_i) with the C2C^2 function B~i\tilde B_i of Lemma 2, so it is C2C^2. The quaternion product is bilinear, so a product of finitely many C2C^2 curves is C2C^2 by the product rule. □\square

By Lemma 4, the segments of the page join with matching values and first and second derivatives at the integer parameters, because they are pieces of one C2C^2 function.

Derivatives

Lemma 5. With Ak=exp⁡(B~k(u) ωj+k)A_k = \exp(\tilde B_k(u)\,\omega_{j+k}), Ak′=Ak B~k′(u) ωj+kA_k' = A_k\,\tilde B_k'(u)\,\omega_{j+k}, and the body angular velocity on segment jj is

2q∗q′=2(A3∗A2∗ B~1′ωj+1 A2A3+A3∗ B~2′ωj+2 A3+B~3′ωj+3).2q^* q' = 2\bigl(A_3^* A_2^*\,\tilde B_1'\omega_{j+1}\,A_2 A_3 + A_3^*\,\tilde B_2'\omega_{j+2}\,A_3 + \tilde B_3'\omega_{j+3}\bigr).

Proof. AkA_k is a function of the commuting family xωj+kx\omega_{j+k}, so its derivative is Ak ωj+kB~k′A_k\,\omega_{j+k}\tilde B_k' by the chain rule. The product rule gives q′=qj(A1′A2A3+A1A2′A3+A1A2A3′)q' = q_j(A_1'A_2A_3 + A_1A_2'A_3 + A_1A_2A_3'). Multiplying on the left by q∗=A3∗A2∗A1∗qj∗q^* = A_3^*A_2^*A_1^*q_j^* and using Ak∗Ak=1A_k^*A_k = 1 gives the formula. □\square

Rotations about one axis

Lemma 6. If every qkq_k is a rotation about the same unit axis a^\hat a, with angles θk\theta_k and ∣θk−θk−1∣<π|\theta_k - \theta_{k-1}| < \pi, then q(t)q(t) is the rotation about a^\hat a by ∑lθlBl(t)\sum_l \theta_l B_l(t).

Proof. After the sign test, qk=(cos⁡θk2,sin⁡θk2a^)q_k = (\cos\frac{\theta_k}2, \sin\frac{\theta_k}2\hat a) up to a common sign choice, and ωk=(0,12(θk−θk−1)a^)\omega_k = (0, \frac12(\theta_k - \theta_{k-1})\hat a). All factors are rotations about a^\hat a, so they commute and their half angles add: 12(θ0+∑i≥1(θi−θi−1)B~i)=12∑lθlBl\frac12(\theta_0 + \sum_{i \ge 1}(\theta_i - \theta_{i-1})\tilde B_i) = \frac12\sum_l \theta_l B_l by summation by parts, since B~0=1\tilde B_0 = 1 on the domain. □\square

Independence of frames

Lemma 7. For unit quaternions aa and bb, the control quaternions a qk ba\,q_k\,b give the curve a q(t) ba\,q(t)\,b.

Proof. (aqk−1b)∗(aqkb)=b∗(qk−1∗qk)b(aq_{k-1}b)^*(aq_kb) = b^*(q_{k-1}^*q_k)b, and conjugation by bb is a rotation of the pure quaternions, so the new ωk\omega_k is b∗ωkbb^*\omega_kb and exp⁡(x b∗ωkb)=b∗exp⁡(xωk)b\exp(x\,b^*\omega_kb) = b^*\exp(x\omega_k)b. In the product a qj b ∏kb∗Akba\,q_j\,b\,\prod_k b^*A_kb, the inner factors b b∗b\,b^* cancel, which leaves a qjA1A2A3 ba\,q_j A_1A_2A_3\,b. The dot products of line L1 do not change, because multiplication by unit quaternions is an isometry of R4\mathbb{R}^4. □\square

Complexity

The build step, lines L1 to L3, costs Θ(n)\Theta(n) time: one quaternion product and one logarithm per step, and Θ(n)\Theta(n) space for the ωk\omega_k. A query costs Θ(1)\Theta(1): three exponentials and three quaternion products. The body angular velocity costs about as much more, with the closed form of the Properties section.

Properties

  • C2C^2 continuity. The curve, its velocity and its acceleration are continuous on [0,n−3][0, n - 3].
  • Simple derivatives. With Ak=exp⁡(B~kωj+k)A_k = \exp(\tilde B_k\omega_{j+k}), q′=qj(A1′A2A3+A1A2′A3+A1A2A3′)q' = q_j(A_1' A_2 A_3 + A_1 A_2' A_3 + A_1 A_2 A_3') and Ak′=Ak ωj+kB~k′A_k' = A_k\,\omega_{j+k}\tilde B_k'. So the body angular velocity 2 q∗q′2\,q^* q' is 2(A3∗A2∗B~1′ωj+1A2A3+A3∗B~2′ωj+2A3+B~3′ωj+3)2(A_3^* A_2^* \tilde B_1'\omega_{j+1} A_2 A_3 + A_3^* \tilde B_2'\omega_{j+2} A_3 + \tilde B_3'\omega_{j+3}).
  • Approximation, not interpolation. At the joint u=0u = 0 of segment jj, the curve is qjexp⁡(56ωj+1)exp⁡(16ωj+2)q_j\exp(\frac56\omega_{j+1})\exp(\frac16\omega_{j+2}), not qj+1q_{j+1}. For rotations about one axis the angle there is 16(θj+4θj+1+θj+2)\frac16(\theta_j + 4\theta_{j+1} + \theta_{j+2}), as for the scalar B-spline.
  • Local control. Segment jj depends on qj,…,qj+3q_j, \dots, q_{j+3} only, so moving one control quaternion changes four segments.
  • Independence of frames. For unit quaternions aa and bb, the control quaternions a qk ba\,q_k\,b give the curve a q(t) ba\,q(t)\,b.
  • One axis. For rotations about one fixed axis, the curve is the uniform cubic B-spline of the rotation angles.
  • No symmetry under reversal. Reversing the order of the control quaternions does not give the same curve run backwards, because the products do not commute. In tests with random keys up to two radians apart, the difference is a few thousandths.

Variants and improvements

  • Other bases. The construction works for any basis in cumulative form. Kim, Kim and Shin also give quaternion Bezier and Hermite curves this way, with the Bernstein basis of the Bezier curve.
  • Interpolating curves. To pass through given keys, solve for control quaternions whose curve meets the keys at the joints. Kim, Kim and Shin treated this problem in a second paper of 1995. The equations are nonlinear, because the products do not commute.
  • Nonuniform knots. Use the cumulative basis of a nonuniform B-spline for keys at uneven times. The curve is still C2C^2.
  • Squad and spherical Bezier curves. Squad and the spherical Bezier curves of Shoemake interpolate the keys and are cheaper to set up, but they are only C1C^1, and their derivatives have no simple form.

When to use it

Use the cumulative B-spline curve when a smooth angular acceleration matters more than hitting each key exactly: a camera that must not shake, a vehicle or a body in a physics-based animation, or a smooth target for a controller that uses the angular acceleration. It is also a good model of a smooth rotation trajectory to fit to noisy orientation data, because the derivatives are cheap. If the keys must be hit, use squad or an interpolating variant.

Pitfalls

  • Inconsistent signs. Without lines L1 and L2, a step between two close rotations can have a quaternion angle above π/2\pi/2, and the curve turns the long way.
  • Steps of a half turn. If two adjacent control quaternions differ by a rotation of π\pi, the logarithm in line L3 has no unique axis.
  • The order of the factors. The factors of line L7 do not commute. Changing their order, or writing the product in the other order, gives a different curve that is no longer the cumulative form.
  • Treating it as an interpolant. The control quaternions are not on the curve. An animator who sets keys and expects the curve to pass through them will see an offset at each key.
  • Euler angles. A B-spline on Euler angles is also C2C^2, but it depends on the angle order and fails near gimbal lock.

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
cumulative_b_spline_quaternion_curve.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cumulative-b-spline-quaternion-curve/. The authors are listed in prov/7V1M8B.jsonl.
"""Cumulative uniform cubic B-spline curve of unit quaternions (Kim, Kim and Shin 1995).

The control quaternions are q_0, ..., q_(n-1), n >= 4. Segment j, for
j = 0, ..., n - 4 and the local parameter u in [0, 1], is

    q(u) = q_j exp(B1(u) w_(j+1)) exp(B2(u) w_(j+2)) exp(B3(u) w_(j+3)),

with w_k = log(q_(k-1)* q_k) and the cumulative basis functions

    B1(u) = (5 + 3u - 3u^2 + u^3) / 6,
    B2(u) = (1 + 3u + 3u^2 - 2u^3) / 6,
    B3(u) = u^3 / 6.

On a line of real numbers the same formula, with sums in place of the
products, is the uniform cubic B-spline in cumulative form.
"""

from anim import q_conj, q_dot, q_exp, q_log, q_mul


def cumulative_basis(u):
    """Return (B1, B2, B3) of the uniform cubic B-spline at u in [0, 1]."""
    u2 = u * u
    u3 = u2 * u
    return (5.0 + 3.0 * u - 3.0 * u2 + u3) / 6.0, (1.0 + 3.0 * u + 3.0 * u2 - 2.0 * u3) / 6.0, u3 / 6.0


def cumulative_basis_derivative(u):
    """Return the derivatives of (B1, B2, B3) with respect to u."""
    u2 = u * u
    return (3.0 - 6.0 * u + 3.0 * u2) / 6.0, (3.0 + 6.0 * u - 6.0 * u2) / 6.0, u2 / 2.0


def _vexp(w, b):
    return q_exp((0.0, b * w[1], b * w[2], b * w[3]))


class CumulativeBSplineQuaternionCurve:
    """The C2 curve of unit quaternions with the control quaternions keys."""

    def __init__(self, keys):
        if len(keys) < 4:
            raise ValueError("a cubic curve needs at least four control quaternions")
        q = [tuple(keys[0])]
        for k in keys[1:]:
            k = tuple(k)
            if q_dot(q[-1], k) < 0.0:  # @line L1
                k = (-k[0], -k[1], -k[2], -k[3])  # @line L2
            q.append(k)
        self.keys = q
        self.omega = [None] + [q_log(q_mul(q_conj(q[k - 1]), q[k])) for k in range(1, len(q))]  # @line L3

    def segments(self):
        """Return the number of segments, n - 3."""
        return len(self.keys) - 3

    def segment(self, j, u):
        """Return the point of segment j at the local parameter u in [0, 1]."""
        b = cumulative_basis(u)  # @line L4
        q = self.keys[j]  # @line L5
        for k in range(3):  # @line L6
            q = q_mul(q, _vexp(self.omega[j + k + 1], b[k]))  # @line L7
        return q  # @line L8

    def __call__(self, t):
        """Return the point at the global parameter t in [0, n - 3]."""
        m = self.segments()
        if t >= m:
            return self.segment(m - 1, 1.0)
        if t <= 0.0:
            return self.segment(0, 0.0)
        j = int(t)
        return self.segment(j, t - j)

    def body_angular_velocity(self, j, u):
        """Return 2 vec(q* dq/du), the body angular velocity per unit of u.

        With A_k = exp(B_k w_k), q* q' = A3* A2* (B1' w1) A2 A3 + A3* (B2' w2) A3 + B3' w3,
        since the factor A_k commutes with w_k.
        """
        b = cumulative_basis(u)
        db = cumulative_basis_derivative(u)
        w = [self.omega[j + k + 1] for k in range(3)]
        a = [_vexp(w[k], b[k]) for k in range(3)]
        acc = (0.0, 0.0, 0.0, 0.0)
        for k in range(3):
            term = (0.0, db[k] * w[k][1], db[k] * w[k][2], db[k] * w[k][3])
            for m in range(k + 1, 3):
                term = q_mul(q_mul(q_conj(a[m]), term), a[m])
            acc = tuple(x + y for x, y in zip(acc, term))
        return (2.0 * acc[1], 2.0 * acc[2], 2.0 * acc[3])
test_cumulative_b_spline_quaternion_curve.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cumulative-b-spline-quaternion-curve/. The authors are listed in prov/7V1M8B.jsonl.
import math
import random

import pytest

import anim
from cumulative_b_spline_quaternion_curve import (
    CumulativeBSplineQuaternionCurve,
    cumulative_basis,
)


def random_unit(rng):
    return anim.q_normalize(tuple(rng.gauss(0.0, 1.0) for _ in range(4)))


def random_keys(rng, n, spread=1.0):
    # A random walk on the sphere, so that adjacent keys are not too far apart.
    q = [random_unit(rng)]
    for _ in range(n - 1):
        axis = tuple(rng.gauss(0.0, 1.0) for _ in range(3))
        q.append(anim.q_mul(q[-1], anim.q_from_axis_angle(axis, rng.uniform(0.2, spread * 2.0))))
    return q


def same_rotation(p, q, tol):
    return min(anim.norm(anim.sub(p, q)), anim.norm(anim.add(p, q))) < tol


def uniform_cubic_bspline(c, j, u):
    # Reference: the scalar uniform cubic B-spline in the usual (not cumulative) basis.
    b = ((1 - u) ** 3 / 6, (3 * u**3 - 6 * u**2 + 4) / 6, (-3 * u**3 + 3 * u**2 + 3 * u + 1) / 6, u**3 / 6)
    return sum(bk * c[j + k] for k, bk in enumerate(b))


def test_cumulative_basis_values():
    assert cumulative_basis(0.0) == pytest.approx((5 / 6, 1 / 6, 0.0))
    assert cumulative_basis(1.0) == pytest.approx((1.0, 5 / 6, 1 / 6))
    assert cumulative_basis(0.5) == pytest.approx((0.9791666666666666, 0.5, 0.020833333333333332))


def test_unit_norm(rng=random.Random(1)):
    c = CumulativeBSplineQuaternionCurve(random_keys(rng, 8))
    for k in range(200):
        q = c(rng.uniform(0.0, c.segments()))
        assert abs(anim.q_dot(q, q) - 1.0) < 1e-12


def test_one_axis_reduces_to_the_scalar_b_spline(rng=random.Random(2)):
    axis = anim.normalize((rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)))
    angles = [0.0]
    for _ in range(7):
        angles.append(angles[-1] + rng.uniform(-2.5, 2.5))
    keys = [anim.q_from_axis_angle(axis, a) for a in angles]
    c = CumulativeBSplineQuaternionCurve(keys)
    for j in range(c.segments()):
        for u in (0.0, 0.3, 0.5, 0.77, 1.0):
            ref = anim.q_from_axis_angle(axis, uniform_cubic_bspline(angles, j, u))
            assert same_rotation(c.segment(j, u), ref, 1e-12)


def test_does_not_pass_through_the_keys():
    z = (0.0, 0.0, 1.0)
    keys = [anim.q_from_axis_angle(z, a) for a in (0.0, 1.0, 0.0, 1.0)]
    c = CumulativeBSplineQuaternionCurve(keys)
    # At u = 0 the angle is (0 + 4 * 1 + 0) / 6, not the key angle 1.
    assert same_rotation(c.segment(0, 0.0), anim.q_from_axis_angle(z, 4.0 / 6.0), 1e-14)


def one_sided(f, t, h, side):
    # Values, first and second derivatives with second order one-sided differences.
    s = 1.0 if side > 0 else -1.0
    v = [f(t + s * k * h) for k in range(4)]
    d1 = [s * (-3 * a + 4 * b - c) / (2 * h) for a, b, c in zip(v[0], v[1], v[2])]
    d2 = [(2 * a - 5 * b + 4 * c - d) / (h * h) for a, b, c, d in zip(*v)]
    return v[0], d1, d2


def test_c2_at_the_joints(rng=random.Random(3)):
    c = CumulativeBSplineQuaternionCurve(random_keys(rng, 7))
    h = 1e-3
    for j in range(1, c.segments()):
        left = one_sided(lambda u: c.segment(j - 1, u), 1.0, h, -1)
        right = one_sided(lambda u: c.segment(j, u), 0.0, h, +1)
        assert anim.norm(anim.sub(left[0], right[0])) < 1e-13
        assert anim.norm(anim.sub(left[1], right[1])) < 1e-4
        assert anim.norm(anim.sub(left[2], right[2])) < 1e-3


def test_body_angular_velocity_against_differences(rng=random.Random(4)):
    c = CumulativeBSplineQuaternionCurve(random_keys(rng, 6))
    h = 1e-6
    for _ in range(30):
        j = rng.randrange(c.segments())
        u = rng.uniform(0.01, 0.99)
        q = c.segment(j, u)
        dq = tuple((a - b) / (2 * h) for a, b in zip(c.segment(j, u + h), c.segment(j, u - h)))
        w = anim.q_mul(anim.q_conj(q), dq)
        num = (2 * w[1], 2 * w[2], 2 * w[3])
        assert anim.norm(anim.sub(num, c.body_angular_velocity(j, u))) < 1e-7


def test_local_control(rng=random.Random(5)):
    keys = random_keys(rng, 9)
    c = CumulativeBSplineQuaternionCurve(keys)
    k = 4
    moved = list(keys)
    moved[k] = anim.q_mul(keys[k], anim.q_from_axis_angle((1, 2, 3), 0.7))
    d = CumulativeBSplineQuaternionCurve(moved)
    for j in range(c.segments()):
        diff = max(anim.norm(anim.sub(c.segment(j, u), d.segment(j, u))) for u in (0.0, 0.4, 1.0))
        if j <= k <= j + 3:
            assert diff > 1e-3
        else:
            assert diff < 1e-15


def test_frame_independence(rng=random.Random(6)):
    keys = random_keys(rng, 6)
    a, b = random_unit(rng), random_unit(rng)
    c = CumulativeBSplineQuaternionCurve(keys)
    d = CumulativeBSplineQuaternionCurve([anim.q_mul(anim.q_mul(a, q), b) for q in keys])
    for _ in range(40):
        t = rng.uniform(0.0, c.segments())
        assert same_rotation(d(t), anim.q_mul(anim.q_mul(a, c(t)), b), 1e-12)


def test_sign_of_the_keys_does_not_matter(rng=random.Random(7)):
    keys = random_keys(rng, 6)
    flipped = [q if i % 2 == 0 else tuple(-x for x in q) for i, q in enumerate(keys)]
    c = CumulativeBSplineQuaternionCurve(keys)
    d = CumulativeBSplineQuaternionCurve(flipped)
    for k in range(25):
        t = c.segments() * k / 24
        assert same_rotation(c(t), d(t), 1e-12)


def test_reversed_keys_give_a_slightly_different_curve(rng=random.Random(9)):
    keys = random_keys(rng, 5)
    c = CumulativeBSplineQuaternionCurve(keys)
    d = CumulativeBSplineQuaternionCurve(keys[::-1])
    gaps = []
    for t in (0.3, 1.0, 1.6):
        a, b = c(t), d(c.segments() - t)
        gaps.append(min(anim.norm(anim.sub(a, b)), anim.norm(anim.add(a, b))))
    assert max(gaps) > 1e-3 and max(gaps) < 0.1


def test_needs_four_keys():
    with pytest.raises(ValueError):
        CumulativeBSplineQuaternionCurve([(1.0, 0.0, 0.0, 0.0)] * 3)

History

Shoemake (1985) brought quaternion curves to animation with slerp and spherical Bezier curves. Kim, Kim and Shin (1995) observed that the cumulative form of a spline turns into a unit quaternion curve when each difference becomes a power of a relative rotation. They gave the construction for the B-spline, Bezier and Hermite bases, and showed that the derivatives of the curves have simple forms. The cumulative B-spline curve is now also used for continuous-time trajectories of cameras and inertial sensors.

References

  1. Myoung-Jun Kim, Myung-Soo Kim and Sung Yong Shin, A general construction scheme for unit quaternion curves with simple high order derivatives, Proceedings of SIGGRAPH 1995, 369-376, 1995, the whole paper (the cumulative form of a spline, the unit quaternion curve built from it, its derivatives, and the B-spline, Bezier and Hermite cases)
  2. Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, Chapter 3, Section 3.3 (interpolation of orientations)

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.build
  • a full proof of time.query
  • 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