Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an NPC path follower that walks a navmesh route through the animation graph (#774)

Nguyen Xuan Anc9e6c61c56ac
diff --git a/bench/animation-graph/main.js b/bench/animation-graph/main.js
index ff560dfc..f801e0f1 100644
--- a/bench/animation-graph/main.js
+++ b/bench/animation-graph/main.js
@@ -4,17 +4,12 @@
// Open bench/animation-graph/index.html with `npm run dev`. W or the up arrow walks, Shift runs; ?speed=3.5 pins the speed
// and ?demo=1 ramps it up and down on its own.
import { Renderer67 } from '/src/index.js';
-import { parseGltf } from '/src/gltf.js';
-import { clipFromGltfAnimation, createAssetPose } from '/src/skeleton-pose.js';
-import { createAnimationClip } from '/src/animation.js';
-import { createAnimationGraph } from '/src/animation-graph.js';
+import { createAssetPose } from '/src/skeleton-pose.js';
+import { createLocomotionGraph, loadRobot, RUN_SPEED, WALK_SPEED } from './robot-graph.js';
import { createCharacterController } from '/src/player.js';
import { createInput, keyboardSource } from '/src/input.js';
import { createRuntime } from '/src/runtime.js';
-const ROBOT_URL = '/tests/fixtures/RobotExpressive.glb';
-const WALK_SPEED = 2.2;
-const RUN_SPEED = 5.5;
const ACCELERATION = 6; // Speed units per second squared.
const DEMO_PERIOD_SECONDS = 8;
const FIXED_RATE = 60;
@@ -23,46 +18,8 @@ const query = new URLSearchParams(location.search);
const pinnedSpeed = query.has('speed') ? Number(query.get('speed')) : null;
const demo = query.get('demo') === '1';
-const response = await fetch(ROBOT_URL);
-const asset = await parseGltf(await response.arrayBuffer(), { maxVertices: 500000 });
-const ROOT_BONE = 'RobotArmature';
-
-// The CC0 clips play in place. Give a stride clip a root travel track of `metersPerSecond` so the graph has root motion to extract.
-function withRootTravel(clip, metersPerSecond) {
- const travel = {
- target: ROOT_BONE,
- property: 'translation',
- keyframes: [{ time: 0, value: [0, 0, 0] }, { time: clip.duration, value: [0, 0, metersPerSecond * clip.duration] }],
- };
- return createAnimationClip({ duration: clip.duration, loop: clip.loop, tracks: [...clip.tracks, travel] });
-}
-
-const clips = {};
-for (const [name, pace] of [['Idle', 0], ['Walking', WALK_SPEED], ['Running', RUN_SPEED]]) {
- const source = asset.animations.find(animation => animation.name === name);
- const clip = clipFromGltfAnimation(source, { loop: true });
- clips[name] = pace > 0 ? withRootTravel(clip, pace) : clip;
-}
-
-const graph = createAnimationGraph({
- rootMotion: { bone: ROOT_BONE },
- clips,
- parameters: { speed: { type: 'number' } },
- layers: [{
- name: 'locomotion',
- states: [{
- name: 'move',
- blend: {
- parameter: 'speed',
- motions: [
- { clip: 'Idle', threshold: 0 },
- { clip: 'Walking', threshold: WALK_SPEED },
- { clip: 'Running', threshold: RUN_SPEED },
- ],
- },
- }],
- }],
-});
+const asset = await loadRobot();
+const graph = createLocomotionGraph(asset);
const pose = createAssetPose(asset, { layers: graph.poseLayers() });
const input = createInput({
diff --git a/bench/animation-graph/npc.html b/bench/animation-graph/npc.html
new file mode 100644
index 00000000..1a50a4e1
--- /dev/null
+++ b/bench/animation-graph/npc.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>NPC path sample</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #14161a; color: #e8eaed; font: 14px/1.4 system-ui, sans-serif; }
+ canvas { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; }
+ .panel { position: fixed; top: 16px; left: 16px; padding: 12px 14px; border-radius: 10px; background: rgba(20, 22, 26, 0.82); }
+ output { display: block; font-variant-numeric: tabular-nums; white-space: pre; }
+</style>
+</head>
+<body>
+<canvas></canvas>
+<div class="panel"><output id="readout"></output></div>
+<script type="module" src="./npc.js"></script>
+</body>
+</html>
diff --git a/bench/animation-graph/npc.js b/bench/animation-graph/npc.js
new file mode 100644
index 00000000..46b1a4e1
--- /dev/null
+++ b/bench/animation-graph/npc.js
@@ -0,0 +1,165 @@
+// Sample for src/npc-follower.js: the CC0 RobotExpressive walks a navmesh route around a wall through the animation graph.
+// The follower steers along the route, writes its speed to the graph, and moves by the graph's root motion.
+// Open bench/animation-graph/npc.html with `npm run dev`. The walk is simulated once at load (it is deterministic), then replayed;
+// the readout gives the time to reach the goal and the largest foot slide measured on the planted feet.
+import { Renderer67, box } from '/src/index.js';
+import { createAssetPose } from '/src/skeleton-pose.js';
+import { createAnimationClip } from '/src/animation.js';
+import { createPathFollower } from '/src/animation-graph.js';
+import { createNavmesh } from '/src/navmesh.js';
+import { createTerrain } from '/src/terrain.js';
+import { createRuntime } from '/src/runtime.js';
+import { createLocomotionGraph, loadRobot, ROOT_BONE, WALK_SPEED } from './robot-graph.js';
+
+const STEP = 1 / 60;
+const FIXED_RATE = 60;
+const START = [-16, 0];
+const GOAL = [16, 0];
+const WALL = { min: [-1.5, -12], max: [1.5, 6] };
+const MAXIMUM_SECONDS = 60;
+const HOLD_SECONDS = 2;
+const KEYFRAME_EVERY = 2; // Steps between keyframes of the trajectory clip.
+const PLANTED_HEIGHT = 0.05; // Above the lowest the foot reaches, in the robot's units.
+const FEET = ['FootL', 'FootR'];
+const FACING_OFFSET = Math.PI; // The follower faces -Z at yaw 0, a glTF robot faces +Z.
+
+const asset = await loadRobot();
+const ground = createTerrain({ size: 48, chunks: 1, levels: 1, resolution: 64, height: () => 0 }).parts[0].geometry;
+const navmesh = createNavmesh({ positions: ground.positions, indices: ground.indices, agentRadius: 1.2, cellSize: 0.5, obstacles: [WALL] });
+
+// Pass 1: the follower and the graph walk the route; record what the pose needs for every step.
+function simulate() {
+ const graph = createLocomotionGraph(asset);
+ const follower = createPathFollower({ graph, navmesh, position: [START[0], 0, START[1]], yaw: Math.PI / 2, cruiseSpeed: WALK_SPEED });
+ follower.goTo(GOAL);
+ const steps = [];
+ let largestMoveError = 0;
+ let previousRootDistance = 0;
+ while (follower.state.status === 'moving' && steps.length < MAXIMUM_SECONDS * FIXED_RATE) {
+ follower.step(STEP);
+ largestMoveError = Math.max(largestMoveError, Math.abs(follower.state.lastMove - previousRootDistance));
+ steps.push({ position: [...follower.state.position], yaw: follower.state.yaw, speed: follower.state.speed });
+ graph.advance(STEP);
+ previousRootDistance = graph.rootMotion.distance;
+ }
+ return { steps, reachedGoal: follower.state.status === 'arrived', largestMoveError };
+}
+
+// The trajectory as a clip on the armature node, so the pose puts the robot where the follower walked it.
+function trajectoryClip(steps) {
+ const translation = [];
+ const rotation = [];
+ for (let index = 0; index < steps.length; index += KEYFRAME_EVERY) {
+ const { position, yaw } = steps[index];
+ const half = (FACING_OFFSET - yaw) / 2;
+ translation.push({ time: index * STEP, value: [...position] });
+ rotation.push({ time: index * STEP, value: [0, Math.sin(half), 0, Math.cos(half)] });
+ }
+ const duration = (steps.length - 1) * STEP;
+ const last = steps.length - 1;
+ if ((last % KEYFRAME_EVERY) !== 0) {
+ const half = (FACING_OFFSET - steps[last].yaw) / 2;
+ translation.push({ time: duration, value: [...steps[last].position] });
+ rotation.push({ time: duration, value: [0, Math.sin(half), 0, Math.cos(half)] });
+ }
+ return createAnimationClip({
+ duration,
+ loop: false,
+ tracks: [
+ { target: ROOT_BONE, property: 'translation', keyframes: translation },
+ { target: ROOT_BONE, property: 'rotation', keyframes: rotation },
+ ],
+ });
+}
+
+const recording = simulate();
+const duration = (recording.steps.length - 1) * STEP;
+const graph = createLocomotionGraph(asset);
+const pose = createAssetPose(asset, { layers: [...graph.poseLayers(), { clip: trajectoryClip(recording.steps), weight: () => 1, clipTime: () => Math.min(graph.time, duration) }] });
+
+function speedAt(time) {
+ const index = Math.min(Math.round(time / STEP), recording.steps.length - 1);
+ return time > duration ? 0 : recording.steps[index].speed;
+}
+
+// Pass 2: replay once and measure the planted feet in world space. A foot is planted when it is within PLANTED_HEIGHT of its lowest point.
+function measureFootSlide() {
+ const paths = FEET.map(() => []);
+ for (let index = 0; index < recording.steps.length; index++) {
+ graph.set('speed', recording.steps[index].speed);
+ graph.advance(STEP);
+ pose.apply(graph.time);
+ FEET.forEach((name, foot) => paths[foot].push([...pose.jointWorld(name).position]));
+ }
+ let largest = 0;
+ let total = 0;
+ let count = 0;
+ paths.forEach(path => {
+ const lowest = Math.min(...path.map(point => point[1]));
+ for (let index = 1; index < path.length; index++) {
+ const planted = path[index][1] <= lowest + PLANTED_HEIGHT && path[index - 1][1] <= lowest + PLANTED_HEIGHT;
+ if (!planted) continue;
+ const slide = Math.hypot(path[index][0] - path[index - 1][0], path[index][2] - path[index - 1][2]) / STEP;
+ largest = Math.max(largest, slide);
+ total += slide;
+ count += 1;
+ }
+ });
+ graph.reset();
+ return { largest, mean: count ? total / count : 0, samples: count };
+}
+
+const footSlide = measureFootSlide();
+const stats = {
+ reachedGoal: recording.reachedGoal,
+ goalReachSeconds: duration,
+ largestRootMotionVsMoveError: recording.largestMoveError,
+ largestFootSlideUnitsPerSecond: footSlide.largest,
+ meanFootSlideUnitsPerSecond: footSlide.mean,
+ plantedSamples: footSlide.samples,
+};
+
+const material = { color: [0.55, 0.57, 0.62], metallic: 0, roughness: 0.7 };
+function placed(center, size) {
+ return new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);
+}
+const scenery = [
+ { geometry: box(), matrix: placed([0, 3, (WALL.min[1] + WALL.max[1]) / 2], [WALL.max[0] - WALL.min[0], 6, WALL.max[1] - WALL.min[1]]), material },
+ { geometry: box(0), matrix: placed([GOAL[0], 0.03, GOAL[1]], [2.4, 0.06, 2.4]), material: { color: [0.2, 0.75, 0.4], metallic: 0, roughness: 0.6 } },
+];
+const parts = [...asset.parts, ...scenery];
+
+const canvas = document.querySelector('canvas');
+const renderer = new Renderer67(canvas, parts, { ground: true, hdr: false, samples: 4, memoryBudgetMiB: 512 });
+renderer.resize();
+
+const replay = {
+ name: 'replay',
+ fixedUpdate() {
+ if (graph.time > duration + HOLD_SECONDS) graph.reset();
+ graph.set('speed', speedAt(graph.time));
+ },
+};
+
+const runtime = createRuntime(renderer, {
+ mode: 'fixed',
+ fixedRate: FIXED_RATE,
+ frame(context) {
+ pose.apply(graph.time);
+ renderer.updateParts(parts);
+ return { eye: [0, 30, 32], target: [0, 0, 0], up: [0, 1, 0], fov: 40, near: 0.1, far: 200, time: context.elapsedSeconds };
+ },
+ systems: [replay, graph.system()],
+});
+runtime.start();
+window.npcSample = { graph, runtime, stats };
+
+const readout = document.querySelector('#readout');
+setInterval(() => {
+ readout.textContent = [
+ `speed ${speedAt(graph.time).toFixed(2)}`,
+ `goal reached in ${stats.goalReachSeconds.toFixed(1)} s`,
+ `foot slide max ${stats.largestFootSlideUnitsPerSecond.toFixed(2)} mean ${stats.meanFootSlideUnitsPerSecond.toFixed(3)} units/s`,
+ `root motion vs moved ${stats.largestRootMotionVsMoveError.toExponential(1)} m`,
+ ].join('\n');
+}, 100);
diff --git a/bench/animation-graph/robot-graph.js b/bench/animation-graph/robot-graph.js
new file mode 100644
index 00000000..fee7e491
--- /dev/null
+++ b/bench/animation-graph/robot-graph.js
@@ -0,0 +1,55 @@
+// The CC0 RobotExpressive and its locomotion graph, shared by the two samples (main.js and npc.js).
+// The Walking and Running clips are in place, so a root travel track at the pace of the stride is added to the armature node:
+// the graph takes it out again and the body moves by it, so the feet do not slide.
+import { parseGltf } from '/src/gltf.js';
+import { clipFromGltfAnimation } from '/src/skeleton-pose.js';
+import { createAnimationClip } from '/src/animation.js';
+import { createAnimationGraph } from '/src/animation-graph.js';
+
+export const ROBOT_URL = '/tests/fixtures/RobotExpressive.glb';
+export const ROOT_BONE = 'RobotArmature';
+export const WALK_SPEED = 2.2;
+export const RUN_SPEED = 5.5;
+
+function withRootTravel(clip, metersPerSecond) {
+ const travel = {
+ target: ROOT_BONE,
+ property: 'translation',
+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: clip.duration, value: [0, 0, metersPerSecond * clip.duration] }],
+ };
+ return createAnimationClip({ duration: clip.duration, loop: clip.loop, tracks: [...clip.tracks, travel] });
+}
+
+export async function loadRobot() {
+ const response = await fetch(ROBOT_URL);
+ return parseGltf(await response.arrayBuffer(), { maxVertices: 500000 });
+}
+
+// Idle, Walking and Running blended by the `speed` parameter, with root motion on.
+export function createLocomotionGraph(asset) {
+ const clips = {};
+ for (const [name, pace] of [['Idle', 0], ['Walking', WALK_SPEED], ['Running', RUN_SPEED]]) {
+ const source = asset.animations.find(animation => animation.name === name);
+ const clip = clipFromGltfAnimation(source, { loop: true });
+ clips[name] = pace > 0 ? withRootTravel(clip, pace) : clip;
+ }
+ return createAnimationGraph({
+ rootMotion: { bone: ROOT_BONE },
+ clips,
+ parameters: { speed: { type: 'number' } },
+ layers: [{
+ name: 'locomotion',
+ states: [{
+ name: 'move',
+ blend: {
+ parameter: 'speed',
+ motions: [
+ { clip: 'Idle', threshold: 0 },
+ { clip: 'Walking', threshold: WALK_SPEED },
+ { clip: 'Running', threshold: RUN_SPEED },
+ ],
+ },
+ }],
+ }],
+ });
+}
diff --git a/changes/774-npc.md b/changes/774-npc.md
new file mode 100644
index 00000000..83635779
--- /dev/null
+++ b/changes/774-npc.md
@@ -0,0 +1 @@
+- `createPathFollower` walks an NPC along a navmesh route through the animation graph, blending idle, walk and run by speed and moving by root motion (#774)
diff --git a/changes/774-npc.size.md b/changes/774-npc.size.md
new file mode 100644
index 00000000..5703641d
--- /dev/null
+++ b/changes/774-npc.size.md
@@ -0,0 +1 @@
+- entry:animation-graph: the path follower (1758 bytes gzip) is what lets an NPC walk a navmesh route through the graph with root motion; it is only in the animation-graph entry, no other bundle carries it.
diff --git a/docs/animation-graph.md b/docs/animation-graph.md
index ec650dbc..e94dd2b4 100644
--- a/docs/animation-graph.md
+++ b/docs/animation-graph.md
@@ -159,9 +159,22 @@ const pose = createAssetPose(character, {
The graph knows no rig, so a creature or a machine runs the same way. The tests drive a quadruped (root, body, neck, head and four legs) and the car from the repo's test assets (wheels spinning while the body travels) through the same graph, root motion and IK hooks.
+## NPC path follower
+
+`createPathFollower({ graph, navmesh, position, yaw, cruiseSpeed })` walks an NPC along a path through the same graph. It writes its speed to the `speed` parameter, so idle, walk and run blend, and it moves by `graph.rootMotion`, so the feet do not slide. The graph needs the `rootMotion` option.
+
+```js
+const follower = createPathFollower({ graph, navmesh, position: [-16, 0, 0], yaw: Math.PI / 2, cruiseSpeed: 2.2 });
+follower.goTo([16, 0]); // a navmesh route; follower.follow(points) takes any list of [x, z] or [x, y, z]
+// systems: [follower.system(), graph.system()]; follower.state has position, yaw, speed and status
+```
+
+Each step it moves by the root motion of the last graph step, turned by its yaw as the [player](player.md) does, then steers to the next waypoint at `turnRate` and picks the speed for the next step: `cruiseSpeed` on a straight, lower toward a sharp corner (`cornerSlowDistance`), and in proportion to the distance inside `slowRadius` of the goal, never below `minimumSpeed`. A large heading error cuts the speed, so a sharp turn happens nearly in place. A corner counts as reached within `cornerRadius` or once passed, so the NPC rounds it on the outside. With a `navmesh`, a step into unwalkable ground slides along its edge (counted in `state.blockedSteps`). `status` becomes `"arrived"` within `arrivalRadius` of the last point and the parameter drops to 0; `stop()` returns to idle. `state.yaw` follows the player convention (0 faces -Z), so a glTF model needs `yaw + PI` about Y.
+
+At most 256 waypoints and speeds up to 100. Errors name the option or point and what to pass. `bench/animation-graph/npc.html` shows the RobotExpressive walking a route around a wall.
+
## Limits and errors
At most 64 parameters, 8 layers, 64 states and 256 transitions per layer, 8 conditions per transition, 16 motions per blend space and 4 states fading out at once. Errors name the field and the fix, for example `createAnimationGraph layers[0].transitions[1].to names "run", which is not a state of this layer. States: idle, move.`
-Path-driven NPC speed is not a separate feature: an NPC sets `speed` from its path follower, such as the navmesh, through the same `graph.set`.
diff --git a/src/animation-graph.js b/src/animation-graph.js
index e20efd24..86fba2e0 100644
--- a/src/animation-graph.js
+++ b/src/animation-graph.js
@@ -7,6 +7,7 @@ import { extractRootMotion, normalizeRootMotionSettings } from './animation-root
export { createFootPlacement, createLookAt } from './animation-ik.js';
export { extractRootMotion } from './animation-root-motion.js';
+export { createPathFollower, NPC_FOLLOWER_LIMITS } from './npc-follower.js';
export const ANIMATION_GRAPH_LIMITS = Object.freeze({
maximumFadingStates: 4,
diff --git a/src/npc-follower.js b/src/npc-follower.js
new file mode 100644
index 00000000..4fcfd5e9
--- /dev/null
+++ b/src/npc-follower.js
@@ -0,0 +1,258 @@
+// An NPC that walks a path through an animation graph: it steers along waypoints (a navmesh route or any list of points), eases its
+// speed for corners and the arrival, writes that speed to a graph parameter so idle, walk and run blend, and moves by the graph's
+// root motion so the feet do not slide. Pure arithmetic, no clock and no random source: the same steps give the same walk.
+
+export const NPC_FOLLOWER_LIMITS = Object.freeze({ maximumWaypoints: 256, maximumSpeed: 100 });
+
+const DEFAULTS = Object.freeze({
+ parameter: 'speed',
+ cruiseSpeed: 2.2,
+ acceleration: 6,
+ turnRate: 6,
+ arrivalRadius: 0.1,
+ slowRadius: 1,
+ cornerRadius: 0.2,
+ cornerSlowDistance: 1.5,
+ minimumSpeed: 0.3,
+});
+const BLOCKED_PROBE_EPSILON = 1e-9;
+
+function describe(value) {
+ if (typeof value === 'string') return JSON.stringify(value);
+ if (Array.isArray(value)) return `an array of ${value.length}`;
+ return value === null ? 'null' : typeof value === 'object' ? 'an object' : String(value);
+}
+
+function positive(value, fallback, label, maximum = Infinity) {
+ const resolved = value ?? fallback;
+ if (!Number.isFinite(resolved) || resolved <= 0 || resolved > maximum) {
+ throw new RangeError(`createPathFollower ${label} must be a number above 0${maximum < Infinity ? ` and at most ${maximum}` : ''}, got ${describe(value)}.`);
+ }
+ return resolved;
+}
+
+function readPoint(value, index) {
+ const valid = Array.isArray(value) && (value.length === 2 || value.length === 3) && value.every(Number.isFinite);
+ if (!valid) throw new TypeError(`follower path point ${index} must be [x, z] or [x, y, z] in metres, got ${describe(value)}.`);
+ return value.length === 2 ? [value[0], null, value[1]] : [value[0], value[1], value[2]];
+}
+
+function readPath(path) {
+ const points = Array.isArray(path) ? path : path?.points;
+ if (!Array.isArray(points) || points.length < 1 || points.length > NPC_FOLLOWER_LIMITS.maximumWaypoints) {
+ throw new RangeError(`follower.follow needs a list of 1 to ${NPC_FOLLOWER_LIMITS.maximumWaypoints} points, or the { points } of navmesh.findPath, got ${describe(path)}.`);
+ }
+ return points.map(readPoint);
+}
+
+function wrapAngle(angle) {
+ return Math.atan2(Math.sin(angle), Math.cos(angle));
+}
+
+function clamp(value, minimum, maximum) {
+ return Math.min(Math.max(value, minimum), maximum);
+}
+
+/**
+ * Options: `graph` (an animation graph made with the `rootMotion` option), `parameter` ('speed', a number parameter of the graph),
+ * `position` ([x, y, z]), `yaw` (radians, the player's convention: 0 faces -Z), `cruiseSpeed` (in parameter units, 2.2),
+ * `acceleration` (6 per second), `turnRate` (6 rad/s), `arrivalRadius` (0.1 m), `slowRadius` (1 m, where it eases in to the goal),
+ * `cornerRadius` (0.2 m, how close a corner counts as reached), `cornerSlowDistance` (1.5 m), `minimumSpeed` (0.3), `navmesh`
+ * (keeps the NPC on walkable ground, gives its height and enables `goTo`).
+ */
+export function createPathFollower(options = {}) {
+ const { graph, navmesh } = options;
+ if (!graph || typeof graph.set !== 'function' || !('rootMotion' in graph)) {
+ throw new TypeError('createPathFollower graph must be an animation graph from createAnimationGraph, such as createPathFollower({ graph, position: [0, 0, 0] }).');
+ }
+ const position = options.position ?? [0, 0, 0];
+ if (!Array.isArray(position) || position.length !== 3 || !position.every(Number.isFinite)) {
+ throw new TypeError(`createPathFollower position must be [x, y, z] in metres, got ${describe(position)}.`);
+ }
+ if (options.yaw !== undefined && !Number.isFinite(options.yaw)) throw new TypeError(`createPathFollower yaw must be a number in radians, got ${describe(options.yaw)}.`);
+ if (navmesh !== undefined && (typeof navmesh?.isWalkable !== 'function' || typeof navmesh.findPath !== 'function')) {
+ throw new TypeError('createPathFollower navmesh must come from createNavmesh (it needs isWalkable, heightAt and findPath).');
+ }
+ const settings = {
+ parameter: options.parameter ?? DEFAULTS.parameter,
+ cruiseSpeed: positive(options.cruiseSpeed, DEFAULTS.cruiseSpeed, 'cruiseSpeed', NPC_FOLLOWER_LIMITS.maximumSpeed),
+ acceleration: positive(options.acceleration, DEFAULTS.acceleration, 'acceleration'),
+ turnRate: positive(options.turnRate, DEFAULTS.turnRate, 'turnRate'),
+ arrivalRadius: positive(options.arrivalRadius, DEFAULTS.arrivalRadius, 'arrivalRadius'),
+ slowRadius: positive(options.slowRadius, DEFAULTS.slowRadius, 'slowRadius'),
+ cornerRadius: positive(options.cornerRadius, DEFAULTS.cornerRadius, 'cornerRadius'),
+ cornerSlowDistance: positive(options.cornerSlowDistance, DEFAULTS.cornerSlowDistance, 'cornerSlowDistance'),
+ minimumSpeed: positive(options.minimumSpeed, DEFAULTS.minimumSpeed, 'minimumSpeed'),
+ };
+ if (settings.minimumSpeed > settings.cruiseSpeed) throw new RangeError('createPathFollower minimumSpeed must not exceed cruiseSpeed.');
+ graph.rootMotion; // Throws and says how to enable it when the graph has no rootMotion option.
+ graph.get(settings.parameter); // Throws with the parameter names when the graph has no such parameter.
+
+ const state = {
+ position: [...position],
+ yaw: options.yaw ?? 0,
+ speed: 0,
+ status: 'idle', // 'idle' | 'moving' | 'arrived'
+ waypointIndex: 0,
+ blockedSteps: 0,
+ lastMove: 0, // Metres moved in the last step.
+ };
+ let waypoints = [];
+
+ function groundHeight(x, z, fallback) {
+ return navmesh?.heightAt?.(x, z) ?? fallback;
+ }
+
+ function distanceTo(point) {
+ return Math.hypot(point[0] - state.position[0], point[2] - state.position[2]);
+ }
+
+ function turnAngleAt(index) {
+ if (index + 1 >= waypoints.length) return 0;
+ const before = waypoints[index - 1];
+ const here = waypoints[index];
+ const after = waypoints[index + 1];
+ const incoming = Math.atan2(here[0] - before[0], here[2] - before[2]);
+ const outgoing = Math.atan2(after[0] - here[0], after[2] - here[2]);
+ return Math.abs(wrapAngle(outgoing - incoming));
+ }
+
+ // Faster on the straight, slower toward a sharp corner, slowest into the goal.
+ function speedLimit(headingError) {
+ const index = state.waypointIndex;
+ const isLast = index === waypoints.length - 1;
+ let limit = settings.cruiseSpeed;
+ if (isLast) {
+ limit = Math.min(limit, settings.cruiseSpeed * distanceTo(waypoints[index]) / settings.slowRadius);
+ } else {
+ const sharpness = turnAngleAt(index) / Math.PI;
+ const cornerSpeed = settings.cruiseSpeed * (1 - sharpness);
+ const nearness = clamp(distanceTo(waypoints[index]) / settings.cornerSlowDistance, 0, 1);
+ limit = Math.min(limit, cornerSpeed + (settings.cruiseSpeed - cornerSpeed) * nearness);
+ }
+ limit = Math.max(limit, settings.minimumSpeed);
+ return limit * clamp(Math.cos(headingError), 0, 1);
+ }
+
+ function arrive() {
+ state.status = 'arrived';
+ state.speed = 0;
+ graph.set(settings.parameter, 0);
+ }
+
+ function hasPassed(index) {
+ const before = waypoints[index - 1];
+ const target = waypoints[index];
+ const alongX = target[0] - before[0];
+ const alongZ = target[2] - before[2];
+ return (target[0] - state.position[0]) * alongX + (target[2] - state.position[2]) * alongZ <= 0;
+ }
+
+ function advanceWaypoint() {
+ while (state.waypointIndex < waypoints.length) {
+ const target = waypoints[state.waypointIndex];
+ const isLast = state.waypointIndex === waypoints.length - 1;
+ if (isLast) {
+ if (distanceTo(target) > settings.arrivalRadius) return true;
+ arrive();
+ return false;
+ }
+ // A corner counts as reached when close enough or already passed, so the NPC rounds it on the outside and not through the obstacle.
+ if (distanceTo(target) > settings.cornerRadius && !hasPassed(state.waypointIndex)) return true;
+ state.waypointIndex += 1;
+ }
+ return false;
+ }
+
+ function steer(stepSeconds) {
+ const target = waypoints[state.waypointIndex];
+ const wantedYaw = Math.atan2(target[0] - state.position[0], -(target[2] - state.position[2]));
+ const headingError = wrapAngle(wantedYaw - state.yaw);
+ const turn = settings.turnRate * stepSeconds;
+ state.yaw = wrapAngle(state.yaw + clamp(headingError, -turn, turn));
+ const wantedSpeed = speedLimit(wrapAngle(wantedYaw - state.yaw));
+ const change = settings.acceleration * stepSeconds;
+ state.speed += clamp(wantedSpeed - state.speed, -change, change);
+ graph.set(settings.parameter, state.speed);
+ }
+
+ // The graph's travel of the last step (x right, negative z forward) turned into the world by the NPC's yaw, as the player does.
+ function moveByRootMotion() {
+ const travel = graph.rootMotion.delta;
+ const forwardX = Math.sin(state.yaw);
+ const forwardZ = -Math.cos(state.yaw);
+ const rightX = Math.cos(state.yaw);
+ const rightZ = Math.sin(state.yaw);
+ const moveX = rightX * travel[0] - forwardX * travel[1];
+ const moveZ = rightZ * travel[0] - forwardZ * travel[1];
+ const [currentX, currentY, currentZ] = state.position;
+ const attempts = [[moveX, moveZ], [moveX, 0], [0, moveZ]];
+ state.lastMove = 0;
+ for (const [attemptX, attemptZ] of attempts) {
+ const nextX = currentX + attemptX;
+ const nextZ = currentZ + attemptZ;
+ const walkable = navmesh ? navmesh.isWalkable(nextX, nextZ) : true;
+ if (!walkable || Math.hypot(attemptX, attemptZ) < BLOCKED_PROBE_EPSILON) continue;
+ state.position = [nextX, groundHeight(nextX, nextZ, currentY), nextZ];
+ state.lastMove = Math.hypot(attemptX, attemptZ);
+ if (attemptX !== moveX || attemptZ !== moveZ) state.blockedSteps += 1;
+ return;
+ }
+ if (Math.hypot(moveX, moveZ) >= BLOCKED_PROBE_EPSILON) state.blockedSteps += 1;
+ }
+
+ const follower = {
+ state,
+
+ // Starts walking a list of [x, z] or [x, y, z] points, or the result of navmesh.findPath. The first point is where it stands.
+ follow(path) {
+ // The route starts where the NPC stands, so every waypoint after it has a segment behind it.
+ const points = readPath(path).map(point => [point[0], point[1] ?? state.position[1], point[2]]);
+ waypoints = [[...state.position], ...points];
+ state.waypointIndex = 1;
+ state.status = 'moving';
+ state.blockedSteps = 0;
+ return follower;
+ },
+
+ // Finds a route over the navmesh to [x, z] and follows it.
+ goTo(goal) {
+ if (!navmesh) throw new TypeError('follower.goTo needs the navmesh option, such as createPathFollower({ graph, navmesh }). Use follower.follow(points) for any other path.');
+ const route = navmesh.findPath([state.position[0], state.position[2]], goal, { spacing: 1e6 });
+ return follower.follow(route);
+ },
+
+ // Stops at once: the speed parameter goes to 0 and the graph blends back to idle.
+ stop() {
+ waypoints = [];
+ state.status = 'idle';
+ state.speed = 0;
+ graph.set(settings.parameter, 0);
+ return follower;
+ },
+
+ // One step: move by the root motion of the last graph step, then pick the heading and the speed for the next one.
+ // Put it before graph.system() so the graph advances with the new speed.
+ step(stepSeconds) {
+ if (!Number.isFinite(stepSeconds) || stepSeconds <= 0) throw new RangeError(`follower.step stepSeconds must be a number above 0, got ${describe(stepSeconds)}.`);
+ state.lastMove = 0;
+ if (state.status !== 'moving') return follower;
+ moveByRootMotion();
+ if (advanceWaypoint()) steer(stepSeconds);
+ return follower;
+ },
+
+ system({ name = 'npc-follower' } = {}) {
+ return {
+ name,
+ fixedUpdate(stepSeconds) {
+ follower.step(stepSeconds);
+ },
+ update(deltaSeconds, context) {
+ if (context.mode === 'variable') follower.step(deltaSeconds);
+ },
+ };
+ },
+ };
+ return follower;
+}
diff --git a/tests/npc-follower.test.js b/tests/npc-follower.test.js
new file mode 100644
index 00000000..c4b5a137
--- /dev/null
+++ b/tests/npc-follower.test.js
@@ -0,0 +1,197 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAnimationClip } from '../src/animation.js';
+import { createAnimationGraph, createPathFollower, NPC_FOLLOWER_LIMITS } from '../src/animation-graph.js';
+import { createNavmesh } from '../src/navmesh.js';
+import { createTerrain } from '../src/terrain.js';
+
+const STEP = 1 / 60;
+const CRUISE = 2;
+const MAXIMUM_STEPS = 60 * 40;
+
+function flatGround(size) {
+ const terrain = createTerrain({ size, chunks: 1, levels: 1, resolution: 64, height: () => 0 });
+ const { positions, indices } = terrain.parts[0].geometry;
+ return { positions, indices };
+}
+
+// A 24 m square with a wall in the middle that the straight line from west to east would cross.
+function wallNavmesh() {
+ return createNavmesh({ ...flatGround(24), agentRadius: 0.4, obstacles: [{ min: [-1, -5], max: [1, 3] }] });
+}
+
+function stillClip(bone, duration) {
+ return createAnimationClip({ duration, loop: true, tracks: [{ target: bone, property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: duration, value: [0, 0, 0, 1] }] }] });
+}
+
+function travelClip(bone, metersPerSecond) {
+ return createAnimationClip({
+ duration: 1,
+ loop: true,
+ tracks: [{ target: bone, property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [0, 0, metersPerSecond] }] }],
+ });
+}
+
+// Idle and a walk that travels 2 m per second at parameter 2: the root travel is linear in the speed parameter.
+function humanGraph() {
+ return createAnimationGraph({
+ rootMotion: { bone: 'Root' },
+ clips: { idle: stillClip('Root', 1), walk: travelClip('Root', CRUISE) },
+ parameters: { speed: { type: 'number' } },
+ layers: [{ name: 'base', states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: CRUISE }] } }] }],
+ });
+}
+
+// The hand-built quadruped of tests/animation-root-motion.test.js: a trot that travels 2 m/s, with a leg swing.
+function quadrupedGraph() {
+ const gait = createAnimationClip({
+ duration: 0.8,
+ loop: true,
+ tracks: [
+ { target: 'Root', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 0.8, value: [0, 0, 1.6] }] },
+ { target: 'HipFL', property: 'rotation', keyframes: [{ time: 0, value: [-0.17, 0, 0, 0.98] }, { time: 0.4, value: [0.17, 0, 0, 0.98] }, { time: 0.8, value: [-0.17, 0, 0, 0.98] }] },
+ ],
+ });
+ return createAnimationGraph({
+ rootMotion: { bone: 'Root' },
+ clips: { stand: stillClip('Body', 0.8), trot: gait },
+ parameters: { speed: { type: 'number' } },
+ layers: [{ name: 'gait', states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'stand', threshold: 0 }, { clip: 'trot', threshold: 2 }] } }] }],
+ });
+}
+
+// Walks the route and records, per step, the NPC's speed parameter, the distance it moved and the root motion it was given.
+function walk(graph, navmesh, from, goal, options = {}) {
+ const follower = createPathFollower({ graph, navmesh, position: [from[0], 0, from[1]], cruiseSpeed: CRUISE, ...options });
+ follower.goTo(goal);
+ const route = navmesh.findPath(from, goal, { spacing: 1e6 }).points;
+ const samples = [];
+ let previousRootDistance = 0;
+ let steps = 0;
+ while (follower.state.status === 'moving' && steps < MAXIMUM_STEPS) {
+ follower.step(STEP);
+ samples.push({
+ position: [...follower.state.position],
+ speed: follower.state.speed,
+ moved: follower.state.lastMove,
+ rootDistance: previousRootDistance,
+ parameter: graph.get('speed'),
+ });
+ graph.advance(STEP);
+ previousRootDistance = graph.rootMotion.distance;
+ steps += 1;
+ }
+ return { follower, route, samples, steps };
+}
+
+test('an NPC walks around an obstacle to the goal, on the navmesh, within a time bound', () => {
+ const navmesh = wallNavmesh();
+ const { follower, route, samples, steps } = walk(humanGraph(), navmesh, [-9, 0], [9, 0]);
+ assert.equal(route.length > 2, true, 'the route bends around the wall');
+ assert.equal(follower.state.status, 'arrived');
+ const goalError = Math.hypot(follower.state.position[0] - 9, follower.state.position[2] - 0);
+ assert.ok(goalError <= 0.15, `stopped ${goalError} m from the goal`);
+ const routeLength = route.slice(1).reduce((total, point, index) => total + Math.hypot(point[0] - route[index][0], point[2] - route[index][2]), 0);
+ assert.ok(steps * STEP <= routeLength / (CRUISE * 0.5) + 4, `took ${steps * STEP} s for ${routeLength} m`);
+ for (const sample of samples) assert.ok(navmesh.isWalkable(sample.position[0], sample.position[2]), `left the navmesh at ${sample.position}`);
+ assert.equal(follower.state.blockedSteps, 0);
+});
+
+test('the speed parameter slows into corners and into the arrival, and reaches cruise on the straights', () => {
+ const navmesh = wallNavmesh();
+ const { route, samples, follower } = walk(humanGraph(), navmesh, [-9, 0], [9, 0]);
+ const peak = Math.max(...samples.map(sample => sample.speed));
+ assert.ok(peak >= CRUISE * 0.95, `cruise reached: ${peak}`);
+ for (const sample of samples) assert.equal(sample.parameter, sample.speed);
+ const corners = route.slice(1, -1);
+ assert.ok(corners.length >= 2);
+ for (const [index, corner] of corners.entries()) {
+ const before = route[index];
+ const after = route[index + 2];
+ const turn = Math.abs(Math.atan2(Math.sin(Math.atan2(after[0] - corner[0], after[2] - corner[2]) - Math.atan2(corner[0] - before[0], corner[2] - before[2])), Math.cos(Math.atan2(after[0] - corner[0], after[2] - corner[2]) - Math.atan2(corner[0] - before[0], corner[2] - before[2]))));
+ const near = samples.filter(sample => Math.hypot(sample.position[0] - corner[0], sample.position[2] - corner[2]) < 0.6);
+ assert.ok(near.length > 0);
+ const slowest = Math.min(...near.map(sample => sample.speed));
+ assert.ok(turn > 0.3, `corner ${index} turns ${turn} rad`);
+ assert.ok(slowest < CRUISE * (1 - 0.5 * turn / Math.PI) + 0.01, `corner ${corner} turning ${turn} rad passed at ${slowest}`);
+ }
+ const lastSecond = samples.slice(-15);
+ assert.ok(Math.max(...lastSecond.map(sample => sample.speed)) < CRUISE * 0.5, 'eases in to the goal');
+ assert.equal(follower.state.speed, 0);
+ assert.equal(follower.state.status, 'arrived');
+});
+
+test('the distance moved each step matches the root motion of the graph, so the feet do not slide', () => {
+ const { samples } = walk(humanGraph(), wallNavmesh(), [-9, 0], [9, 0]);
+ let largestError = 0;
+ let movedTotal = 0;
+ let rootTotal = 0;
+ for (const sample of samples) {
+ largestError = Math.max(largestError, Math.abs(sample.moved - sample.rootDistance));
+ movedTotal += sample.moved;
+ rootTotal += sample.rootDistance;
+ }
+ assert.ok(largestError < 1e-9, `per-step difference ${largestError}`);
+ assert.ok(Math.abs(movedTotal - rootTotal) < 1e-6);
+ assert.ok(movedTotal > 18, `moved ${movedTotal} m`);
+});
+
+test('the same steps give the same walk, and a start that is inside the wall is refused with a reason', () => {
+ const navmesh = wallNavmesh();
+ const first = walk(humanGraph(), navmesh, [-9, 0], [9, 0]);
+ const second = walk(humanGraph(), navmesh, [-9, 0], [9, 0]);
+ assert.deepEqual(first.samples, second.samples);
+ const follower = createPathFollower({ graph: humanGraph(), navmesh, position: [0, 0, 0] });
+ assert.throws(() => follower.goTo([9, 0]), /Start .* not walkable/);
+});
+
+test('a quadruped follows the same path through its own graph', () => {
+ const navmesh = wallNavmesh();
+ const { follower, samples } = walk(quadrupedGraph(), navmesh, [-9, 6], [9, -6]);
+ assert.equal(follower.state.status, 'arrived');
+ for (const sample of samples) {
+ assert.ok(navmesh.isWalkable(sample.position[0], sample.position[2]));
+ assert.ok(Math.abs(sample.moved - sample.rootDistance) < 1e-9, `${sample.moved} vs ${sample.rootDistance} at ${sample.position}`);
+ }
+});
+
+test('a blocked step slides along the edge of the navmesh instead of leaving it', () => {
+ const navmesh = wallNavmesh();
+ const graph = humanGraph();
+ const follower = createPathFollower({ graph, navmesh, position: [-9, 0, 0], cruiseSpeed: CRUISE });
+ follower.follow([[-9, 0], [-0.5, 0]]); // A route straight at the wall, which the navmesh would never give.
+ for (let step = 0; step < 600; step++) {
+ follower.step(STEP);
+ graph.advance(STEP);
+ assert.ok(navmesh.isWalkable(follower.state.position[0], follower.state.position[2]));
+ }
+ assert.ok(follower.state.blockedSteps > 0);
+});
+
+test('stop returns the NPC to idle and a path that is not a list is refused', () => {
+ const graph = humanGraph();
+ const follower = createPathFollower({ graph, position: [0, 0, 0] });
+ follower.follow([[0, 0], [10, 0]]);
+ follower.step(STEP);
+ graph.advance(STEP);
+ assert.ok(graph.get('speed') > 0);
+ follower.stop();
+ assert.equal(graph.get('speed'), 0);
+ assert.equal(follower.state.status, 'idle');
+ assert.throws(() => follower.follow('north'), /needs a list of 1 to 256 points/);
+ assert.throws(() => follower.follow([[0, 'a']]), /path point 0 must be \[x, z\]/);
+ assert.throws(() => follower.follow(new Array(NPC_FOLLOWER_LIMITS.maximumWaypoints + 1).fill([0, 0])), /1 to 256 points/);
+ assert.throws(() => follower.goTo([1, 1]), /goTo needs the navmesh option/);
+});
+
+test('option mistakes name the option and the fix', () => {
+ const graph = humanGraph();
+ assert.throws(() => createPathFollower({}), /graph must be an animation graph/);
+ assert.throws(() => createPathFollower({ graph, parameter: 'pace' }), /pace/);
+ assert.throws(() => createPathFollower({ graph, cruiseSpeed: -1 }), /cruiseSpeed must be a number above 0/);
+ assert.throws(() => createPathFollower({ graph, cruiseSpeed: 1, minimumSpeed: 2 }), /minimumSpeed must not exceed cruiseSpeed/);
+ assert.throws(() => createPathFollower({ graph, position: [0, 0] }), /position must be \[x, y, z\]/);
+ assert.throws(() => createPathFollower({ graph, navmesh: {} }), /navmesh must come from createNavmesh/);
+ const withoutRootMotion = createAnimationGraph({ clips: { idle: stillClip('Root', 1) }, parameters: { speed: { type: 'number' } }, layers: [{ name: 'base', states: [{ name: 'a', clip: 'idle' }] }] });
+ assert.throws(() => createPathFollower({ graph: withoutRootMotion }), /rootMotion option/);
+});