Algorithm Search⌘K

Algorithmresearch

Motion matching

Every few frames, search a motion database for the frame whose pose and future trajectory features best match the current state and the user input.

Time
O(f d) normalize_database · searchO(d) query
Space
O(f d) database
Where
d = the number of feature dimensions; f = the number of frames in the database
Properties
deterministicexactonlineiterative
Origin
Simon Clavet, Michael Büttner, 2016

Motion matching animates a character from a large database of captured motion with no hand-made state machine and no precomputed transitions. Every frame of the database gets a feature vector: a few numbers about the current pose (foot positions and velocities, hip velocity) and a few about the near future (where the character will be and which way it will face in a third, two thirds and one second). At run time, every few frames, the game builds the same vector from the current pose and the trajectory that the player asks for, finds the database frame with the nearest vector, and jumps there with a short blend. The search is a nearest neighbor search with ff frames and dd dimensions, O(fd)O(f d) by brute force, or faster with a k-d tree or other index. The page describes the search of Clavet (2016); the name "learned motion matching" belongs to a later method of Holden and coworkers (2020), which replaces the database by neural networks, and is not the method of this page.

In plain words

Think of a large library of short films of a person who walks, runs and turns. Each frame has a label that says where the feet are now and where the person will be one second later. Many times per second, the game writes the same kind of label for the character on the screen: where its feet are now, and where the player wants it to be one second later. Then it looks through the library for the frame with the closest label. If that frame is not the one that would play next anyway, the game cuts to it with a short smooth fade. The character always plays real captured motion, and it follows the stick within a few frames.

The problem

The input is a database of ff frames with raw feature vectors v1,…,vf∈Rdv_1, \dots, v_f \in \mathbb{R}^d, split into groups (for example foot positions, foot velocities, hip velocity, trajectory positions, trajectory directions), a weight wg>0w_g > 0 for each group, and a set PP of playable frames. Each dimension kk has the mean μk\mu_k and the standard deviation σk\sigma_k over the database. The normalized vector of vv is xk=(vk−μk) wg(k)/σkx_k = (v_k - \mu_k)\, w_{g(k)} / \sigma_k.

A query is a raw vector vqv^q, built from the current pose and the desired future trajectory in the local frame of the character. The task is to return

i∗=arg min⁡i∈P∑k=1d(xik−xkq)2,i^* = \operatorname*{arg\,min}_{i \in P} \sum_{k=1}^{d} (x_{ik} - x^q_k)^2,

with ties broken by the lower frame number. The positions and directions are in the ground frame of the character at that frame (the root projected on the floor, with its heading), so a turn to the left matches every turn to the left in the database.

The algorithm

  1. MOTION-MATCHING-SEARCH(X, P, vq) ▷ normalized frames, playable set, raw query
  2. 1xq ← (vq - μ) ⊙ s ▷ sₖ = w_g(k) / σₖ, the group weight over the std
  3. best ← ∞; i* ← none
  4. 2for each frame i in P
  5. s ← 0
  6. 3for k ← 1 to d: s ← s + (X[i][k] - xq[k])²
  7. 4if s > best then stop this sum ▷ the frame cannot win
  8. 5if s < best then best ← s; i* ← i
  9. 6return i*

The run time loop calls the search. Each tick, the character advances to the next frame of its clip. Every nn ticks, or when the input changes sharply, the game builds the query from the current frame and the desired trajectory, and searches. If the result is not the frame that plays anyway, the character jumps to it and blends the pose over a few frames. Frames near the end of a clip are left out of PP, so that the character never reaches a clip end before the next search.

Line L4 is an early exit: the partial sums only grow, so once a partial sum is larger than the best full cost the frame cannot win. A k-d tree over the normalized vectors gives the same answer and skips whole groups of frames: if the squared distance from the query to a splitting plane is larger than the best cost, no frame on the far side can win.

Example

