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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The cumulative B-spline quaternion curve of Kim, Kim and Shin (1995) is a smooth curve of unit quaternions controlled by a sequence of orientations. It starts from the B-spline written in cumulative form, , where . Each sum becomes a product and each scaled difference becomes a power of a relative rotation:
For the uniform cubic B-spline the curve is , 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 , , in the Hamilton convention with the scalar first. The output is a curve of unit quaternions for that is , 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 . The logarithm of a unit quaternion is , and is its inverse on pure quaternions.
The algorithm
On segment with the local parameter , only four basis functions are active. The factors before them are , whose product telescopes to , and the factors after them are 1. So the segment is
with the cumulative uniform cubic basis
KKS(q₀, ..., qₙ₋₁; j, u) ▷ control quaternions; the point of segment j at u- 1
for k ← 1 to n - 1: if qₖ₋₁ · qₖ < 0 then - 2
qₖ ← -qₖ ▷ the same rotation, near the previous one - 3
for k ← 1 to n - 1: ωₖ ← log(qₖ₋₁* qₖ) ▷ half the rotation vector of each step - 4
(B̃₁, B̃₂, B̃₃) ← the cumulative basis at u - 5
q ← qⱼ - 6
for k ← 1 to 3 do - 7
q ← q exp(B̃ₖ ωⱼ₊ₖ) ▷ a part of the k-th step - 8
return q
Lines L1 to L3 run once for the sequence. Lines L4 to L8 are the query; for a global parameter , use and . The factors of line L7 must be applied in this order, since quaternion products do not commute.
Example
Take four control orientations: ; , a turn by 90 degrees about ; , a further turn by 90 degrees about the body axis; and , a further turn by 90 degrees about the body axis.
- Lines L1 and L2: all adjacent dot products are , so no sign changes.
- Line L3: , and .
- At the basis is , and , a rotation by 1.33114 radians. The key is a rotation by , so the curve does not pass through it.
- At the basis is , and , close to the midpoint of the slerp from to .
- At the basis is , and .
The body angular velocity at is radians per unit of .
Correctness
In the global form, each cumulative basis function is a sum of cubic B-splines, so it is . The map is smooth, so each factor is a curve of unit quaternions. A product of finitely many curves is , so is . Each factor has length 1, so is a unit quaternion.
The segment form of line L7 is the global form: on segment , for and for , by the partition of unity and the supports of the B-splines. Then . 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 with a unit vector , for real , which is a unit quaternion and a smooth function of . The uniform cubic B-splines are piecewise cubics on the knots , numbered so that on the active ones are , with for
They sum to 1 on .
The cumulative basis
Lemma 1. Let . On , for , for , and for , which gives the three polynomials of the page.
Proof. On only are nonzero. For the sum contains all of them, so it is 1. For it contains none of them. For it is . Adding the polynomials gives , and .
Lemma 2. Each is on .
Proof. It is a finite sum of functions.
The segment form
Lemma 3. After lines L1 to L3, for each .
Proof. Line L2 makes , so has a scalar part and its angle is in . On such unit quaternions, .
Lemma 4. On the global curve equals the segment form of lines L4 to L8 with .
Proof. By Lemma 1 the factors with are by Lemma 3, and the factors with are . The product telescopes to , because . The remaining factors are those of line L7, in the same order.
Smoothness and unit length
Theorem. is a unit quaternion for every , and is .
Proof. Each factor is a unit quaternion, and a product of unit quaternions has length 1. The factor is the composition of the smooth map with the function of Lemma 2, so it is . The quaternion product is bilinear, so a product of finitely many curves is by the product rule.
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 function.
Derivatives
Lemma 5. With , , and the body angular velocity on segment is
Proof. is a function of the commuting family , so its derivative is by the chain rule. The product rule gives . Multiplying on the left by and using gives the formula.
Rotations about one axis
Lemma 6. If every is a rotation about the same unit axis , with angles and , then is the rotation about by .
Proof. After the sign test, up to a common sign choice, and . All factors are rotations about , so they commute and their half angles add: by summation by parts, since on the domain.
Independence of frames
Lemma 7. For unit quaternions and , the control quaternions give the curve .
Proof. , and conjugation by is a rotation of the pure quaternions, so the new is and . In the product , the inner factors cancel, which leaves . The dot products of line L1 do not change, because multiplication by unit quaternions is an isometry of .
Complexity
The build step, lines L1 to L3, costs time: one quaternion product and one logarithm per step, and space for the . A query costs : three exponentials and three quaternion products. The body angular velocity costs about as much more, with the closed form of the Properties section.
Properties
- continuity. The curve, its velocity and its acceleration are continuous on .
- Simple derivatives. With , and . So the body angular velocity is .
- Approximation, not interpolation. At the joint of segment , the curve is , not . For rotations about one axis the angle there is , as for the scalar B-spline.
- Local control. Segment depends on only, so moving one control quaternion changes four segments.
- Independence of frames. For unit quaternions and , the control quaternions give the curve .
- 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 .
- 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 , 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 , and the curve turns the long way.
- Steps of a half turn. If two adjacent control quaternions differ by a rotation of , 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 , 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7V1M8B Edit this page History Report an error Markdown