Keyframes and Sampling
Physics computes motion. Animation plays back motion that an artist authored (or a motion-capture session recorded). The data format behind every animation clip, from a door swing to a full-body run cycle, is the same: tracks of keyframes.
- A keyframe (key) is a time and a value: "at 0.2 s the door is at 45°".
- A track (channel, curve) is a sorted list of keys for one property: one bone's rotation, one light's intensity, one UI element's alpha.
- A clip is a set of tracks with a length: a walk cycle has one rotation track per bone, plus a translation track for the root (and sometimes for other bones).
Playing a clip means sampling every track at the current playback time. Sampling is the topic of this lesson.
Finding the segment
Keys are sorted by time, so finding the two keys around time t is a binary search (std::upper_bound), O(log n) per track. Many runtimes also cache the last segment index per track: playback moves forward a little each frame, so the right segment is usually the same one or the next.
Then interpolate between the two keys, using u = (t - t0) / (t1 - t0) in [0, 1]:
| Mode | Formula | Looks like | Used for |
|---|---|---|---|
| Step (constant) | value of the earlier key | instant jumps | sprite frames, visibility, switching weapons |
| Linear | lerp a + (b - a) * u |
constant speed, sharp corners at keys | most baked skeletal data (dense keys) |
| Cubic Hermite | values plus tangents at both ends | smooth, may overshoot | hand-keyed curves in editors |
Cubic Hermite needs a tangent (slope) at each key. Editors store tangents the artist shaped; the simplest automatic choice is the Catmull-Rom slope from the neighbouring keys, the same curve as in Catmull-Rom Splines.
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cmath>
struct Key { double t, value; };
enum class Interp { Step, Linear, Cubic };
// Index of the last key with key.t <= t (binary search), clamped to a valid segment start.
size_t segmentAt(const std::vector<Key>& keys, double t) {
auto it = std::upper_bound(keys.begin(), keys.end(), t, [](double v, const Key& k) { return v < k.t; });
size_t i = it == keys.begin() ? 0 : size_t(it - keys.begin()) - 1;
return std::min(i, keys.size() - 2);
}
double sampleTrack(const std::vector<Key>& keys, double t, Interp mode) {
t = std::clamp(t, keys.front().t, keys.back().t); // clamp mode: hold the end values
size_t i = segmentAt(keys, t);
const Key& a = keys[i]; const Key& b = keys[i + 1];
double h = b.t - a.t, u = (t - a.t) / h; // 0..1 inside the segment
if (mode == Interp::Step) return u < 1 ? a.value : b.value;
if (mode == Interp::Linear) return a.value + (b.value - a.value) * u;
// Cubic Hermite with Catmull-Rom tangents (slope from the neighbouring keys)
auto slope = [&](size_t k) {
size_t lo = k == 0 ? 0 : k - 1, hi = std::min(k + 1, keys.size() - 1);
return (keys[hi].value - keys[lo].value) / (keys[hi].t - keys[lo].t);
};
double m0 = slope(i) * h, m1 = slope(i + 1) * h;
double u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * a.value + (u3 - 2 * u2 + u) * m0
+ (-2 * u3 + 3 * u2) * b.value + (u3 - u2) * m1;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
// A door's opening angle in degrees: closed, quickly half open, slowly fully open, a little bounce back.
std::vector<Key> door = {{0.0, 0}, {0.2, 45}, {1.0, 90}, {1.2, 80}};
std::cout << " t step linear cubic\n";
for (double t : {-0.1, 0.0, 0.1, 0.2, 0.4, 0.6, 0.9, 1.0, 1.1, 1.5}) {
std::cout << std::setw(6) << t << std::setw(9) << sampleTrack(door, t, Interp::Step)
<< std::setw(9) << sampleTrack(door, t, Interp::Linear) << std::setw(9) << sampleTrack(door, t, Interp::Cubic) << "\n";
}
} t step linear cubic
-0.100 0.000 0.000 0.000
0.000 0.000 0.000 0.000
0.100 0.000 22.500 25.875
0.200 45.000 45.000 45.000
0.400 45.000 56.250 60.844
0.600 45.000 67.500 73.000
0.900 45.000 84.375 86.371
1.000 90.000 90.000 90.000
1.100 90.000 85.000 87.125
1.500 80.000 80.000 80.000
Some things to notice:
- At key times all three modes agree, because every mode passes through the keys.
- Step holds 0 until the 0.2 s key, then 45 until the 1.0 s key: correct for a sprite index, wrong for a door.
- The cubic curve leaves each key with the slope of its neighbours, so it eases in and out instead of changing speed instantly at 0.2 s. Near 0.1 s it is ahead of the linear value (25.9 vs 22.5) because the door starts with the steep slope of the first segment.
- Times outside the clip are clamped: before the start you get the first key, after the end the last key.
Note: Rotation tracks are sampled the same way, but each segment blends quaternions with nlerp or slerp instead of a scalar lerp (see Slerp). Never interpolate Euler angles from a skeleton: a bone that turns from 350° to 10° would spin the long way around.
Wrap modes
What happens past the end of the clip is a property of how it is played:
- Clamp (once): hold the last pose. Death animations, door swings.
- Loop: wrap around with
fmod. Walk and run cycles, idle breathing. The first and last keys of a loop must match, or the character pops once per cycle. - Ping-pong: forward, then backward. Swinging lights, idle machinery.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
// Turn a playback position into a clip-local time, for the three usual wrap modes.
double wrapTime(double t, double length, const std::string& mode) {
if (mode == "clamp") return std::fmin(std::fmax(t, 0.0), length);
if (mode == "loop") {
double r = std::fmod(t, length);
return r < 0 ? r + length : r; // fmod keeps the sign: fix negatives (rewinding)
}
// ping-pong: forward, then backward
double r = std::fmod(t, 2 * length);
if (r < 0) r += 2 * length;
return r <= length ? r : 2 * length - r;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
const double length = 1.2; // a 1.2 s walk cycle
std::cout << "playback clamp loop ping-pong\n";
for (double t : {0.5, 1.2, 1.5, 2.6, 3.7, -0.3}) {
std::cout << std::setw(8) << t << std::setw(8) << wrapTime(t, length, "clamp")
<< std::setw(8) << wrapTime(t, length, "loop") << std::setw(10) << wrapTime(t, length, "ping-pong") << "\n";
}
}playback clamp loop ping-pong
0.500 0.500 0.500 0.500
1.200 1.200 0.000 1.200
1.500 1.200 0.300 0.900
2.600 1.200 0.200 0.200
3.700 1.200 0.100 1.100
-0.300 0.000 0.900 0.300
Watch the negative input: std::fmod(-0.3, 1.2) is -0.3 in C++ (the result keeps the sign of the dividend), so playing a loop backwards needs the + length fix.
How many keys? Sampling rate and compression
Exporters from Blender, Maya or a motion-capture pipeline usually bake every frame: one key per bone per track at 30 or 60 samples per second. A 60-bone character with a rotation and translation per bone at 30 Hz is around 60 × 30 × 7 floats ≈ 50 KB per second of animation, before scale tracks. Games ship hundreds of clips, so runtimes compress them:
- Key reduction: drop keys that interpolation can rebuild within a tolerance.
- Quantization: store quaternions in 48 bits or less instead of 128 (drop the largest component and rebuild it, since a unit quaternion's length is 1).
- Curve fitting and wavelet methods in high-end libraries.
Here is key reduction on one second of a baked hip bob (a 2 Hz bounce plus a small drift):
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
struct Key { double t, value; };
// Greedy key reduction: keep a key only if linear interpolation between the last kept key
// and the next candidate would miss some of the original samples by more than `tolerance`.
std::vector<Key> reduce(const std::vector<Key>& in, double tolerance) {
std::vector<Key> out = {in.front()};
size_t anchor = 0;
for (size_t end = 2; end < in.size(); end++) {
const Key& a = in[anchor]; const Key& b = in[end];
bool fits = true;
for (size_t k = anchor + 1; k < end && fits; k++) {
double u = (in[k].t - a.t) / (b.t - a.t);
fits = std::fabs(a.value + (b.value - a.value) * u - in[k].value) <= tolerance;
}
if (!fits) { out.push_back(in[end - 1]); anchor = end - 1; }
}
out.push_back(in.back());
return out;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
// One second of a hip bob baked at 30 samples per second: what exporters produce.
std::vector<Key> baked;
for (int i = 0; i <= 30; i++) {
double t = i / 30.0;
baked.push_back({t, 0.05 * std::sin(2 * 3.141592653589793 * 2 * t) + (t > 0.5 ? 0.1 : 0.0) * (t - 0.5)});
}
std::cout << "baked keys: " << baked.size() << "\n";
for (double tol : {0.001, 0.002, 0.005, 0.02}) {
auto kept = reduce(baked, tol);
std::cout << "tolerance " << tol << " m -> " << std::setw(2) << kept.size() << " keys ("
<< std::setprecision(0) << 100.0 * kept.size() / baked.size() << std::setprecision(3) << "%)\n";
}
}baked keys: 31
tolerance 0.001 m -> 27 keys (87%)
tolerance 0.002 m -> 23 keys (74%)
tolerance 0.005 m -> 14 keys (45%)
tolerance 0.020 m -> 6 keys (19%)
A 2 cm error budget keeps 6 keys out of 31, but 2 cm on a hip is visible as a lack of bounce, and errors add up down the hierarchy: a small rotation error on a shoulder becomes a large position error at the fingertips. That is why serious compressors (for example the open-source ACL library, or the engines' own codecs) measure the error on the resulting vertex or joint positions, not on each track's raw values. Unity's import settings (Anim. Compression with rotation/position error), Unreal's compression settings on animation sequences and Godot's import compression all expose this trade-off.
Test yourself
How do runtimes find the two keys around time t in a track efficiently?
- A linear scan from the first key every frame
- Binary search on the sorted key times (often with the last segment cached)
- A hash table keyed by time
- They resample the whole clip each frame
Which interpolation mode fits a track that switches a sprite frame index?
- Linear
- Cubic Hermite
- Step (constant)
- Slerp
Why should animation compression measure error on final joint or vertex positions instead of per track?
- Because it is faster
- Because rotation errors on parent bones grow along the hierarchy, so an equal track error matters much more on a shoulder than on a finger
- Because tracks have no units
- Because quaternions cannot be compared