By hand. Three normalized frames X0=(0,0)X_0 = (0, 0), X1=(1,2)X_1 = (1, 2), X2=(3,0)X_2 = (3, 0) and the query xq=(1,1)x^q = (1, 1). Frame 0: s=1s = 1, then s=2s = 2; best =2= 2. Frame 1: s=0s = 0, then s=1s = 1; best =1= 1, i∗=1i^* = 1. Frame 2: s=4>1s = 4 > 1 after the first dimension, so line L4 stops the sum. The search returns frame 1, with cost 1.

The test database. The test builds five clips of 60 frames each at 30 frames per second: a straight walk at 1.2 m/s, a left turn and a right turn at 0.6 rad/s, a run at 2.5 m/s, and standing still. Each frame has d=22d = 22 features: the two foot positions (4 numbers, 2D), the two foot velocities (4), the hip velocity (2), the trajectory positions 20, 40 and 60 frames ahead (6) and the facing directions at the same times (6). The group weights are 0.75 for the foot positions, 1.5 for the directions and 1 for the rest; these are tuning, chosen for the test. The last 5 frames of each clip are not playable.

The character starts on frame 0 of the straight walk, with a search every 10 ticks, and the input asks for the features of the left turn from frame 70 on. At tick 10, the search jumps from frame 10 to frame 80, the exact match. At ticks 20 and 30, the best frame is the one that plays next, so no jump happens, and the character plays frames 80 to 109 of the turn. A second run in which every query is the features of the next frame makes no jump at all, as it must.

Correctness

The proof file shows that the normalized cost equals a weighted squared distance of the raw vectors with the weights (wg(k)/σk)2(w_{g(k)} / \sigma_k)^2, that the partial sums of line L3 never decrease (also in floating point, where each added term is nonnegative), and so that the early exit of line L4 never drops a frame that could win or tie. Line L6 then returns the brute force answer, with ties broken by the lower frame number, because line L5 replaces the best frame only on a strictly smaller cost and the frames are scanned in increasing order. It also shows that the k-d tree search returns the same frame: a skipped subtree holds no frame with a cost at most the best cost at the time of the skip, and the best cost only decreases.

These are facts about the search. The quality of the motion is a different question. The choice of features, the group weights and the search interval are tuning; that a nearest match looks good and follows the input is a visual heuristic, checked by looking at results and not proved.

Proof: The motion matching scan and the k-d tree return the brute force nearest framefull

We use the notation of the page. The database has ff frames with raw feature vectors vi∈Rdv_i \in \mathbb{R}^d, and a list PP of playable frames in increasing order. Line L1 maps a raw vector vv to x=σ⊙(v−μ)x = \sigma \odot (v - \mu), where μk\mu_k is the mean of dimension kk and σk=wg(k)/sk\sigma_k = w_{g(k)} / s_k is the weight of the feature group of kk over the standard deviation of kk. The cost of frame ii for the query qq is ci=∑k=1d(xik−qk)2c_i = \sum_{k=1}^{d} (x_{ik} - q_k)^2. The brute force answer is the smallest index i∈Pi \in P with the smallest cic_i.

The normalization

Lemma 1. The cost is the weighted squared distance ci=∑k(wg(k)/sk)2(vik−vkq)2c_i = \sum_k (w_{g(k)} / s_k)^2 (v_{ik} - v_k^{q})^2 of the raw vectors, where vqv^q is the raw query. In particular the mean μ\mu drops out, and scaling dimension kk of all the data and the query by a factor a≠0a \ne 0 does not change any cost.

Proof. xik−qk=σk(vik−μk)−σk(vkq−μk)=σk(vik−vkq)x_{ik} - q_k = \sigma_k (v_{ik} - \mu_k) - \sigma_k (v^q_k - \mu_k) = \sigma_k (v_{ik} - v^q_k). A scaling by aa multiplies sks_k and vik−vkqv_{ik} - v^q_k by ∣a∣|a| and aa, so σk(vik−vkq)\sigma_k (v_{ik} - v^q_k) changes only its sign. □\square

The scan with early exit

Lemma 2. In the loop of line L3, the partial sum ss never decreases. This also holds in floating point arithmetic with rounding to nearest.

Proof. Each step adds t2≥0t^2 \ge 0. In floating point, fl⁡(s+t2)≥s\operatorname{fl}(s + t^2) \ge s, because s+t2≥ss + t^2 \ge s and rounding to nearest is monotone and leaves ss unchanged. □\square

