Algorithmcore
Motion warping
Also called motion displacement mapping.
Edit a captured motion by adding a smooth displacement curve that meets new keyframe constraints while keeping the high-frequency detail.
- Time
- O(j (m + f log m)) warp
- Space
- O(j (f + m)) extra
- Where
- f = the number of frames; j = the number of channels; m = the number of keys in a channel
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew Witkin, Zoran Popović, 1995
Motion warping changes a captured motion so that it meets a few new key poses, and keeps all the small detail of the capture. Each joint channel becomes
where is a time warp, is a smooth scale curve and is a smooth offset curve. The animator sets keys where the new channel must have the value . With fixed, each key gives one offset , and is a spline through the offsets. Because is smooth and only adds to , the high frequency parts of the capture (the small shakes, the impact of a foot) stay as they were; only a slow change is added. The cost is for the spline of keys and to evaluate it on frames, for each channel.
In plain words
You have a captured motion of a person who reaches for a cup. Now the cup is 10 cm higher. You do not want to animate the arm again by hand, because you would lose all the small life of the real motion. So you say only: at this moment, the shoulder must be raised a bit more. The method computes a smooth correction that is zero far away and grows to the needed amount at that moment. It adds the correction to the captured motion. The small movements of the original are still there, on top of the slow correction.
The problem
The input is one or more channels, each a list of samples at the frames (a joint angle, a root coordinate), a list of keys with for each channel, an optional scale curve , and an optional time warp . The output is a new channel with for every key, as smooth as the input between the keys, and equal to when every key already holds.
The time warp maps new time to original time. It is given by pairs with both lists increasing: the new motion reaches original time at new time . Between the pairs is linear, and outside them it has slope 1. So the warp can slow down or speed up parts of a motion, for example to make a jump wait for a moving platform.
The algorithm
MOTION-WARP(θ, keys, c, g) ▷ samples, keys (tₖ, vₖ), scale, time warp- 1
src(t) ← θ(g(t)) ▷ the original, read at the warped time - 2
βₖ ← vₖ - c(tₖ) · src(tₖ) for every key ▷ the offset needed at each key - 3
b ← the natural cubic spline through (tₖ, βₖ), constant outside [t₁, tₘ] - 4
θ'(t) ← c(t) · src(t) + b(t) for every channel- 5
evaluate θ' at the new frames 0, 1, 2, ... - 6
return the new frames
The samples are read between frames by linear interpolation, clamped at the ends. For rotations stored as joint angles, the method works channel by channel; for quaternion channels, the offset is a rotation and the sum is a product, an extension that the code does not cover.
Line L3 uses a natural cubic spline: a cubic on each interval between keys, at the keys, with zero second derivative at the first and the last key. Its second derivatives solve a tridiagonal system with a strictly dominant diagonal, so the Thomas algorithm solves it in . With one key, is a constant; with two, it is a line between the keys. The original paper uses interpolating splines for and ; the natural spline and the constant ends are choices of the code.
Example
Take a channel with , and , no scale, no time warp, and the keys , , . Line L2 gives the offsets .
The spline has the knot spacing and one unknown second derivative in the middle, with :
At , with ,
So , and by symmetry . For the offset is 0.3, and for it is 0.3. Whatever detail has between the keys, it is kept; only the smooth curve is added.
A time warp with the pairs , , plays the first 80 frames over 100 frames; new frame 25 reads original time 20, and new frame 75 reads original time 60.
Correctness
The proof file shows the following facts, in exact arithmetic.
- The natural spline through keys exists and is unique, because its tridiagonal system has a strictly dominant diagonal.
- It reproduces linear data: offsets on a line give that line.
- So the warped channel meets every key, (Theorem 1).
- If every key already holds, the offset is zero and the motion is unchanged up to the scale and the time warp (Theorem 2).
- A linear change at the keys gives exactly that linear change between them (Theorem 3).
- The offset is between the first and the last key, so it adds no corner (Theorem 4).
- The time warp is continuous and strictly increasing and maps each pair as given (Theorem 5), so it never plays the motion backward.
That the result looks like the same actor is a visual heuristic, not a theorem. A large offset or a strong time warp changes the dynamics: a sped up jump does not follow the same parabola in a world with the same gravity, and a raised arm can push a hand through the body.
Proof: A motion warp meets its keys, leaves a motion unchanged when the keys already hold, and keeps the order of the posesfull
We use the notation of the page. The arithmetic is exact. One channel is a function , sampled at the frames and read between frames by linear interpolation. The keys are pairs with in new time. The scale curve is 1, or a natural cubic spline through its own keys. The time warp is the identity, or the piecewise linear map through pairs with both lists strictly increasing, with slope 1 outside the pairs. Lines L1 to L4 compute , where is the natural cubic spline through the points with .
The natural cubic spline
Lemma 1. For points with increasing , there is exactly one function that is a cubic on each , is on , has , and has at and . Its second derivatives solve a tridiagonal system that is strictly diagonally dominant, and the Thomas algorithm solves it without pivoting.
Proof. On with , the cubic with values and second derivatives at the ends is with and ; this is the formula in the code. It has the right values and second derivatives, so is and its second derivative is continuous for any . Continuity of at each inner key is the equation , and the natural ends set . The diagonal is larger than the sum of the off diagonal entries, so the matrix is strictly diagonally dominant, nonsingular, and the Thomas algorithm has no zero pivot.
For the code uses the constant . Outside the code holds the end values; this is a choice of the code and is part of the definition of .
Lemma 2. If the are values of a linear function , then on .
Proof. solves the system, because the right side is , and by Lemma 1 the solution is unique. With the formula is the linear interpolation of the values, which is .
The keys
Theorem 1. for every key.
Proof. , by Lemma 1 for and by the constant for .
Theorem 2. If every key already holds, that is , then : the displacement is zero.
Proof. All , so by Lemma 2 with , and by the constant hold outside.
Theorem 3. If the scale is 1 and the wanted change is linear, , then on .
Proof. , and Lemma 2 applies.
Theorem 4. The displacement is on , so it adds no corner to the motion; where and are smooth, is as smooth as they are.
Proof. Lemma 1.
The time warp
Theorem 5. is continuous and strictly increasing, and . So the warped motion shows the poses of in the same order, and never plays a part of the motion backward.
Proof. On each piece , is linear from to with slope . Outside the pairs the slope is 1, and the pieces meet at the pairs. The code raises an error if a list is not strictly increasing.
Complexity
For each channel, line L2 costs , the spline of line L3 costs with the Thomas algorithm, and the evaluation of line L5 costs per frame for the search of the interval, so for all frames. For channels this is time and space. When the frames are evaluated in order, a moving index replaces the search and the time is .
Properties
- Exact at the keys. Every key holds, up to rounding.
- Local in size. The offset depends only on the keys; between two keys it is a cubic, so far from all keys it is the end constant.
- No change without need. Keys that the motion already meets change nothing.
- Detail kept. The added curve has only the frequencies of the key spacing; the higher frequencies of the capture pass unchanged.
- Channel by channel. No constraint between joints is kept; for a hand or a foot at a place, use inverse kinematics first to find the joint keys.
Variants and improvements
- Scale curve. A curve through scale keys stretches the motion around zero, for example to make a gesture larger.
- Hierarchical displacement. Later work fits the offset with a hierarchy of B-splines, coarse first, so that keys close in time get detail and keys far apart get a smooth change.
- Motion signal processing. Motion signal processing of Bruderlin and Williams edits the frequency bands of the channels; their motion displacement mapping is the same idea as motion warping, from the same conference.
- Constraint based editing. Spacetime constraints and per frame inverse kinematics solve for the change from positions of end effectors.
- Blending. To join two motions, warp the end of one and the start of the other to meet at a common pose, then blend.
When to use it
Use motion warping to fit a captured motion to a new scene with small changes: a hand that must reach a new place, a foot on a step, a jump that must last a few frames longer. It is fast and needs only a few keys. For large changes, or when contacts must hold over many frames, combine it with inverse kinematics and footskate cleanup, or use a method that knows about the body.
Pitfalls
- Keys too close. Two keys a few frames apart with very different offsets make the spline swing far beyond both offsets between and around them.
- Euler angles. Warping three Euler channels of one joint independently can give an unexpected rotation, mostly near gimbal lock. Warp in a parameterization that is well behaved near the pose, or use quaternion offsets.
- Foot contacts. An offset on the hip or the legs moves a planted foot. Fix the contacts after the warp.
- Time warp physics. Slowing a fall makes it float. Keep the time warp mild in ballistic phases.
- Ends. Outside the key range, the code holds the end offset. Without it, a spline continued past the last key can grow without bound.
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
# Part of https://algorithm.tamnd.com/motion-warping/. The authors are listed in prov/7QR9V6.jsonl.
"""Motion warping (Witkin and Popovic 1995) of sampled joint curves.
A motion channel is a list of samples theta[0..f-1] at the frame times
0, 1, ..., f-1 (any unit of time; the code uses frames). The warped channel
is
theta'(t) = c(t) theta(g(t)) + b(t),
where g is a time warp (a monotone piecewise linear map from new time to
original time), c is a smooth scale curve and b is a smooth offset curve.
The animator gives key constraints (t_k, value_k): the warped channel must
take value_k at time t_k. With c fixed (by default c = 1), the offsets
b_k = value_k - c(t_k) theta(g(t_k)) are interpolated by a natural cubic
spline, so theta' passes through every key and stays C2 between keys
wherever theta is C2. Outside the key range, b keeps its end value.
"""
import bisect
def sample(theta, t):
"""Linear interpolation of the samples, clamped at the ends."""
f = len(theta)
if t <= 0:
return theta[0]
if t >= f - 1:
return theta[-1]
i = int(t)
u = t - i
return (1 - u) * theta[i] + u * theta[i + 1]
class NaturalSpline:
"""The natural cubic spline through (x_k, y_k), x strictly increasing."""
def __init__(self, xs, ys):
n = len(xs)
if n < 1 or any(b <= a for a, b in zip(xs, xs[1:])):
raise ValueError("key times must increase")
self.x, self.y = list(xs), list(ys)
self.m = [0.0] * n # second derivatives
if n > 2:
h = [xs[i + 1] - xs[i] for i in range(n - 1)]
# tridiagonal system for m[1..n-2], with m[0] = m[n-1] = 0
a = [h[i - 1] for i in range(1, n - 1)]
b = [2.0 * (h[i - 1] + h[i]) for i in range(1, n - 1)]
c = [h[i] for i in range(1, n - 1)]
d = [6.0 * ((ys[i + 1] - ys[i]) / h[i] - (ys[i] - ys[i - 1]) / h[i - 1])
for i in range(1, n - 1)]
for i in range(1, len(b)):
w = a[i] / b[i - 1]
b[i] -= w * c[i - 1]
d[i] -= w * d[i - 1]
sol = [0.0] * len(b)
sol[-1] = d[-1] / b[-1]
for i in range(len(b) - 2, -1, -1):
sol[i] = (d[i] - c[i] * sol[i + 1]) / b[i]
self.m[1:n - 1] = sol
def __call__(self, t):
x, y, m = self.x, self.y, self.m
if len(x) == 1 or t <= x[0]:
return y[0]
if t >= x[-1]:
return y[-1]
i = bisect.bisect_right(x, t) - 1
h = x[i + 1] - x[i]
A = (x[i + 1] - t) / h
B = (t - x[i]) / h
return (A * y[i] + B * y[i + 1]
+ ((A ** 3 - A) * m[i] + (B ** 3 - B) * m[i + 1]) * h * h / 6.0)
class TimeWarp:
"""g(t') through the pairs (new time, original time), both increasing.
Outside the pairs, g has slope 1."""
def __init__(self, pairs):
self.new = [p for p, _ in pairs]
self.old = [q for _, q in pairs]
if any(b <= a for a, b in zip(self.new, self.new[1:])) or \
any(b <= a for a, b in zip(self.old, self.old[1:])):
raise ValueError("a time warp must be strictly increasing")
def __call__(self, t):
n, o = self.new, self.old
if t <= n[0]:
return o[0] + (t - n[0])
if t >= n[-1]:
return o[-1] + (t - n[-1])
i = bisect.bisect_right(n, t) - 1
u = (t - n[i]) / (n[i + 1] - n[i])
return o[i] + u * (o[i + 1] - o[i])
def warp_channel(theta, keys, scale_keys=None, timewarp=None):
"""Return the function t -> theta'(t) for one channel.
keys: list of (t_k, value_k) in new time; scale_keys: optional list of
(t_k, c_k) for the scale curve; timewarp: optional TimeWarp.
"""
g = timewarp if timewarp is not None else (lambda t: t)
if scale_keys:
c = NaturalSpline([t for t, _ in scale_keys], [v for _, v in scale_keys])
else:
c = lambda t: 1.0
src = lambda t: sample(theta, g(t)) # @line L1
keys = sorted(keys)
offsets = [v - c(t) * src(t) for t, v in keys] # @line L2
b = NaturalSpline([t for t, _ in keys], offsets) # @line L3
return lambda t: c(t) * src(t) + b(t) # @line L4
def warp_motion(motion, keys_per_channel, timewarp=None, frames=None):
"""Warp every channel and resample at the integer new times.
motion: list of frames, each a list of channel values.
keys_per_channel: dict channel -> list of (t, value); channels without
keys get only the time warp.
"""
f = len(motion)
if frames is None:
frames = f if timewarp is None else int(timewarp.new[-1]) + 1
chans = list(zip(*motion))
out_ch = []
for ci, ch in enumerate(chans):
keys = keys_per_channel.get(ci)
if keys:
fn = warp_channel(list(ch), keys, timewarp=timewarp)
else:
g = timewarp if timewarp is not None else (lambda t: t)
fn = lambda t, ch=ch, g=g: sample(list(ch), g(t))
out_ch.append([fn(t) for t in range(frames)]) # @line L5
return [list(v) for v in zip(*out_ch)] # @line L6
test_motion_warping.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-warping/. The authors are listed in prov/7QR9V6.jsonl.
"""Tests of motion warping.
The warped channel passes through every key, keys at the original values
change nothing, a linear offset is reproduced exactly, the offset spline is
C2 at the keys, the time warp is monotone and maps its pairs exactly, and
the scale curve is honored at the keys. Motion data is made in code.
"""
import math
import random
import motion_warping as mw
def channel(f, seed):
rng = random.Random(seed)
a, w, p = rng.uniform(0.2, 1.0), rng.uniform(0.1, 0.3), rng.uniform(0, 6)
return [a * math.sin(w * i + p) + 0.1 * math.cos(0.05 * i) for i in range(f)]
def test_keys_are_met():
rng = random.Random(1)
th = channel(120, 2)
keys = sorted((rng.uniform(0, 119), rng.uniform(-1, 1)) for _ in range(6))
fn = mw.warp_channel(th, keys)
for t, v in keys:
assert abs(fn(t) - v) < 1e-12
def test_keys_on_the_curve_change_nothing():
th = channel(80, 3)
keys = [(10.0, th[10]), (40.0, th[40]), (70.0, th[70])]
fn = mw.warp_channel(th, keys)
assert max(abs(fn(t) - th[t]) for t in range(80)) < 1e-12
def test_linear_offset_is_exact():
s = mw.NaturalSpline([0.0, 3.0, 7.0, 12.0, 20.0], [1.0 + 0.5 * x for x in (0.0, 3.0, 7.0, 12.0, 20.0)])
for k in range(201):
x = k / 10.0
assert abs(s(x) - (1.0 + 0.5 * x)) < 1e-12
def test_spline_is_c2_at_the_keys():
rng = random.Random(5)
xs = [0.0, 2.0, 5.0, 6.0, 10.0, 13.0]
ys = [rng.uniform(-1, 1) for _ in xs]
s = mw.NaturalSpline(xs, ys)
h = 1e-4
for x in xs[1:-1]:
left = (s(x) - 2 * s(x - h) + s(x - 2 * h)) / (h * h)
right = (s(x + 2 * h) - 2 * s(x + h) + s(x)) / (h * h)
d1l = (s(x) - s(x - h)) / h
d1r = (s(x + h) - s(x)) / h
assert abs(left - right) < 1e-2
assert abs(d1l - d1r) < 1e-2
# natural end conditions: zero second derivative at both ends
for x, sgn in ((xs[0], 1), (xs[-1], -1)):
d2 = (s(x) - 2 * s(x + sgn * h) + s(x + 2 * sgn * h)) / (h * h)
assert abs(d2) < 1e-2
def test_timewarp_is_monotone_and_maps_pairs():
tw = mw.TimeWarp([(0.0, 0.0), (30.0, 20.0), (90.0, 80.0), (100.0, 119.0)])
vals = [tw(t / 4.0) for t in range(-40, 440)]
assert all(b > a for a, b in zip(vals, vals[1:]))
for n, o in [(0.0, 0.0), (30.0, 20.0), (90.0, 80.0), (100.0, 119.0)]:
assert tw(n) == o
try:
mw.TimeWarp([(0.0, 0.0), (10.0, 5.0), (20.0, 4.0)])
raised = False
except ValueError:
raised = True
assert raised
def test_warp_motion_with_timewarp_and_keys():
f = 120
motion = [[a, b] for a, b in zip(channel(f, 7), channel(f, 8))]
tw = mw.TimeWarp([(0.0, 0.0), (50.0, 30.0), (100.0, 119.0)])
keys = {0: [(20.0, 0.5), (60.0, -0.2)]}
out = mw.warp_motion(motion, keys, timewarp=tw)
assert len(out) == 101
assert abs(out[20][0] - 0.5) < 1e-12 and abs(out[60][0] + 0.2) < 1e-12
# channel 1 has no keys: it is the original at the warped time
ch1 = [m[1] for m in motion]
for t in (0, 50, 100):
assert abs(out[t][1] - mw.sample(ch1, tw(t))) < 1e-12
def test_scale_curve_at_keys():
th = channel(60, 9)
keys = [(5.0, 0.3), (30.0, 0.9), (55.0, -0.4)]
scale = [(0.0, 1.0), (30.0, 2.0), (59.0, 1.0)]
fn = mw.warp_channel(th, keys, scale_keys=scale)
for t, v in keys:
assert abs(fn(t) - v) < 1e-12
History
Andrew Witkin and Zoran Popović presented motion warping at SIGGRAPH 95, with a few keyframes, a smooth warp of each channel, and a time warp, as a way to reuse captured or keyframed motion. At the same conference, Armin Bruderlin and Lance Williams presented motion signal processing, whose motion displacement mapping is the same idea. Later, Jehee Lee and Sung Yong Shin fitted the displacement with hierarchical B-splines and combined it with inverse kinematics.
References
- Andrew Witkin and Zoran Popović, Motion warping, SIGGRAPH 95, 1995, 105 to 108, the warp of a channel by a scale curve and an offset curve through keyframes, and the time warp
- Armin Bruderlin and Lance Williams, Motion signal processing, SIGGRAPH 95, 1995, 97 to 104, the section on motion displacement mapping
- Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, the material on the processing of motion capture data
Where this leads
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 7QR9V6 Edit this page History Report an error Markdown