Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add player addon: character controller with kinematic collide-and-slide and swappable follow, first-person and top-down camera rigs (#772)

Nguyen Xuan An7a10fbd8b2cd
diff --git a/README.md b/README.md
index 43a5cca3..381490e6 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline |
| Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
+| Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --git a/bench/runtime-loop/index.html b/bench/runtime-loop/index.html
index 6b226a82..b6e7fe59 100644
--- a/bench/runtime-loop/index.html
+++ b/bench/runtime-loop/index.html
@@ -22,6 +22,12 @@
<button type="button" data-mode="variable">Variable</button>
<button type="button" data-mode="both">Both, interpolated</button>
</div>
+ <div class="modes" role="group" aria-label="Camera rig">
+ <button type="button" data-rig="static">Fixed view</button>
+ <button type="button" data-rig="follow">Follow</button>
+ <button type="button" data-rig="firstPerson">First person</button>
+ <button type="button" data-rig="topDown">Top down</button>
+ </div>
<output id="readout"></output>
</div>
<script type="module" src="./main.js"></script>
diff --git a/bench/runtime-loop/main.js b/bench/runtime-loop/main.js
index 7b3854b8..53de1174 100644
--- a/bench/runtime-loop/main.js
+++ b/bench/runtime-loop/main.js
@@ -3,6 +3,7 @@
import { Renderer67, box, sphere } from '/src/index.js';
import { createRuntime } from '/src/runtime.js';
import { createInput, gamepadSource, keyboardSource } from '/src/input.js';
+import { createCharacterController, createFirstPersonCamera, createFollowCamera, createTopDownCamera } from '/src/player.js';
const GRAVITY = -9.8;
const FIXED_RATE = 20; // Low on purpose, so the difference between fixed and interpolated is visible.
@@ -22,6 +23,12 @@ function rotationAroundY(angle, x, y, z) {
return new Float32Array([cosine, 0, -sine, 0, 0, 1, 0, 0, sine, 0, cosine, 0, x, y, z, 1]);
}
+function boxMatrix({ min, max }) {
+ const size = max.map((value, axis) => value - min[axis]);
+ const center = max.map((value, axis) => (value + min[axis]) / 2);
+ 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 ballPart = {
name: 'Ball',
geometry: sphere(),
@@ -37,10 +44,29 @@ const cubePart = {
const groundPart = {
name: 'Ground',
geometry: box(),
- matrix: new Float32Array([8, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 4, 0, 0, -0.05, 0, 1]),
+ matrix: new Float32Array([30, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 30, 0, 0, -0.05, 0, 1]),
material: { color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.9, emission: 0 },
};
-const parts = [groundPart, ballPart, cubePart];
+
+// Static boxes the character walks into (a wall) and climbs (steps), as { min, max } for the kinematic mover.
+const obstacles = [
+ { min: [-6, 0, -4.4], max: [6, 1.5, -4] },
+ { min: [3, 0, -1], max: [5, 0.3, 2] },
+ { min: [3.5, 0, -1], max: [5, 0.6, 1] },
+];
+const obstacleParts = obstacles.map((obstacle, index) => ({
+ name: `Obstacle${index}`,
+ geometry: box(),
+ matrix: boxMatrix(obstacle),
+ material: { color: [0.62, 0.58, 0.5], metallic: 0, roughness: 0.8, emission: 0 },
+}));
+const playerPart = {
+ name: 'Player',
+ geometry: box(),
+ matrix: boxMatrix({ min: [-0.4, 0, -0.4], max: [0.4, 1.8, 0.4] }),
+ material: { color: [0.95, 0.8, 0.25], metallic: 0, roughness: 0.5, emission: 0 },
+};
+const parts = [groundPart, ballPart, cubePart, ...obstacleParts, playerPart];
const physicsSystem = {
name: 'ball-physics',
@@ -77,7 +103,7 @@ const spinSystem = {
angle: 0,
x: 1.2,
slide(deltaSeconds) {
- this.x = Math.max(-3.5, Math.min(3.5, this.x + input.getAxis('moveX') * CUBE_SPEED * deltaSeconds));
+ this.x = Math.max(-3.5, Math.min(3.5, this.x + input.getAxis('cubeX') * CUBE_SPEED * deltaSeconds));
},
fixedUpdate(stepSeconds) {
this.slide(stepSeconds);
@@ -88,47 +114,88 @@ const spinSystem = {
},
};
-// Keys or a gamepad drive the sample: A/D or the arrow keys slide the cube, Space (or gamepad button 0) kicks the ball up.
+// Keys or a gamepad drive the sample. WASD walks the player, Shift runs, the arrow keys look, J/L slide the cube, and Space
+// jumps the player and kicks the ball up.
const input = createInput({
sources: [keyboardSource(), gamepadSource()],
- actions: { jump: ['keyboard/Space', 'gamepad/0.button0'] },
+ actions: { jump: ['keyboard/Space', 'gamepad/0.button0'], run: ['keyboard/ShiftLeft'] },
axes: {
- moveX: [
- 'keyboard/KeyD', 'keyboard/ArrowRight',
- { control: 'keyboard/KeyA', scale: -1 }, { control: 'keyboard/ArrowLeft', scale: -1 },
- 'gamepad/0.axis0',
- ],
+ cubeX: ['keyboard/KeyL', { control: 'keyboard/KeyJ', scale: -1 }],
+ moveX: ['keyboard/KeyD', { control: 'keyboard/KeyA', scale: -1 }, 'gamepad/0.axis0'],
+ moveForward: ['keyboard/KeyW', { control: 'keyboard/KeyS', scale: -1 }, { control: 'gamepad/0.axis1', scale: -1 }],
+ lookX: ['keyboard/ArrowRight', { control: 'keyboard/ArrowLeft', scale: -1 }],
+ lookY: ['keyboard/ArrowUp', { control: 'keyboard/ArrowDown', scale: -1 }],
},
});
+// The player faces and walks relative to whichever camera rig is active, so swapping the rig keeps the controls natural.
+const player = createCharacterController({
+ input,
+ position: [0, 0, 3],
+ obstacles,
+ cameraYaw: () => runtime?.getSystem('camera')?.yaw ?? 0,
+});
+const RIG_FACTORIES = {
+ follow: () => createFollowCamera({ subject: player.state, input }),
+ firstPerson: () => createFirstPersonCamera({ subject: player.state, input }),
+ topDown: () => createTopDownCamera({ subject: player.state }),
+};
+const requestedRig = new URLSearchParams(location.search).get('rig');
+let rigKind = requestedRig in RIG_FACTORIES || requestedRig === 'static' ? requestedRig : 'follow';
+
const canvas = document.querySelector('canvas');
const renderer = new Renderer67(canvas, parts, { samples: 4, memoryBudgetMiB: 256 });
renderer.resize();
+// The player box is drawn between its last two fixed steps, turned to its heading, and hidden when the camera is inside it.
+function placePlayer(blend) {
+ const [x, y, z] = player.positionAt(blend);
+ const size = [0.8, 1.8, 0.8];
+ const hiddenDrop = rigKind === 'firstPerson' ? 100 : 0; // the first-person camera sits inside the body
+ const cosine = Math.cos(player.state.yaw);
+ const sine = Math.sin(player.state.yaw);
+ playerPart.matrix = new Float32Array([
+ cosine * size[0], 0, sine * size[0], 0,
+ 0, size[1], 0, 0,
+ -sine * size[2], 0, cosine * size[2], 0,
+ x, y + size[1] / 2 - hiddenDrop, z, 1,
+ ]);
+}
+
// The ball is drawn between its last two fixed states in "both" mode and at its newest state otherwise.
function buildFrame(context) {
const blend = context.alpha;
const height = physicsSystem.previousHeight + (physicsSystem.height - physicsSystem.previousHeight) * blend;
ballPart.matrix = translation(-1.2, height, 0, BALL_RADIUS);
cubePart.matrix = rotationAroundY(spinSystem.angle, spinSystem.x, 0.5, 0);
+ placePlayer(context.alpha);
renderer.updateParts(parts);
- return { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0], time: context.elapsedSeconds };
+ const pose = runtime.getSystem('camera')?.pose(context) ?? { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0] };
+ return { ...pose, time: context.elapsedSeconds };
}
let runtime = null;
+function markRigButtons() {
+ for (const button of document.querySelectorAll('button[data-rig]')) {
+ button.setAttribute('aria-pressed', String(button.dataset.rig === rigKind));
+ }
+}
+
function startMode(mode) {
- runtime?.dispose();
+ runtime?.stop(); // not dispose: dispose would also dispose the shared input and player
runtime = createRuntime(renderer, {
mode,
fixedRate: FIXED_RATE,
frame: buildFrame,
- systems: [input, physicsSystem, spinSystem],
+ systems: [input, physicsSystem, spinSystem, player],
});
+ if (rigKind !== 'static') runtime.addSystem(RIG_FACTORIES[rigKind]());
runtime.start();
for (const button of document.querySelectorAll('button[data-mode]')) {
button.setAttribute('aria-pressed', String(button.dataset.mode === mode));
}
+ markRigButtons();
window.runtimeSample = runtime;
}
@@ -136,6 +203,20 @@ for (const button of document.querySelectorAll('button[data-mode]')) {
button.addEventListener('click', () => startMode(button.dataset.mode));
}
+// Swapping a rig while the game runs: the runtime replaces the "camera" system and the player keeps moving.
+function selectRig(kind) {
+ rigKind = kind;
+ if (kind === 'static') {
+ if (runtime.getSystem('camera')) runtime.removeSystem('camera');
+ } else if (runtime.getSystem('camera')) runtime.replaceSystem('camera', RIG_FACTORIES[kind]());
+ else runtime.addSystem(RIG_FACTORIES[kind]());
+ markRigButtons();
+}
+
+for (const button of document.querySelectorAll('button[data-rig]')) {
+ button.addEventListener('click', () => selectRig(button.dataset.rig));
+}
+
const readout = document.querySelector('#readout');
setInterval(() => {
const stats = runtime.stats;
@@ -143,7 +224,8 @@ setInterval(() => {
`${stats.framesPerSecond.toFixed(0)} fps, ${stats.averageFrameMilliseconds.toFixed(1)} ms average, ${stats.maximumFrameMilliseconds.toFixed(1)} ms worst`,
`update ${stats.updateMilliseconds.toFixed(2)} ms, render ${stats.renderMilliseconds.toFixed(2)} ms`,
`fixed steps ${stats.fixedSteps}, alpha ${stats.alpha.toFixed(2)}`,
- 'A/D or arrows slide the cube, Space kicks the ball',
+ `player ${player.state.grounded ? 'on the ground' : 'airborne'}, speed ${player.state.speed.toFixed(1)}`,
+ 'WASD walks, Shift runs, Space jumps, arrows look, J/L slide the cube',
].join('\n');
}, 250);
diff --git a/changes/772.md b/changes/772.md
new file mode 100644
index 00000000..a09d6ca5
--- /dev/null
+++ b/changes/772.md
@@ -0,0 +1 @@
+- `67js/addons/player` adds a character controller (walk, run, jump, kinematic collide-and-slide on a ground plane, heightfield or boxes, with a `mover` seam for physics) and swappable follow, first-person and top-down camera rigs as runtime systems (#772)
diff --git a/docs/player.md b/docs/player.md
new file mode 100644
index 00000000..4fcc3a87
--- /dev/null
+++ b/docs/player.md
@@ -0,0 +1,82 @@
+# Player: controllers and camera rigs
+
+`67js/addons/player` gives a live game something to control and a camera that follows it. A controller is a [runtime](runtime.md) system that reads named [input](input.md) actions and axes and moves a body. A camera rig is a runtime system that places the camera. Both are swappable while the game runs, and a game can write its own with the same shape. The addon loads only when imported and adds no dependency.
+
+```js
+import { createRuntime } from '67js/addons/runtime';
+import { createInput, keyboardSource } from '67js/addons/input';
+import { createCharacterController, createFollowCamera } from '67js/addons/player';
+
+const input = createInput({
+ sources: [keyboardSource()],
+ actions: { jump: ['keyboard/Space'], run: ['keyboard/ShiftLeft'] },
+ axes: {
+ moveX: ['keyboard/KeyD', { control: 'keyboard/KeyA', scale: -1 }],
+ moveForward: ['keyboard/KeyW', { control: 'keyboard/KeyS', scale: -1 }],
+ lookX: ['keyboard/ArrowRight', { control: 'keyboard/ArrowLeft', scale: -1 }],
+ lookY: ['keyboard/ArrowUp', { control: 'keyboard/ArrowDown', scale: -1 }],
+ },
+});
+const player = createCharacterController({ input, position: [0, 0, 3], ground: (x, z) => terrainHeight(x, z) });
+const camera = createFollowCamera({ subject: player.state, input });
+const runtime = createRuntime(renderer, {
+ systems: [input, player, camera], // input, then controller, then rig
+ frame: context => ({ ...camera.pose(context), time: context.elapsedSeconds }),
+});
+runtime.start();
+```
+
+Order the systems input, controller, rig. The controller reads this step's input, and the rig follows where the controller ended up.
+
+## Character controller
+
+`createCharacterController(options)` walks, runs and jumps. It accelerates toward the wanted velocity (less control in the air), turns the body toward where it moves, and applies gravity. Movement is relative to a view yaw: pass `cameraYaw` as a number or a function such as `() => runtime.getSystem('camera').yaw`, so the same keys work under every rig.
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `input` | required | The `createInput` object |
+| `moveX`, `moveForward`, `jump`, `run` | same names | Names of the axes and actions it reads |
+| `walkSpeed`, `runSpeed`, `jumpSpeed` | 3, 6, 7 | Units per second |
+| `gravity`, `acceleration`, `airControl` | 20, 40, 0.3 | Air control scales acceleration while airborne |
+| `radius`, `height`, `stepHeight` | 0.4, 1.8, 0.4 | Body size and the tallest step it climbs |
+| `ground`, `obstacles` | 0, none | Passed to the built-in kinematic mover |
+| `position`, `yaw` | origin, 0 | Start pose. Yaw 0 faces -Z, positive turns toward +X |
+| `faceCamera`, `turnSpeed` | false, 12 | Face the view yaw (first person) or turn toward the move direction |
+| `node` | none | An object with `position` (and `rotationY`) that is written every step |
+| `mover` | kinematic | The seam for physics, see below |
+| `name` | `player` | System name, for `replaceSystem` |
+
+`controller.state` is updated in place for animation and audio: `position`, `previousPosition`, `velocity`, `yaw`, `grounded`, `airborne`, `speed` (horizontal) and `running`. `controller.positionAt(alpha)` returns the position drawn between the last two fixed steps, and `teleport(position, yaw)` places it again.
+
+### Collide and slide
+
+`createKinematicMover({ ground, obstacles })` is the default world. `ground` is a height or a heightfield function `(x, z) => height`. `obstacles` is up to 256 boxes `{ min: [x, y, z], max: [x, y, z] }`. The body is a vertical cylinder: x and z are resolved one after the other, so it slides along a wall; anything up to `stepHeight` above the feet is climbed, and a short drop snaps down. A move is split into pieces no longer than the radius, so a fast body does not tunnel through a thin wall. A box whose underside is out of reach does not block, so there is no ceiling. Every value is bounded and the result depends only on the inputs.
+
+### Where physics plugs in
+
+A mover is `{ move(body, displacement, stepSeconds) => { position, grounded } }`. `body` holds `position`, `velocity`, `radius`, `height`, `stepHeight` and `grounded`; `displacement` is the move the controller wants this step, gravity included. A physics engine implements `move` with its own character query and returns where the body ended up. The controller derives its velocity from the result and needs nothing else from it.
+
+## Camera rigs
+
+A rig follows a `subject`: a controller's `state` or any `{ position: [x, y, z], yaw }`. Each fixed step it reads the look axes and eases a focus point toward the subject (`followSeconds`, 0 for rigid). `rig.pose(context)` gives `{ eye, target, up }` for the frame, interpolated between fixed steps with `context.alpha`. `rig.yaw` and `rig.pitch` are readable and writable; positive pitch looks up for a first-person rig and puts the camera higher for the others.
+
+- `createFollowCamera`: behind the subject at `distance` (5), `pitch` (0.35), aimed at `lookHeight` (1.5) above its feet. `clipEye(target, eye) => eye` is the seam for pulling the camera in against a world.
+- `createFirstPersonCamera`: at `eyeHeight` (1.6) looking along yaw and pitch. Pair it with `faceCamera: true` on the controller and hide the body.
+- `createTopDownCamera`: `distance` (12) above at a steep `pitch` (1.2). It does not turn unless you name `lookX`.
+
+All three take `lookX` and `lookY` axis names (set one to `null` to turn it off), `lookSpeed` in radians per second, and `minimumPitch` and `maximumPitch`.
+
+## Swapping
+
+Both swap with `runtime.replaceSystem(name, system)`. A new rig starts at the subject's yaw. A new controller starts where you put it, so pass the old `state.position`:
+
+```js
+runtime.replaceSystem('camera', createFirstPersonCamera({ subject: player.state, input }));
+runtime.replaceSystem('player', createCharacterController({ input, position: [...player.state.position], runSpeed: 9 }));
+```
+
+## Limits and errors
+
+Speeds up to 100, acceleration up to 1000, gravity up to 200, 256 obstacles, 64 sub-steps per move (`PLAYER_LIMITS`). Errors name the option and say what to pass, for example `createCharacterController walkSpeed must be a number from 0 to 100, got -1.`
+
+A runnable sample is `bench/runtime-loop/index.html`: WASD walks a box over a wall and steps, Shift runs, Space jumps, and the buttons switch between a fixed view, follow, first-person and top-down cameras.
diff --git a/package.json b/package.json
index 93180ac7..7d52a6bc 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"docs/physics.md",
"docs/runtime.md",
"docs/input.md",
+ "docs/player.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -120,6 +121,7 @@
"./addons/cloth": "./build/cloth.js",
"./addons/runtime": "./build/runtime.js",
"./addons/input": "./build/input.js",
+ "./addons/player": "./build/player.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index c1736dd8..7ca8bfcd 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -53,7 +53,7 @@ const sourceDocuments = [
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'runtime.md', 'input.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
+ 'runtime.md', 'input.md', 'player.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/src/docs-live.js b/src/docs-live.js
index d98ebc38..36cb15a8 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -64,6 +64,7 @@ const addonLoaders = import.meta.glob([
'./cloth.js',
'./runtime.js',
'./input.js',
+ './player.js',
'./update-part-vertices.js',
]);
const moduleCache = new Map();
diff --git a/src/player.js b/src/player.js
new file mode 100644
index 00000000..077f27e5
--- /dev/null
+++ b/src/player.js
@@ -0,0 +1,393 @@
+// Player layer for live games: controllers and camera rigs as runtime systems. A controller reads named input actions and
+// axes (src/input.js) and moves a body; a camera rig reads the body it follows and places the camera. Both are plain runtime
+// systems, so runtime.replaceSystem swaps them while the game runs. Motion is deterministic: the same input sequence over the
+// same fixed steps gives the same positions. The collide-and-slide here is kinematic; a physics engine plugs in through
+// options.mover (see docs/player.md). Yaw 0 faces -Z, positive yaw turns toward +X, positive pitch looks up.
+
+export const PLAYER_LIMITS = Object.freeze({
+ maximumSpeed: 100,
+ maximumAcceleration: 1000,
+ maximumGravity: 200,
+ maximumRadius: 10,
+ maximumHeight: 20,
+ maximumObstacles: 256,
+ maximumDistance: 10000,
+ maximumSubsteps: 64,
+ maximumPitch: 1.5,
+});
+
+const WORLD_UP = [0, 1, 0];
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function numberOption(owner, label, value, fallback, minimum, maximum) {
+ const resolved = value ?? fallback;
+ if (!Number.isFinite(resolved) || resolved < minimum || resolved > maximum) {
+ throw new RangeError(`${owner} ${label} must be a number from ${minimum} to ${maximum}, got ${String(resolved)}.`);
+ }
+ return resolved;
+}
+
+function vectorOption(owner, label, value, fallback) {
+ const resolved = value ?? fallback;
+ const limit = PLAYER_LIMITS.maximumDistance;
+ if (!Array.isArray(resolved) || resolved.length !== 3 || !resolved.every(entry => Number.isFinite(entry) && Math.abs(entry) <= limit)) {
+ throw new TypeError(`${owner} ${label} must be an array of 3 finite numbers within ${limit}, such as [0, 0, 0], got ${JSON.stringify(resolved)}.`);
+ }
+ return [...resolved];
+}
+
+function requireInput(owner, input) {
+ const hasInterface = input !== null && typeof input === 'object'
+ && ['getAxis', 'isHeld', 'wasPressed'].every(method => typeof input[method] === 'function');
+ if (!hasInterface) {
+ throw new TypeError(`${owner} needs options.input: the object from createInput() with getAxis, isHeld and wasPressed, got ${describe(input)}.`);
+ }
+ return input;
+}
+
+function forwardDirection(yaw) {
+ return [Math.sin(yaw), 0, -Math.cos(yaw)];
+}
+
+function rightDirection(yaw) {
+ return [Math.cos(yaw), 0, Math.sin(yaw)];
+}
+
+function wrapAngle(angle) {
+ const wrapped = (angle + Math.PI) % (2 * Math.PI);
+ return (wrapped < 0 ? wrapped + 2 * Math.PI : wrapped) - Math.PI;
+}
+
+function clamp(value, minimum, maximum) {
+ return Math.max(minimum, Math.min(maximum, value));
+}
+
+function blend(from, to, amount) {
+ return from.map((value, index) => value + (to[index] - value) * amount);
+}
+
+function validateObstacles(obstacles) {
+ if (!Array.isArray(obstacles) || obstacles.length > PLAYER_LIMITS.maximumObstacles) {
+ throw new RangeError(`createKinematicMover obstacles must be an array of at most ${PLAYER_LIMITS.maximumObstacles} boxes like { min: [x, y, z], max: [x, y, z] }.`);
+ }
+ return obstacles.map((box, index) => {
+ const label = `obstacles[${index}]`;
+ const min = vectorOption('createKinematicMover', `${label}.min`, box?.min);
+ const max = vectorOption('createKinematicMover', `${label}.max`, box?.max);
+ if (min.some((value, axis) => value > max[axis])) {
+ throw new RangeError(`createKinematicMover ${label} min must not exceed max on any axis, got min ${JSON.stringify(min)} and max ${JSON.stringify(max)}.`);
+ }
+ return { min, max };
+ });
+}
+
+// Kinematic world for a character: a ground (a height, or a heightfield function (x, z) => height) plus static boxes.
+// move(body, displacement) slides along walls by resolving x and z one after the other, climbs anything up to body.stepHeight,
+// snaps down short drops and reports grounded. Replace it with options.mover on a controller to use physics instead.
+export function createKinematicMover(options = {}) {
+ const ground = options.ground ?? 0;
+ if (typeof ground !== 'function' && !Number.isFinite(ground)) {
+ throw new TypeError(`createKinematicMover ground must be a height number or a function (x, z) => height, got ${describe(ground)}.`);
+ }
+ const obstacles = validateObstacles(options.obstacles ?? []);
+
+ function groundHeight(x, z) {
+ const height = typeof ground === 'function' ? ground(x, z) : ground;
+ if (!Number.isFinite(height)) {
+ throw new RangeError(`createKinematicMover ground(${x}, ${z}) must return a finite height, got ${String(height)}.`);
+ }
+ return height;
+ }
+
+ // Highest surface under a body of `radius` at (x, z) that starts within reach of its feet.
+ function surfaceHeight(x, z, radius, feetY, reach) {
+ let height = groundHeight(x, z);
+ for (const { min, max } of obstacles) {
+ const covers = x >= min[0] - radius && x <= max[0] + radius && z >= min[2] - radius && z <= max[2] + radius;
+ if (covers && min[1] <= feetY + reach) height = Math.max(height, max[1]);
+ }
+ return height;
+ }
+
+ function move(body, displacement) {
+ const [startX, startY, startZ] = body.position;
+ const { radius, stepHeight } = body;
+ const horizontalDistance = Math.hypot(displacement[0], displacement[2]);
+ const substeps = clamp(Math.ceil(horizontalDistance / radius), 1, PLAYER_LIMITS.maximumSubsteps);
+ let x = startX;
+ let z = startZ;
+ for (let index = 0; index < substeps; index += 1) {
+ const nextX = x + displacement[0] / substeps;
+ if (surfaceHeight(nextX, z, radius, startY, stepHeight) <= startY + stepHeight) x = nextX;
+ const nextZ = z + displacement[2] / substeps;
+ if (surfaceHeight(x, nextZ, radius, startY, stepHeight) <= startY + stepHeight) z = nextZ;
+ }
+ const surface = surfaceHeight(x, z, radius, startY, stepHeight);
+ const wantedY = startY + displacement[1];
+ if (wantedY <= surface) return { position: [x, surface, z], grounded: true };
+ const canSnapDown = body.grounded && displacement[1] <= 0 && wantedY - surface <= stepHeight;
+ if (canSnapDown) return { position: [x, surface, z], grounded: true };
+ return { position: [x, wantedY, z], grounded: false };
+ }
+
+ return { move, groundHeight };
+}
+
+function validateMover(owner, mover) {
+ if (mover === null || typeof mover !== 'object' || typeof mover.move !== 'function') {
+ throw new TypeError(`${owner} mover must be an object with move(body, displacement, stepSeconds) => { position, grounded }, such as createKinematicMover(), got ${describe(mover)}.`);
+ }
+ return mover;
+}
+
+function readMoveResult(owner, result) {
+ const validPosition = Array.isArray(result?.position) && result.position.length === 3 && result.position.every(Number.isFinite);
+ if (!validPosition || typeof result.grounded !== 'boolean') {
+ throw new TypeError(`${owner} mover.move must return { position: [x, y, z], grounded: boolean }, got ${JSON.stringify(result)}.`);
+ }
+ return result;
+}
+
+// Character controller: walk, run and jump with acceleration, air control and ground snap. Put it after the input system and
+// before any camera rig. Name defaults to "player"; replaceSystem("player", other) swaps it.
+export function createCharacterController(options = {}) {
+ const owner = 'createCharacterController';
+ const input = requireInput(owner, options.input);
+ const mover = validateMover(owner, options.mover ?? createKinematicMover({ ground: options.ground, obstacles: options.obstacles }));
+ const settings = {
+ walkSpeed: numberOption(owner, 'walkSpeed', options.walkSpeed, 3, 0, PLAYER_LIMITS.maximumSpeed),
+ runSpeed: numberOption(owner, 'runSpeed', options.runSpeed, 6, 0, PLAYER_LIMITS.maximumSpeed),
+ jumpSpeed: numberOption(owner, 'jumpSpeed', options.jumpSpeed, 7, 0, PLAYER_LIMITS.maximumSpeed),
+ gravity: numberOption(owner, 'gravity', options.gravity, 20, 0, PLAYER_LIMITS.maximumGravity),
+ acceleration: numberOption(owner, 'acceleration', options.acceleration, 40, 0.01, PLAYER_LIMITS.maximumAcceleration),
+ airControl: numberOption(owner, 'airControl', options.airControl, 0.3, 0, 1),
+ turnSpeed: numberOption(owner, 'turnSpeed', options.turnSpeed, 12, 0, 100),
+ radius: numberOption(owner, 'radius', options.radius, 0.4, 0.01, PLAYER_LIMITS.maximumRadius),
+ height: numberOption(owner, 'height', options.height, 1.8, 0.01, PLAYER_LIMITS.maximumHeight),
+ stepHeight: numberOption(owner, 'stepHeight', options.stepHeight, 0.4, 0, PLAYER_LIMITS.maximumHeight),
+ };
+ const names = {
+ moveX: options.moveX ?? 'moveX',
+ moveForward: options.moveForward ?? 'moveForward',
+ jump: options.jump ?? 'jump',
+ run: options.run ?? 'run',
+ };
+ const faceCamera = options.faceCamera ?? false;
+ const cameraYaw = options.cameraYaw ?? 0;
+ if (typeof cameraYaw !== 'function' && !Number.isFinite(cameraYaw)) {
+ throw new TypeError(`${owner} cameraYaw must be a yaw in radians or a function returning one, such as () => rig.yaw, got ${describe(cameraYaw)}.`);
+ }
+ const node = options.node;
+ if (node !== undefined && (node === null || typeof node !== 'object' || !Array.isArray(node.position))) {
+ throw new TypeError(`${owner} node must be an object with a position array, such as { position: [0, 0, 0] }, got ${describe(node)}.`);
+ }
+
+ const startPosition = vectorOption(owner, 'position', options.position, [0, 0, 0]);
+ const state = {
+ position: startPosition,
+ previousPosition: [...startPosition],
+ velocity: [0, 0, 0],
+ yaw: numberOption(owner, 'yaw', options.yaw, 0, -1000, 1000),
+ grounded: false,
+ airborne: true,
+ speed: 0,
+ running: false,
+ };
+
+ function writeNode() {
+ if (!node) return;
+ node.position[0] = state.position[0];
+ node.position[1] = state.position[1];
+ node.position[2] = state.position[2];
+ if ('rotationY' in node) node.rotationY = -state.yaw;
+ }
+
+ function currentCameraYaw() {
+ const yaw = typeof cameraYaw === 'function' ? cameraYaw() : cameraYaw;
+ if (!Number.isFinite(yaw)) throw new TypeError(`${owner} cameraYaw must give a finite number of radians, got ${String(yaw)}.`);
+ return yaw;
+ }
+
+ function turnToward(targetYaw, stepSeconds) {
+ const difference = wrapAngle(targetYaw - state.yaw);
+ const maximumTurn = settings.turnSpeed * stepSeconds;
+ state.yaw = wrapAngle(state.yaw + clamp(difference, -maximumTurn, maximumTurn));
+ }
+
+ function advance(stepSeconds) {
+ state.previousPosition = [...state.position];
+ const sideInput = input.getAxis(names.moveX);
+ const forwardInput = input.getAxis(names.moveForward);
+ const intentLength = Math.min(1, Math.hypot(sideInput, forwardInput));
+ const intentScale = intentLength > 0 ? intentLength / Math.hypot(sideInput, forwardInput) : 0;
+ const viewYaw = currentCameraYaw();
+ const forward = forwardDirection(viewYaw);
+ const right = rightDirection(viewYaw);
+ state.running = input.isHeld(names.run);
+ const topSpeed = state.running ? settings.runSpeed : settings.walkSpeed;
+ const wantedX = (forward[0] * forwardInput + right[0] * sideInput) * intentScale * topSpeed;
+ const wantedZ = (forward[2] * forwardInput + right[2] * sideInput) * intentScale * topSpeed;
+
+ const control = state.grounded ? 1 : settings.airControl;
+ const maximumChange = settings.acceleration * control * stepSeconds;
+ const changeX = wantedX - state.velocity[0];
+ const changeZ = wantedZ - state.velocity[2];
+ const changeLength = Math.hypot(changeX, changeZ);
+ const changeScale = changeLength > maximumChange ? maximumChange / changeLength : 1;
+ state.velocity[0] += changeX * changeScale;
+ state.velocity[2] += changeZ * changeScale;
+
+ if (faceCamera) turnToward(viewYaw, stepSeconds);
+ else if (intentLength > 0.1) turnToward(Math.atan2(wantedX, -wantedZ), stepSeconds);
+
+ if (state.grounded && input.wasPressed(names.jump)) {
+ state.velocity[1] = settings.jumpSpeed;
+ state.grounded = false;
+ }
+ state.velocity[1] = Math.max(-PLAYER_LIMITS.maximumSpeed, state.velocity[1] - settings.gravity * stepSeconds);
+
+ const body = {
+ position: [...state.position],
+ velocity: [...state.velocity],
+ radius: settings.radius,
+ height: settings.height,
+ stepHeight: settings.stepHeight,
+ grounded: state.grounded,
+ };
+ const displacement = state.velocity.map(component => component * stepSeconds);
+ const result = readMoveResult(owner, mover.move(body, displacement, stepSeconds));
+ state.velocity[0] = (result.position[0] - state.position[0]) / stepSeconds;
+ state.velocity[2] = (result.position[2] - state.position[2]) / stepSeconds;
+ if (result.grounded && state.velocity[1] <= 0) state.velocity[1] = 0;
+ state.position = [...result.position];
+ state.grounded = result.grounded;
+ state.airborne = !result.grounded;
+ state.speed = Math.hypot(state.velocity[0], state.velocity[2]);
+ writeNode();
+ }
+
+ const controller = {
+ name: options.name ?? 'player',
+ kind: 'character',
+ state,
+ // Position drawn between the last two fixed steps; alpha is context.alpha.
+ positionAt: alpha => blend(state.previousPosition, state.position, alpha),
+ teleport(position, yaw = state.yaw) {
+ state.position = vectorOption(owner, 'teleport position', position);
+ state.previousPosition = [...state.position];
+ state.velocity = [0, 0, 0];
+ state.yaw = numberOption(owner, 'teleport yaw', yaw, 0, -1000, 1000);
+ state.grounded = false;
+ state.airborne = true;
+ writeNode();
+ return controller;
+ },
+ init: writeNode,
+ fixedUpdate: advance,
+ update(deltaSeconds, context) {
+ if (context?.mode === 'variable') advance(deltaSeconds);
+ },
+ };
+ return controller;
+}
+
+const RIG_KINDS = Object.freeze({
+ follow: { pitch: 0.35, minimumPitch: -0.2, maximumPitch: 1.3, distance: 5, lookHeight: 1.5, followSeconds: 0.12, lookAxes: true },
+ firstPerson: { pitch: 0, minimumPitch: -1.4, maximumPitch: 1.4, eyeHeight: 1.6, followSeconds: 0, lookAxes: true },
+ topDown: { pitch: 1.2, minimumPitch: 0.5, maximumPitch: 1.5, distance: 12, lookHeight: 0, followSeconds: 0.2, lookAxes: false },
+});
+
+function placeCamera(kind, rig, focus) {
+ const yaw = rig.yaw;
+ const pitch = rig.pitch;
+ if (kind === 'firstPerson') {
+ const eye = [focus[0], focus[1] + rig.eyeHeight, focus[2]];
+ const horizontal = Math.cos(pitch);
+ const look = [Math.sin(yaw) * horizontal, Math.sin(pitch), -Math.cos(yaw) * horizontal];
+ return { eye, target: eye.map((value, axis) => value + look[axis]) };
+ }
+ // follow and topDown orbit the focus point at `distance`; pitch is how far above the horizon the camera sits.
+ const target = [focus[0], focus[1] + rig.lookHeight, focus[2]];
+ const forward = forwardDirection(yaw);
+ const behind = rig.distance * Math.cos(pitch);
+ const eye = [target[0] - forward[0] * behind, target[1] + rig.distance * Math.sin(pitch), target[2] - forward[2] * behind];
+ return { eye: rig.clipEye ? rig.clipEye(target, eye) : eye, target };
+}
+
+function createCameraRig(kind, options) {
+ const owner = `create${kind[0].toUpperCase()}${kind.slice(1)}Camera`;
+ const defaults = RIG_KINDS[kind];
+ const subject = options.subject;
+ if (subject === null || typeof subject !== 'object' || !Array.isArray(subject.position)) {
+ throw new TypeError(`${owner} needs options.subject: a controller's state (controller.state) or any { position: [x, y, z], yaw }, got ${describe(subject)}.`);
+ }
+ if (options.clipEye !== undefined && typeof options.clipEye !== 'function') {
+ throw new TypeError(`${owner} clipEye must be a function (target, eye) => eye, or left out, got ${describe(options.clipEye)}.`);
+ }
+ const lookNames = defaults.lookAxes ? { x: options.lookX ?? 'lookX', y: options.lookY ?? 'lookY' } : { x: options.lookX, y: options.lookY };
+ const wantsLook = lookNames.x !== null && lookNames.x !== undefined;
+ const input = wantsLook || lookNames.y ? requireInput(owner, options.input) : options.input;
+ const minimumPitch = numberOption(owner, 'minimumPitch', options.minimumPitch, defaults.minimumPitch, -PLAYER_LIMITS.maximumPitch, PLAYER_LIMITS.maximumPitch);
+ const maximumPitch = numberOption(owner, 'maximumPitch', options.maximumPitch, defaults.maximumPitch, minimumPitch, PLAYER_LIMITS.maximumPitch);
+ const lookSpeed = numberOption(owner, 'lookSpeed', options.lookSpeed, 2.5, 0, 100);
+ const followSeconds = numberOption(owner, 'followSeconds', options.followSeconds, defaults.followSeconds, 0, 10);
+ const rig = {
+ name: options.name ?? 'camera',
+ kind,
+ subject,
+ yaw: numberOption(owner, 'yaw', options.yaw, subject.yaw ?? 0, -1000, 1000),
+ pitch: clamp(numberOption(owner, 'pitch', options.pitch, defaults.pitch, -PLAYER_LIMITS.maximumPitch, PLAYER_LIMITS.maximumPitch), minimumPitch, maximumPitch),
+ distance: numberOption(owner, 'distance', options.distance, defaults.distance ?? 0, defaults.distance === undefined ? 0 : 0.1, PLAYER_LIMITS.maximumDistance),
+ lookHeight: numberOption(owner, 'lookHeight', options.lookHeight, defaults.lookHeight ?? 0, -PLAYER_LIMITS.maximumHeight, PLAYER_LIMITS.maximumHeight),
+ eyeHeight: numberOption(owner, 'eyeHeight', options.eyeHeight, defaults.eyeHeight ?? 0, 0, PLAYER_LIMITS.maximumHeight),
+ clipEye: options.clipEye,
+ focus: [...subject.position],
+ previousFocus: [...subject.position],
+ };
+
+ function advance(stepSeconds) {
+ if (wantsLook) {
+ rig.yaw = wrapAngle(rig.yaw + input.getAxis(lookNames.x) * lookSpeed * stepSeconds);
+ }
+ if (lookNames.y) {
+ rig.pitch = clamp(rig.pitch + input.getAxis(lookNames.y) * lookSpeed * stepSeconds, minimumPitch, maximumPitch);
+ }
+ rig.previousFocus = rig.focus;
+ const amount = followSeconds === 0 ? 1 : 1 - Math.exp(-stepSeconds / followSeconds);
+ rig.focus = blend(rig.focus, rig.subject.position, amount);
+ }
+
+ rig.init = () => {
+ rig.focus = [...rig.subject.position];
+ rig.previousFocus = [...rig.focus];
+ };
+ rig.fixedUpdate = advance;
+ rig.update = (deltaSeconds, context) => {
+ if (context?.mode === 'variable') advance(deltaSeconds);
+ };
+ // The camera for one frame: { eye, target, up }, ready to merge into the frame passed to render. Pass the runtime context.
+ rig.pose = context => {
+ const focus = blend(rig.previousFocus, rig.focus, context?.alpha ?? 1);
+ return { ...placeCamera(kind, rig, focus), up: WORLD_UP };
+ };
+ return rig;
+}
+
+// Third-person follow camera: orbits behind the subject, turns with the look axes and eases toward it (followSeconds).
+// options.clipEye(target, eye) => eye is the seam for collision pull-in against a world.
+export function createFollowCamera(options = {}) {
+ return createCameraRig('follow', options);
+}
+
+// First-person camera at the subject's eye height, looking where yaw and pitch point.
+export function createFirstPersonCamera(options = {}) {
+ return createCameraRig('firstPerson', options);
+}
+
+// Top-down camera high above the subject at a steep fixed pitch. It does not turn unless lookX is named.
+export function createTopDownCamera(options = {}) {
+ return createCameraRig('topDown', options);
+}
diff --git a/tests/player.test.js b/tests/player.test.js
new file mode 100644
index 00000000..cbdf0f41
--- /dev/null
+++ b/tests/player.test.js
@@ -0,0 +1,291 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createInput } from '../src/input.js';
+import {
+ createCharacterController, createFirstPersonCamera, createFollowCamera, createKinematicMover, createTopDownCamera, PLAYER_LIMITS,
+} from '../src/player.js';
+import { createRuntime } from '../src/runtime.js';
+
+const STEP_MILLISECONDS = 1000 / 60;
+const fakeRenderer = { render: () => {} };
+const scheduler = { request: () => 1, cancel: () => {} };
+
+function createScriptedInput() {
+ return createInput({
+ actions: { jump: ['script/jump'], run: ['script/run'] },
+ axes: {
+ moveX: ['script/right', { control: 'script/left', scale: -1 }],
+ moveForward: ['script/forward', { control: 'script/back', scale: -1 }],
+ lookX: ['script/lookRight', { control: 'script/lookLeft', scale: -1 }],
+ lookY: ['script/lookUp', { control: 'script/lookDown', scale: -1 }],
+ },
+ });
+}
+
+function createGame(options = {}) {
+ const input = createScriptedInput();
+ const player = createCharacterController({ input, ...options.controller });
+ const systems = [input, player];
+ if (options.rig) systems.push(options.rig(player, input));
+ const runtime = createRuntime(fakeRenderer, { mode: 'fixed', fixedStepSeconds: 1 / 60, systems, scheduler });
+ return { input, player, runtime };
+}
+
+function run(runtime, steps) {
+ for (let index = 0; index < steps; index += 1) runtime.step(STEP_MILLISECONDS);
+}
+
+function approximately(actual, expected, tolerance = 1e-6) {
+ assert.ok(Math.abs(actual - expected) <= tolerance, `expected ${actual} to be within ${tolerance} of ${expected}`);
+}
+
+test('walking forward moves along -Z at walk speed and run speed', () => {
+ const { input, player, runtime } = createGame();
+ input.press('script/forward');
+ run(runtime, 60);
+ approximately(player.state.speed, 3);
+ assert.ok(player.state.position[2] < -2.4 && player.state.position[2] > -3, `z was ${player.state.position[2]}`);
+ assert.equal(player.state.grounded, true);
+ input.press('script/run');
+ run(runtime, 60);
+ approximately(player.state.speed, 6);
+ assert.equal(player.state.running, true);
+});
+
+test('the same input sequence gives the same positions', () => {
+ const finalPositions = [0, 1].map(() => {
+ const { input, player, runtime } = createGame({ controller: { ground: (x, z) => 0.1 * Math.sin(x) * Math.cos(z) } });
+ input.press('script/forward');
+ input.press('script/right');
+ run(runtime, 30);
+ input.press('script/jump');
+ run(runtime, 2);
+ input.release('script/jump');
+ run(runtime, 60);
+ return player.state.position;
+ });
+ assert.deepEqual(finalPositions[0], finalPositions[1]);
+});
+
+test('a jump leaves the ground, peaks near the expected height and lands', () => {
+ const { input, player, runtime } = createGame();
+ run(runtime, 2);
+ assert.equal(player.state.grounded, true);
+ input.press('script/jump');
+ run(runtime, 1);
+ input.release('script/jump');
+ assert.equal(player.state.airborne, true);
+ let peak = 0;
+ for (let step = 0; step < 120 && player.state.airborne; step += 1) {
+ run(runtime, 1);
+ peak = Math.max(peak, player.state.position[1]);
+ }
+ assert.ok(peak > 1.1 && peak < 1.3, `peak was ${peak}`); // 7^2 / (2 * 20) = 1.225
+ assert.equal(player.state.grounded, true);
+ assert.equal(player.state.position[1], 0);
+});
+
+test('a jump pressed in the air does not restart the jump', () => {
+ const { input, player, runtime } = createGame();
+ run(runtime, 2);
+ input.press('script/jump');
+ run(runtime, 30);
+ input.release('script/jump');
+ input.press('script/jump');
+ run(runtime, 1);
+ assert.ok(player.state.velocity[1] < 0, `vertical speed was ${player.state.velocity[1]}`);
+});
+
+test('the character follows a heightfield', () => {
+ const { input, player, runtime } = createGame({ controller: { ground: (x, z) => Math.max(0, -z) * 0.2 } });
+ input.press('script/forward');
+ run(runtime, 60);
+ approximately(player.state.position[1], Math.max(0, -player.state.position[2]) * 0.2, 1e-9);
+ assert.ok(player.state.position[1] > 0.3);
+ assert.equal(player.state.grounded, true);
+ input.release('script/forward');
+ input.press('script/back');
+ run(runtime, 200);
+ assert.equal(player.state.grounded, true);
+ assert.equal(player.state.position[1], 0);
+});
+
+test('walls block and slide, and stairs are climbed', () => {
+ const wall = { min: [-50, 0, -4], max: [50, 3, -3] };
+ const { input, player, runtime } = createGame({ controller: { obstacles: [wall] } });
+ input.press('script/forward');
+ input.press('script/right');
+ run(runtime, 240);
+ assert.ok(player.state.position[2] >= -3 + 0.4 - 1e-6, `stopped at z ${player.state.position[2]}`);
+ assert.ok(player.state.position[0] > 3, `slid along the wall to x ${player.state.position[0]}`);
+
+ const stairs = [0.3, 0.6, 0.9].map((top, index) => ({ min: [-2, 0, -2 - index], max: [2, top, -1 - index] }));
+ const climber = createGame({ controller: { obstacles: stairs, stepHeight: 0.35 } });
+ climber.input.press('script/forward');
+ run(climber.runtime, 80);
+ approximately(climber.player.state.position[1], 0.9, 1e-9);
+});
+
+test('a fast character does not tunnel through a thin wall', () => {
+ const wall = { min: [-5, 0, -5.05], max: [5, 3, -5] };
+ const { input, player, runtime } = createGame({ controller: { obstacles: [wall], runSpeed: 90, acceleration: 1000 } });
+ input.press('script/forward');
+ input.press('script/run');
+ run(runtime, 60);
+ assert.ok(player.state.position[2] > -5, `ended at z ${player.state.position[2]}`);
+});
+
+test('state exposes grounded, airborne, speed, yaw and velocity for animation and audio', () => {
+ const { player } = createGame();
+ for (const key of ['grounded', 'airborne', 'speed', 'yaw', 'velocity', 'running']) assert.ok(key in player.state, key);
+});
+
+test('movement is relative to the camera yaw and the body turns toward it', () => {
+ const { input, player, runtime } = createGame({ controller: { cameraYaw: Math.PI / 2 } });
+ input.press('script/forward');
+ run(runtime, 30);
+ assert.ok(player.state.position[0] > 1, `x was ${player.state.position[0]}`);
+ approximately(player.state.position[2], 0, 1e-9);
+ approximately(player.state.yaw, Math.PI / 2);
+});
+
+test('a controller writes its node and can be teleported', () => {
+ const node = { position: [9, 9, 9], rotationY: 0 };
+ const { input, player, runtime } = createGame({ controller: { node } });
+ input.press('script/forward');
+ run(runtime, 10);
+ assert.deepEqual(node.position, player.state.position);
+ player.teleport([4, 5, 6]);
+ assert.deepEqual(node.position, [4, 5, 6]);
+ assert.deepEqual(player.state.previousPosition, [4, 5, 6]);
+});
+
+test('a physics engine plugs in through options.mover', () => {
+ const calls = [];
+ const mover = {
+ move(body, displacement, stepSeconds) {
+ calls.push({ body, displacement, stepSeconds });
+ return { position: [body.position[0] + displacement[0], 0, body.position[2] + displacement[2]], grounded: true };
+ },
+ };
+ const { input, player, runtime } = createGame({ controller: { mover } });
+ input.press('script/forward');
+ run(runtime, 3);
+ assert.equal(calls.length, 3);
+ assert.equal(calls[0].body.radius, 0.4);
+ assert.ok(player.state.position[2] < 0);
+ const broken = createCharacterController({ input, mover: { move: () => ({ position: [0, 0], grounded: true }) } });
+ assert.throws(() => broken.fixedUpdate(1 / 60), /mover\.move must return/);
+});
+
+test('swapping the controller at runtime keeps the world and the position', () => {
+ const { input, player, runtime } = createGame();
+ input.press('script/forward');
+ run(runtime, 60);
+ const handedOver = [...player.state.position];
+ const sprinter = createCharacterController({ input, position: handedOver, walkSpeed: 6 });
+ runtime.replaceSystem('player', sprinter);
+ assert.equal(runtime.getSystem('player'), sprinter);
+ run(runtime, 60);
+ approximately(sprinter.state.speed, 6);
+ assert.ok(sprinter.state.position[2] < handedOver[2] - 4);
+});
+
+test('camera rigs place the camera and swap while the game runs', () => {
+ const { input, player, runtime } = createGame({
+ rig: (controller, inputLayer) => createFollowCamera({ subject: controller.state, input: inputLayer, distance: 5, pitch: 0.35 }),
+ });
+ run(runtime, 120);
+ const follow = runtime.getSystem('camera').pose({ alpha: 1 });
+ approximately(follow.eye[2], 5 * Math.cos(0.35), 1e-9);
+ approximately(follow.target[1], 1.5, 1e-9);
+ assert.ok(follow.eye[1] > follow.target[1]);
+ input.press('script/forward');
+ run(runtime, 120);
+ const moving = runtime.getSystem('camera').pose({ alpha: 1 });
+ assert.ok(moving.eye[2] < follow.eye[2] - 4, 'the camera trails the moving subject');
+ assert.ok(moving.eye[2] > player.state.position[2], 'and stays behind it');
+
+ runtime.replaceSystem('camera', createFirstPersonCamera({ subject: player.state, input }));
+ run(runtime, 1);
+ const first = runtime.getSystem('camera').pose({ alpha: 1 });
+ approximately(first.eye[1], 1.6, 1e-9);
+ approximately(first.eye[0], player.state.position[0], 1e-9);
+ assert.ok(first.target[2] < first.eye[2], 'looks toward -Z at yaw 0');
+
+ runtime.replaceSystem('camera', createTopDownCamera({ subject: player.state }));
+ run(runtime, 120);
+ const top = runtime.getSystem('camera').pose({ alpha: 1 });
+ assert.ok(top.eye[1] > 10, `top-down eye height ${top.eye[1]}`);
+ assert.ok(Math.abs(top.target[0] - player.state.position[0]) < 1e-3);
+});
+
+test('look axes turn the camera and clamp its pitch', () => {
+ const input = createScriptedInput();
+ const rig = createFirstPersonCamera({ subject: { position: [0, 0, 0], yaw: 0 }, input });
+ rig.init();
+ input.press('script/lookRight');
+ input.press('script/lookUp');
+ input.sample();
+ for (let step = 0; step < 60; step += 1) rig.fixedUpdate(1 / 60);
+ approximately(rig.yaw, 2.5);
+ approximately(rig.pitch, 1.4, 1e-9);
+});
+
+test('a first-person rig can drive the body heading through cameraYaw', () => {
+ const input = createScriptedInput();
+ const rig = createFirstPersonCamera({ subject: { position: [0, 0, 0], yaw: 0 }, input });
+ const player = createCharacterController({ input, faceCamera: true, cameraYaw: () => rig.yaw });
+ rig.yaw = 1;
+ input.press('script/forward');
+ input.sample();
+ for (let step = 0; step < 30; step += 1) player.fixedUpdate(1 / 60);
+ approximately(player.state.yaw, 1);
+});
+
+test('the pose interpolates between fixed steps', () => {
+ const subject = { position: [0, 0, 0], yaw: 0 };
+ const rig = createTopDownCamera({ subject, followSeconds: 0 });
+ rig.init();
+ subject.position = [10, 0, 0];
+ rig.fixedUpdate(1 / 60);
+ const half = rig.pose({ alpha: 0.5 });
+ const full = rig.pose({ alpha: 1 });
+ approximately(full.target[0] - half.target[0], 5, 1e-9);
+});
+
+test('clipEye can pull the camera in', () => {
+ const subject = { position: [0, 0, 0], yaw: 0 };
+ const rig = createFollowCamera({ subject, input: createScriptedInput(), clipEye: (target, eye) => [eye[0], Math.max(eye[1], 3), eye[2]], pitch: 0, lookHeight: 0 });
+ rig.init();
+ assert.equal(rig.pose().eye[1], 3);
+});
+
+test('mistakes name the field and the fix', () => {
+ const input = createScriptedInput();
+ const subject = { position: [0, 0, 0] };
+ assert.throws(() => createCharacterController({}), /options\.input.*createInput/);
+ assert.throws(() => createCharacterController({ input, walkSpeed: -1 }), /walkSpeed must be a number from 0 to 100/);
+ assert.throws(() => createCharacterController({ input, position: [0, 'x', 0] }), /position must be an array of 3 finite numbers/);
+ assert.throws(() => createCharacterController({ input, cameraYaw: 'north' }), /cameraYaw must be a yaw/);
+ assert.throws(() => createCharacterController({ input, mover: {} }), /mover must be an object with move/);
+ assert.throws(() => createFollowCamera({}), /options\.subject/);
+ assert.throws(() => createFollowCamera({ subject }), /options\.input/);
+ assert.throws(() => createFollowCamera({ subject, input, clipEye: 4 }), /clipEye must be a function/);
+ assert.throws(() => createFollowCamera({ subject, input, minimumPitch: 1, maximumPitch: 0 }), /maximumPitch/);
+ assert.throws(() => createKinematicMover({ ground: 'flat' }), /ground must be a height number/);
+ assert.throws(() => createKinematicMover({ obstacles: [{ min: [1, 0, 0], max: [0, 1, 1] }] }), /min must not exceed max/);
+ assert.throws(() => createKinematicMover({ obstacles: new Array(PLAYER_LIMITS.maximumObstacles + 1).fill({ min: [0, 0, 0], max: [1, 1, 1] }) }), /at most 256 boxes/);
+ assert.throws(() => createKinematicMover({ ground: () => NaN }).groundHeight(0, 0), /finite height/);
+});
+
+test('variable mode advances the controller and rig from update', () => {
+ const input = createScriptedInput();
+ const player = createCharacterController({ input });
+ const rig = createFollowCamera({ subject: player.state, input });
+ const runtime = createRuntime(fakeRenderer, { mode: 'variable', systems: [input, player, rig], scheduler });
+ input.press('script/forward');
+ run(runtime, 30);
+ assert.ok(player.state.position[2] < -1);
+ assert.ok(rig.focus[2] < 0);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 80d48ff3..7814be9f 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -107,6 +107,7 @@ export default defineConfig({
cloth: 'src/cloth.js',
runtime: 'src/runtime.js',
input: 'src/input.js',
+ player: 'src/player.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.