Theorem 1. Line L6 returns the brute force answer.

Proof. The invariant of the loop of line L2 is: after the frames P1,…,PmP_1, \dots, P_m, best=min⁡l≤mcPl\text{best} = \min_{l \le m} c_{P_l} and best_i\text{best\_i} is the first PlP_l with that cost. It holds before the loop with best=∞\text{best} = \infty. Take the next frame ii. If the loop of line L3 ends early at line L4, then a partial sum is greater than best, so by Lemma 2 ci>bestc_i > \text{best}, and frame ii changes nothing; the code does not change best, because s>bests > \text{best} fails the test of line L5. Otherwise s=cis = c_i, computed in the same order as the brute force cost. Line L5 replaces best only if ci<bestc_i < \text{best}, so a later frame with an equal cost does not replace an earlier one. So the invariant holds after frame ii. At the end, m=∣P∣m = |P|, and since PP is increasing the first frame with the smallest cost is the smallest index with that cost. ■\blacksquare

The k-d tree

The tree stores the normalized playable frames. An inner node splits on a dimension kk at a value tt: the points with xk<tx_k < t go left, the others go right. The search visits the child on the side of qq first, and visits the other child only if (qk−t)2≤best(q_k - t)^2 \le \text{best}.

Lemma 3. If (qk−t)2>best(q_k - t)^2 > \text{best}, no point of the far child has a cost at most best.

Proof. Every point xx of the far child is on the other side of tt from qkq_k in dimension kk, or on the plane, so ∣xk−qk∣≥∣qk−t∣|x_k - q_k| \ge |q_k - t|. So its cost is at least (xk−qk)2≥(qk−t)2>best(x_k - q_k)^2 \ge (q_k - t)^2 > \text{best}. □\square

Theorem 2. The k-d tree search returns the brute force answer.

Proof. The search keeps the same pair (best, best_i) as the scan, but it updates it on a cost that is smaller, or equal with a smaller index. By Lemma 3, a subtree that the search skips holds no point with a cost at most best at the time of the skip, and best only decreases later, so the skipped points cannot be the answer or tie with it. Every other point is compared. So the search ends with the smallest cost and, among equal costs, the smallest index. ■\blacksquare

The test compares the scan and the tree with the brute force search on 251 queries, including a duplicated feature row that makes a tie.

Complexity

Normalizing the database costs O(fd)O(f d) once. A query costs O(d)O(d) to normalize and O(fd)O(f d) for the scan in the worst case; the early exit and the tree only lower the constant in practice. A k-d tree with leaves of a few frames needs O(f(d+log⁡f)log⁡f)O(f (d + \log f) \log f) time to build in the code (a spread over all dimensions and a sort at each level) and O(fd)O(f d) space for the vectors; in 20 to 30 dimensions its search often visits a large part of the leaves, so engines also use bounding boxes over runs of frames or lower the precision of the vectors. With f=105f = 10^5 frames, about an hour at 30 frames per second, and d=27d = 27, one brute force search is 2.7⋅1062.7 \cdot 10^6 multiply and add steps.

Properties

  • Exact. All three searches of the code (brute force, the scan with early exit and the k-d tree) return the same frame.
  • Deterministic. The same state and input give the same frame, also on ties.
  • Online. Each search uses only the current state and the current input.
  • Data driven. The character can only play motion that is in the database; there is no new pose except inside a blend.

Variants and improvements

  • Inertialization. Instead of a cross fade between the old and the new clip, many engines add an offset that starts at the pose difference and decays to zero, so that only one clip is evaluated.
  • Learned motion matching. Holden and coworkers (2020) replace the stored features, the search and the pose lookup by three small neural networks, so that the memory no longer grows with the database. In their open source code the features have 27 dimensions: the two foot positions and velocities (12), the hip velocity (3), and the trajectory positions and directions at 20, 40 and 60 frames ahead (6 and 6, in 2D); the mean is taken per dimension and one standard deviation is shared by each group.
  • Tags and costs. Add a cost for a jump, for a change of tag (walk, run), or for frames that the designers want to avoid.
  • Faster search. Use bounding boxes over runs of frames, clusters, or a smaller set of key frames; quantize the vectors.
  • Contact cleanup. After the jump and the blend, plant the feet with two-bone inverse kinematics or footskate cleanup.
  • Motion graphs. A motion graph precomputes a few good transitions; motion matching allows a jump from any frame to any frame and decides at run time.

When to use it

Use motion matching for a player character in a game that must answer the input within a few frames and that has a large, well covered motion capture database. It reduces the hand work of blend trees and state machines. It needs much data, and it can only play what was captured; for a character that must react to forces, a physics controller such as SIMBICON or a learned policy such as DeepMimic fits better.

Pitfalls

  • Unnormalized features. Positions in meters, velocities in meters per second and unit directions have different scales. Without the normalization, one group decides every search.
  • Gaps in the data. If no frame of the database matches the input, the nearest frame can still be far. Plan the capture so that it covers the turns, stops and speeds that the game asks for.
  • Too frequent jumps. Searching every frame without a cost for a jump can make the character jitter between near equal frames. A search interval of a few frames, a small bonus for the current clip, or both, help.
  • Clip ends. A frame near the end of a clip can be chosen and then run out before the next search. Leave the last frames out of the playable set.
  • The name. "Learned motion matching" is a later, different method; do not confuse it with the plain search.

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.

motion_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-matching/. The authors are listed in prov/GYSR9F.jsonl.
"""Motion matching: play the database frame whose features best match the
current pose and the desired future trajectory.

The database has f frames. Each frame has a feature vector of d numbers,
split into named groups (for example foot positions, foot velocities, hip
velocity, future trajectory positions and directions). Every dimension is
normalized by its mean and standard deviation over the database, and each
group is multiplied by a weight (a tuning). The cost of a frame is the
squared Euclidean distance between its normalized feature vector and the
query.

Three exact searches return the same frame, with ties broken by the lower
frame number:
  * search_brute: a plain linear scan, O(f d);
  * search_scan: a linear scan that stops a sum once it passes the best cost;
  * KdTree.search: a k-d tree over the normalized features.

run() is the runtime loop: every `interval` frames, or when the input
changes, it builds a query from the current frame and the desired
trajectory, searches, and jumps if the best frame is not the frame that
would play next anyway.
"""

import math


class Database:
    def __init__(self, features, groups, weights, playable=None):
        """features: list of f vectors; groups: list of (name, start, stop);
        weights: dict name -> weight; playable: frames a search may return."""
        self.raw = [list(v) for v in features]
        self.f = len(features)
        self.d = len(features[0])
        self.groups = groups
        self.weights = weights
        self.mean = [sum(v[k] for v in features) / self.f for k in range(self.d)]
        self.std = []
        for k in range(self.d):
            var = sum((v[k] - self.mean[k]) ** 2 for v in features) / self.f
            self.std.append(math.sqrt(var) if var > 0.0 else 1.0)
        self.scale = [1.0] * self.d
        for name, a, b in groups:
            for k in range(a, b):
                self.scale[k] = weights[name] / self.std[k]
        self.X = [self.normalize(v) for v in features]
        self.playable = list(range(self.f)) if playable is None else list(playable)

    def normalize(self, v):
        return [(v[k] - self.mean[k]) * self.scale[k] for k in range(self.d)]  # @line L1


def cost(x, y):
    return sum((a - b) * (a - b) for a, b in zip(x, y))


def search_brute(db, query):
    q = db.normalize(query)
    return min(db.playable, key=lambda i: (cost(db.X[i], q), i))


def search_scan(db, query):
    q = db.normalize(query)
    best, best_i = math.inf, -1
    for i in db.playable:  # @line L2
        x = db.X[i]
        s = 0.0
        for k in range(db.d):  # @line L3
            t = x[k] - q[k]
            s += t * t
            if s > best:  # @line L4
                break
        if s < best:  # @line L5
            best, best_i = s, i
    return best_i  # @line L6


class KdTree:
    """A k-d tree over the normalized features of the playable frames."""

    def __init__(self, db, leaf=4):
        self.db = db
        self.leaf = leaf
        self.root = self._build(list(db.playable))

    def _build(self, idx):
        if len(idx) <= self.leaf:
            return ("leaf", idx)
        X = self.db.X
        d = self.db.d
        spread = [max(X[i][k] for i in idx) - min(X[i][k] for i in idx) for k in range(d)]
        k = max(range(d), key=lambda c: spread[c])
        if spread[k] == 0.0:
            return ("leaf", idx)
        idx.sort(key=lambda i: X[i][k])
        m = len(idx) // 2
        split = X[idx[m]][k]
        left = [i for i in idx if X[i][k] < split]
        right = [i for i in idx if X[i][k] >= split]
        if not left or not right:
            return ("leaf", idx)
        return ("node", k, split, self._build(left), self._build(right))

    def search(self, query):
        q = self.db.normalize(query)
        best = [math.inf, -1]
        self._search(self.root, q, best)
        return best[1]

    def _search(self, node, q, best):
        if node[0] == "leaf":
            for i in node[1]:
                c = cost(self.db.X[i], q)
                if c < best[0] or (c == best[0] and i < best[1]):
                    best[0], best[1] = c, i
            return
        _, k, split, left, right = node
        near, far = (left, right) if q[k] < split else (right, left)
        self._search(near, q, best)
        gap = q[k] - split
        if gap * gap <= best[0]:
            self._search(far, q, best)


def run(db, query_of, ticks, interval, start=0, search=None, next_frame=None):
    """Play `ticks` frames. query_of(t, frame) returns the query vector.

    next_frame(i) is the frame that plays after i without a jump (default
    i + 1). Return the list of played frames and the list of jumps.
    """
    if search is None:
        search = search_scan
    if next_frame is None:
        next_frame = lambda i: i + 1
    frame = start
    played, jumps = [frame], []
    for t in range(1, ticks):
        frame = next_frame(frame)
        if t % interval == 0:
            q = query_of(t, frame)
            best = search(db, q)
            if best != frame:
                jumps.append((t, frame, best))
                frame = best
        played.append(frame)
    return played, jumps
test_motion_matching.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/motion-matching/. The authors are listed in prov/GYSR9F.jsonl.
"""Tests of motion matching.

The scan with early exit and the k-d tree must return the same frame as a
brute force nearest neighbor search, ties included. The normalization gives
every dimension zero mean and the weight as its standard deviation. The run
loop jumps only to the nearest frame, and does not jump when the next frame
is already the best. The database is made in code with a fixed seed.
"""

import math
import random

import motion_matching as mm

GROUPS = [("foot_pos", 0, 4), ("foot_vel", 4, 8), ("hip_vel", 8, 10),
          ("traj_pos", 10, 16), ("traj_dir", 16, 22)]
WEIGHTS = {"foot_pos": 0.75, "foot_vel": 1.0, "hip_vel": 1.0, "traj_pos": 1.0, "traj_dir": 1.5}


def clip(n, speed, turn, phase, rng):
    """Feature vectors of a 2D walk with constant speed and turn rate."""
    out = []
    for i in range(n):
        t = i / 30.0
        ph = 2.0 * math.pi * 1.1 * t + phase
        lf = (0.15 + 0.2 * math.sin(ph), 0.1)
        rf = (0.15 - 0.2 * math.sin(ph), -0.1)
        lv = (0.2 * 2 * math.pi * 1.1 * math.cos(ph), 0.0)
        rv = (-lv[0], 0.0)
        hip = (speed, 0.02 * math.sin(2 * ph))
        traj, dirs = [], []
        for k in (20, 40, 60):
            a = turn * k / 30.0
            if abs(turn) > 1e-9:
                r = speed / turn
                traj += [r * math.sin(a), r * (1 - math.cos(a))]
            else:
                traj += [speed * k / 30.0, 0.0]
            dirs += [math.cos(a), math.sin(a)]
        v = list(lf + rf + lv + rv + hip) + traj + dirs
        out.append([x + rng.gauss(0.0, 0.01) for x in v])
    return out


def database(seed=1):
    rng = random.Random(seed)
    feats = []
    for speed, turn, phase in ((1.2, 0.0, 0.0), (1.2, 0.6, 1.0), (1.2, -0.6, 2.0),
                               (2.5, 0.0, 0.5), (0.0, 0.0, 0.0)):
        feats += clip(60, speed, turn, phase, rng)
    # an exact duplicate row to test ties
    feats.append(list(feats[10]))
    return mm.Database(feats, GROUPS, WEIGHTS)


def test_normalization():
    db = database()
    for k in range(db.d):
        col = [x[k] for x in db.X]
        m = sum(col) / db.f
        s = math.sqrt(sum((c - m) ** 2 for c in col) / db.f)
        assert abs(m) < 1e-9
        name = next(n for n, a, b in GROUPS if a <= k < b)
        if db.std[k] != 1.0:
            assert abs(s - WEIGHTS[name]) < 1e-9


def test_searches_equal_brute_force():
    db = database()
    tree = mm.KdTree(db)
    rng = random.Random(9)
    queries = [list(db.raw[rng.randrange(db.f)]) for _ in range(50)]
    queries += [[x + rng.gauss(0.0, 0.3) for x in db.raw[rng.randrange(db.f)]] for _ in range(150)]
    queries += [[rng.gauss(0.0, 2.0) for _ in range(db.d)] for _ in range(50)]
    queries.append(list(db.raw[10]))  # tie between frame 10 and the duplicate
    for q in queries:
        b = mm.search_brute(db, q)
        assert mm.search_scan(db, q) == b
        assert tree.search(q) == b
    assert mm.search_brute(db, db.raw[10]) == 10


def test_playable_frames_only():
    db = database()
    db.playable = [i for i in range(db.f) if i % 60 < 40]
    tree = mm.KdTree(db)
    rng = random.Random(4)
    for _ in range(60):
        q = [x + rng.gauss(0.0, 0.2) for x in db.raw[rng.randrange(db.f)]]
        b = mm.search_brute(db, q)
        assert b in db.playable
        assert mm.search_scan(db, q) == b == tree.search(q)


def test_run_jumps_to_nearest_and_stays_when_best():
    db = database()
    db.playable = [i for i in range(db.f - 1) if i % 60 < 55]
    # the input asks for the features of the turning clip, frame 70 onward
    target = lambda t, frame: db.raw[70 + t]
    played, jumps = mm.run(db, target, 40, 10, start=0)
    assert jumps, "the first search must leave the straight clip"
    t0, _, to = jumps[0]
    assert to == mm.search_brute(db, target(t0, None))
    # when the query is the next frame itself, no jump happens
    played, jumps = mm.run(db, lambda t, frame: db.raw[frame], 40, 5, start=120)
    assert jumps == []
    assert played == list(range(120, 160))

History

Simon Clavet presented motion matching at GDC 2016 as the animation system of the game For Honor. It grew out of a 2015 talk by Michael Büttner and Simon Clavet at the nucl.ai conference. The idea of jumping between similar frames of motion capture data is older: motion graphs (2002) precompute such jumps. In 2020, Daniel Holden, Oussama Kanoun, Maksym Perepichka and Tiberiu Popa published learned motion matching, which keeps the same behavior and replaces the database search by neural networks.

References

  1. Simon Clavet, Motion matching and the road to next-gen animation, Game Developers Conference, 2016, the talk as a whole: the search over the database for the best pose and trajectory match, and the blend to the found frame
  2. Daniel Holden, Oussama Kanoun, Maksym Perepichka and Tiberiu Popa, Learned motion matching, ACM Transactions on Graphics 39(4) (SIGGRAPH 2020), the description of basic motion matching, its feature vector and its normalization, before the learned variant
  3. Lucas Kovar, Michael Gleicher and Frederic Pighin, Motion graphs, ACM Transactions on Graphics 21(3) (SIGGRAPH 2002), 473 to 482, the precomputed transitions that motion matching replaces by a search at run time

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.normalize_database
  • a full proof of time.query
  • a full proof of time.search
  • a full proof of space.database
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
  • a scene preset for the example