Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add vehicle and flight controllers, orbit, chase and side-scroller rigs, camera clip and a controller registry to the player addon (#772)

Nguyen Xuan An7b762c5f483a
diff --git a/README.md b/README.md
index 29c7110d..a8096377 100644
--- a/README.md
+++ b/README.md
@@ -145,7 +145,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Live games | `67js/addons/physics-runtime` | [Live physics](docs/physics-runtime.md): a physics world stepped in the game loop, contact and sensor events, ray, shape and overlap queries |
| Live games | `67js/addons/audio` | [Spatial audio](docs/audio.md): sounds on nodes, played from contacts, markers and input, with buses and a limiter |
| Live games | `67js/addons/animation-graph` | [Animation graph](docs/animation-graph.md): states, 1D and 2D blend spaces, parameter transitions with crossfades and masked layers for any rig |
-| Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
+| Live games | `67js/addons/player` | [Player](docs/player.md): character, vehicle and flight controllers, follow, first-person, top-down, orbit, chase and side-scroller camera rigs with wall pull-in, custom kinds, swappable at runtime |
| Live games | `67js/addons/game-rules` | [Game rules](docs/game-rules.md): a JSON rule document of variables, triggers and actions, played as a runtime system |
| 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) |
diff --git a/changes/772-controllers-rigs.md b/changes/772-controllers-rigs.md
new file mode 100644
index 00000000..0ff6e795
--- /dev/null
+++ b/changes/772-controllers-rigs.md
@@ -0,0 +1 @@
+- `67js/addons/player` adds vehicle and free-flight controllers, orbit, chase and side-scroller camera rigs, `createCameraClip` (camera pull-in against walls and ground), and a registry (`registerController`, `registerCameraRig`, `replaceController`, `replaceCameraRig`) for custom kinds and runtime swaps (#772)
diff --git a/docs/player.md b/docs/player.md
index c3026595..bc299f0b 100644
--- a/docs/player.md
+++ b/docs/player.md
@@ -67,6 +67,40 @@ A rig follows a `subject`: a controller's `state` or any `{ position: [x, y, z],
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`.
+## Vehicle and flight controllers
+
+Both read the same input names as the character controller, use the same `mover` seam, `node`, `position`, `yaw`, `teleport` and `positionAt`, and expose `state` for animation and audio.
+
+`createVehicleController(options)`: an arcade car. `moveForward` is the throttle (negative reverses), `moveX` steers and the `jump` action brakes (rename them with `throttle`, `steer`, `brake`). Steering is a bicycle model: yaw rate is `speed / wheelbase * tan(steer)`. A wall removes the speed it blocks. Options: `maximumSpeed` (20), `reverseSpeed` (6), `acceleration` (12), `brakeDeceleration` (25), `coastDeceleration` (4), `wheelbase` (2.5), `maximumSteer` (0.6 rad), `steerSeconds` (0.15), `gravity`, `radius` (1), `height`, `stepHeight` (0.4). State: `forwardSpeed` (signed), `speed`, `steer` (-1 to 1, for wheel animation with [createVehicleRig](vehicle.md)), `yaw`, `grounded`, `airborne`, `braking`.
+
+`createFlightController(options)`: free flight along the nose. `moveX` yaws, `moveForward` pitches (positive climbs), `run` boosts and `jump` brakes (`yawAxis`, `pitchAxis`, `boost`, `brake`). Speed eases between `brakeSpeed` (6), `cruiseSpeed` (14) and `boostSpeed` (24); pitch levels out after `levelSeconds` (0.6) with no input and is limited to `maximumPitch` (1.2). A wall stops it, the ground is skimmed, and a box that starts above its height is flown under. State: `pitch`, `roll` (bank, for animation), `speed`, `velocity`, `boosting`, `grounded`.
+
+## More camera rigs
+
+- `createOrbitCamera`: free look around the subject at `distance` (6). Name a `zoom` axis to change the distance between `minimumDistance` (1) and `maximumDistance` (50) at `zoomSpeed` (8) units per second.
+- `createChaseCamera`: behind the subject like the follow rig, but the yaw swings round to `subject.yaw` over `yawFollowSeconds` (0.3). Use it for cars and flyers. It does not take look input unless you name `lookX`.
+- `createSideScrollerCamera`: `distance` (10) away on +Z looking along -Z, at the subject's height plus `lookHeight` (1), leading the subject by up to `lookAhead` (2) units along its horizontal `velocity`.
+
+### Camera collision
+
+`createCameraClip({ obstacles, ground, padding })` returns a `clipEye(target, eye)` for any orbiting rig. It pulls the eye along the line to the target until it is `padding` (0.25) outside every obstacle box and above the ground, so the camera never ends up inside a wall or under the floor. A body pressed within `padding` of a wall leaves the camera at the target.
+
+```js
+const clip = createCameraClip({ obstacles, ground });
+const camera = createChaseCamera({ subject: car.state, clipEye: clip });
+```
+
+## Custom kinds and swapping
+
+`registerController(kind, factory)` and `registerCameraRig(kind, factory)` add a kind (up to 64 names, built-ins cannot be replaced). A controller factory returns a runtime system with `state.position` and a `fixedUpdate` or `update` function; a rig factory returns a system with `subject` and `pose(context) => { eye, target, up }`. `createController(kind, options)` and `createCameraRigOfKind(kind, options)` build one by name; `listControllerKinds()` and `listCameraRigKinds()` list them (`character`, `vehicle`, `flight`; `follow`, `firstPerson`, `topDown`, `orbit`, `chase`, `sideScroller`).
+
+`replaceController(runtime, name, kind, options)` swaps the controller system for another kind at the same position and yaw. `replaceCameraRig(runtime, name, kind, options)` swaps the rig and keeps its subject and yaw. After a controller swap, point the rig at the new `state`:
+
+```js
+const car = replaceController(runtime, 'player', 'vehicle', { input });
+replaceCameraRig(runtime, 'camera', 'chase', { subject: car.state, input });
+```
+
## 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`:
diff --git a/src/player.js b/src/player.js
index 29aed19f..43b5c48d 100644
--- a/src/player.js
+++ b/src/player.js
@@ -184,10 +184,7 @@ export function createCharacterController(options = {}) {
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 node = validateNode(owner, options.node);
const startPosition = vectorOption(owner, 'position', options.position, [0, 0, 0]);
const state = {
@@ -203,11 +200,7 @@ export function createCharacterController(options = {}) {
};
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;
+ writeNodePose(node, state.position, state.yaw);
}
function currentCameraYaw() {
@@ -316,6 +309,9 @@ 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 },
+ orbit: { pitch: 0.4, minimumPitch: -1.4, maximumPitch: 1.4, distance: 6, lookHeight: 1, followSeconds: 0.05, lookAxes: true },
+ chase: { pitch: 0.25, minimumPitch: -0.2, maximumPitch: 1.3, distance: 7, lookHeight: 1.2, followSeconds: 0.1, lookAxes: false, yawFollowSeconds: 0.3 },
+ sideScroller: { pitch: 0, minimumPitch: 0, maximumPitch: 0, distance: 10, lookHeight: 1, followSeconds: 0.25, lookAxes: false, lookAhead: 2 },
});
function placeCamera(kind, rig, focus) {
@@ -327,7 +323,11 @@ function placeCamera(kind, rig, focus) {
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.
+ if (kind === 'sideScroller') {
+ const sideTarget = [focus[0], focus[1] + rig.lookHeight, focus[2]];
+ return { eye: [sideTarget[0], sideTarget[1], sideTarget[2] + rig.distance], target: sideTarget };
+ }
+ // follow, topDown, orbit and chase 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);
@@ -347,11 +347,16 @@ function createCameraRig(kind, options) {
}
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 input = wantsLook || lookNames.y || options.zoom ? 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 yawFollowSeconds = numberOption(owner, 'yawFollowSeconds', options.yawFollowSeconds, defaults.yawFollowSeconds ?? 0, 0, 10);
+ const zoomName = options.zoom ?? null;
+ const minimumDistance = numberOption(owner, 'minimumDistance', options.minimumDistance, 1, 0.1, PLAYER_LIMITS.maximumDistance);
+ const maximumDistance = numberOption(owner, 'maximumDistance', options.maximumDistance, 50, minimumDistance, PLAYER_LIMITS.maximumDistance);
+ const zoomSpeed = numberOption(owner, 'zoomSpeed', options.zoomSpeed, 8, 0, 1000);
const rig = {
name: options.name ?? 'camera',
kind,
@@ -362,6 +367,7 @@ function createCameraRig(kind, options) {
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,
+ lookAhead: numberOption(owner, 'lookAhead', options.lookAhead, defaults.lookAhead ?? 0, 0, PLAYER_LIMITS.maximumDistance),
focus: [...subject.position],
previousFocus: [...subject.position],
};
@@ -373,13 +379,28 @@ function createCameraRig(kind, options) {
if (lookNames.y) {
rig.pitch = clamp(rig.pitch + input.getAxis(lookNames.y) * lookSpeed * stepSeconds, minimumPitch, maximumPitch);
}
+ if (zoomName !== null) {
+ rig.distance = clamp(rig.distance - input.getAxis(zoomName) * zoomSpeed * stepSeconds, minimumDistance, maximumDistance);
+ }
+ if (yawFollowSeconds > 0) {
+ const yawAmount = 1 - Math.exp(-stepSeconds / yawFollowSeconds);
+ rig.yaw = wrapAngle(rig.yaw + wrapAngle((rig.subject.yaw ?? rig.yaw) - rig.yaw) * yawAmount);
+ }
rig.previousFocus = rig.focus;
const amount = followSeconds === 0 ? 1 : 1 - Math.exp(-stepSeconds / followSeconds);
- rig.focus = blend(rig.focus, rig.subject.position, amount);
+ rig.focus = blend(rig.focus, focusGoal(), amount);
+ }
+
+ // A side scroller leads the subject along its horizontal velocity so the view shows where it is heading.
+ function focusGoal() {
+ const goal = rig.subject.position;
+ if (kind !== 'sideScroller' || rig.lookAhead === 0) return goal;
+ const sideSpeed = rig.subject.velocity?.[0] ?? 0;
+ return [goal[0] + rig.lookAhead * clamp(sideSpeed / 5, -1, 1), goal[1], goal[2]];
}
rig.init = () => {
- rig.focus = [...rig.subject.position];
+ rig.focus = [...focusGoal()];
rig.previousFocus = [...rig.focus];
};
rig.fixedUpdate = advance;
@@ -409,3 +430,433 @@ export function createFirstPersonCamera(options = {}) {
export function createTopDownCamera(options = {}) {
return createCameraRig('topDown', options);
}
+
+// Orbit camera: free look around the subject; name a `zoom` axis to change the distance between minimumDistance and maximumDistance.
+export function createOrbitCamera(options = {}) {
+ return createCameraRig('orbit', options);
+}
+
+// Chase camera: sits behind the subject and swings round to its yaw (yawFollowSeconds), for vehicles and flyers.
+export function createChaseCamera(options = {}) {
+ return createCameraRig('chase', options);
+}
+
+// Side-scroller camera: looks along -Z from `distance` away and leads the subject by `lookAhead` units along its horizontal velocity.
+export function createSideScrollerCamera(options = {}) {
+ return createCameraRig('sideScroller', options);
+}
+
+// A clipEye for any orbiting rig: pulls the camera in along the line from its target so the eye stays `padding` outside every
+// obstacle box and above the ground, and so never shows the inside of a wall.
+export function createCameraClip(options = {}) {
+ const owner = 'createCameraClip';
+ const padding = numberOption(owner, 'padding', options.padding, 0.25, 0, 10);
+ const boxes = validateObstacles(options.obstacles ?? []).map(({ min, max }) => ({
+ min: min.map(value => value - padding),
+ max: max.map(value => value + padding),
+ }));
+ const ground = options.ground ?? 0;
+ if (typeof ground !== 'function' && !Number.isFinite(ground)) {
+ throw new TypeError(`${owner} ground must be a height number or a function (x, z) => height, got ${describe(ground)}.`);
+ }
+ const groundHeight = (x, z) => (typeof ground === 'function' ? ground(x, z) : ground);
+
+ // Fraction of the segment target -> eye that is free of the padded box (1 when it never enters it).
+ function freeFraction(target, offset, box) {
+ let entry = 0;
+ let exit = 1;
+ for (let axis = 0; axis < 3; axis += 1) {
+ if (offset[axis] === 0) {
+ if (target[axis] < box.min[axis] || target[axis] > box.max[axis]) return 1;
+ continue;
+ }
+ const first = (box.min[axis] - target[axis]) / offset[axis];
+ const second = (box.max[axis] - target[axis]) / offset[axis];
+ entry = Math.max(entry, Math.min(first, second));
+ exit = Math.min(exit, Math.max(first, second));
+ }
+ return entry > exit || exit < 0 ? 1 : entry;
+ }
+
+ function underGround(target, offset, fraction) {
+ const x = target[0] + offset[0] * fraction;
+ const z = target[2] + offset[2] * fraction;
+ return target[1] + offset[1] * fraction < groundHeight(x, z) + padding;
+ }
+
+ return function clipEye(target, eye) {
+ const offset = eye.map((value, axis) => value - target[axis]);
+ let fraction = 1;
+ for (const box of boxes) fraction = Math.min(fraction, freeFraction(target, offset, box));
+ const samples = 24;
+ for (let sample = 1; sample <= samples; sample += 1) {
+ const sampleFraction = (fraction * sample) / samples;
+ if (!underGround(target, offset, sampleFraction)) continue;
+ let low = (fraction * (sample - 1)) / samples;
+ let high = sampleFraction;
+ for (let round = 0; round < 8; round += 1) {
+ const middle = (low + high) / 2;
+ if (underGround(target, offset, middle)) high = middle;
+ else low = middle;
+ }
+ fraction = low;
+ break;
+ }
+ return target.map((value, axis) => value + offset[axis] * fraction);
+ };
+}
+
+function validateNode(owner, 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)}.`);
+ }
+ return node;
+}
+
+function writeNodePose(node, position, yaw) {
+ if (!node) return;
+ node.position[0] = position[0];
+ node.position[1] = position[1];
+ node.position[2] = position[2];
+ if ('rotationY' in node) node.rotationY = -yaw;
+}
+
+// Runtime-system shell shared by the vehicle and flight controllers.
+function finishController(parts) {
+ const { state, writeNode, advance, teleport } = parts;
+ const controller = {
+ name: parts.name,
+ kind: parts.kind,
+ state,
+ positionAt: alpha => blend(state.previousPosition, state.position, alpha),
+ teleport(position, yaw) {
+ teleport(position, yaw);
+ writeNode();
+ return controller;
+ },
+ init: writeNode,
+ fixedUpdate: advance,
+ update(deltaSeconds, context) {
+ if (context?.mode === 'variable') advance(deltaSeconds);
+ },
+ };
+ return controller;
+}
+
+function vehicleSettings(owner, options) {
+ const speedLimit = PLAYER_LIMITS.maximumSpeed;
+ const accelerationLimit = PLAYER_LIMITS.maximumAcceleration;
+ return {
+ maximumSpeed: numberOption(owner, 'maximumSpeed', options.maximumSpeed, 20, 0, speedLimit),
+ reverseSpeed: numberOption(owner, 'reverseSpeed', options.reverseSpeed, 6, 0, speedLimit),
+ acceleration: numberOption(owner, 'acceleration', options.acceleration, 12, 0.01, accelerationLimit),
+ brakeDeceleration: numberOption(owner, 'brakeDeceleration', options.brakeDeceleration, 25, 0.01, accelerationLimit),
+ coastDeceleration: numberOption(owner, 'coastDeceleration', options.coastDeceleration, 4, 0, accelerationLimit),
+ wheelbase: numberOption(owner, 'wheelbase', options.wheelbase, 2.5, 0.1, PLAYER_LIMITS.maximumRadius),
+ maximumSteer: numberOption(owner, 'maximumSteer', options.maximumSteer, 0.6, 0.01, 1.4),
+ steerSeconds: numberOption(owner, 'steerSeconds', options.steerSeconds, 0.15, 0.001, 10),
+ gravity: numberOption(owner, 'gravity', options.gravity, 20, 0, PLAYER_LIMITS.maximumGravity),
+ radius: numberOption(owner, 'radius', options.radius, 1, 0.01, PLAYER_LIMITS.maximumRadius),
+ height: numberOption(owner, 'height', options.height, 1.5, 0.01, PLAYER_LIMITS.maximumHeight),
+ stepHeight: numberOption(owner, 'stepHeight', options.stepHeight, 0.4, 0, PLAYER_LIMITS.maximumHeight),
+ };
+}
+
+// Arcade car: throttle axis (moveForward), steer axis (moveX) and a brake action (jump). Steering follows a bicycle model, so the yaw
+// rate is speed / wheelbase * tan(steer). The same mover seam as the character controller keeps it on the ground and off the walls.
+// state.steer runs -1..1 and state.forwardSpeed is signed, for wheel and engine animation (createVehicleRig) and audio.
+export function createVehicleController(options = {}) {
+ const owner = 'createVehicleController';
+ const input = requireInput(owner, options.input);
+ const mover = validateMover(owner, options.mover ?? createKinematicMover({ ground: options.ground, obstacles: options.obstacles }));
+ const settings = vehicleSettings(owner, options);
+ const names = { steer: options.steer ?? 'moveX', throttle: options.throttle ?? 'moveForward', brake: options.brake ?? 'jump' };
+ const node = validateNode(owner, options.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),
+ forwardSpeed: 0,
+ speed: 0,
+ steer: 0,
+ grounded: false,
+ airborne: true,
+ braking: false,
+ };
+
+ function writeNode() {
+ writeNodePose(node, state.position, state.yaw);
+ }
+
+ function approachSpeed(target, rate, stepSeconds) {
+ const maximumChange = rate * stepSeconds;
+ state.forwardSpeed += clamp(target - state.forwardSpeed, -maximumChange, maximumChange);
+ }
+
+ function updateSpeed(throttle, stepSeconds) {
+ state.braking = input.isHeld(names.brake);
+ if (state.braking) {
+ approachSpeed(0, settings.brakeDeceleration, stepSeconds);
+ } else if (throttle > 0) {
+ const rate = state.forwardSpeed < 0 ? settings.brakeDeceleration : settings.acceleration;
+ approachSpeed(throttle * settings.maximumSpeed, rate, stepSeconds);
+ } else if (throttle < 0) {
+ const rate = state.forwardSpeed > 0.1 ? settings.brakeDeceleration : settings.acceleration;
+ approachSpeed(throttle * settings.reverseSpeed, rate, stepSeconds);
+ } else {
+ approachSpeed(0, settings.coastDeceleration, stepSeconds);
+ }
+ }
+
+ function advance(stepSeconds) {
+ state.previousPosition = [...state.position];
+ updateSpeed(clamp(input.getAxis(names.throttle), -1, 1), stepSeconds);
+ const steerWanted = clamp(input.getAxis(names.steer), -1, 1);
+ state.steer += (steerWanted - state.steer) * (1 - Math.exp(-stepSeconds / settings.steerSeconds));
+ const yawRate = (state.forwardSpeed / settings.wheelbase) * Math.tan(state.steer * settings.maximumSteer);
+ state.yaw = wrapAngle(state.yaw + yawRate * stepSeconds);
+
+ const heading = forwardDirection(state.yaw);
+ const verticalSpeed = state.grounded ? 0 : Math.max(-PLAYER_LIMITS.maximumSpeed, state.velocity[1] - settings.gravity * stepSeconds);
+ const displacement = [heading[0] * state.forwardSpeed * stepSeconds, verticalSpeed * stepSeconds, heading[2] * state.forwardSpeed * stepSeconds];
+ const body = {
+ position: [...state.position],
+ velocity: [...state.velocity],
+ grounded: state.grounded,
+ radius: settings.radius,
+ height: settings.height,
+ stepHeight: settings.stepHeight,
+ };
+ const result = readMoveResult(owner, mover.move(body, displacement, stepSeconds));
+ const movedX = (result.position[0] - state.position[0]) / stepSeconds;
+ const movedZ = (result.position[2] - state.position[2]) / stepSeconds;
+ // A wall removes the speed it blocks: the car keeps only the part of the move that really happened.
+ state.forwardSpeed = movedX * heading[0] + movedZ * heading[2];
+ state.velocity = [movedX, result.grounded ? 0 : verticalSpeed, movedZ];
+ state.position = [...result.position];
+ state.grounded = result.grounded;
+ state.airborne = !result.grounded;
+ state.speed = Math.abs(state.forwardSpeed);
+ writeNode();
+ }
+
+ return finishController({
+ name: options.name ?? 'vehicle',
+ kind: 'vehicle',
+ state,
+ writeNode,
+ advance,
+ teleport(position, yaw) {
+ state.position = vectorOption(owner, 'teleport position', position);
+ state.previousPosition = [...state.position];
+ state.velocity = [0, 0, 0];
+ state.forwardSpeed = 0;
+ state.yaw = numberOption(owner, 'teleport yaw', yaw, state.yaw, -1000, 1000);
+ state.grounded = false;
+ state.airborne = true;
+ },
+ });
+}
+
+function flightSettings(owner, options) {
+ const speedLimit = PLAYER_LIMITS.maximumSpeed;
+ const maximumPitch = numberOption(owner, 'maximumPitch', options.maximumPitch, 1.2, 0, PLAYER_LIMITS.maximumPitch);
+ return {
+ cruiseSpeed: numberOption(owner, 'cruiseSpeed', options.cruiseSpeed, 14, 0, speedLimit),
+ boostSpeed: numberOption(owner, 'boostSpeed', options.boostSpeed, 24, 0, speedLimit),
+ brakeSpeed: numberOption(owner, 'brakeSpeed', options.brakeSpeed, 6, 0, speedLimit),
+ acceleration: numberOption(owner, 'acceleration', options.acceleration, 10, 0.01, PLAYER_LIMITS.maximumAcceleration),
+ turnRate: numberOption(owner, 'turnRate', options.turnRate, 1.4, 0, 20),
+ pitchRate: numberOption(owner, 'pitchRate', options.pitchRate, 1.1, 0, 20),
+ maximumPitch,
+ levelSeconds: numberOption(owner, 'levelSeconds', options.levelSeconds, 0.6, 0.001, 100),
+ radius: numberOption(owner, 'radius', options.radius, 0.8, 0.01, PLAYER_LIMITS.maximumRadius),
+ height: numberOption(owner, 'height', options.height, 0.6, 0.01, PLAYER_LIMITS.maximumHeight),
+ };
+}
+
+// Free flight: yaw axis (moveX), pitch axis (moveForward, positive climbs), boost action (run) and brake action (jump). The flyer
+// always moves along its nose at a speed that eases between brakeSpeed, cruiseSpeed and boostSpeed, levels out when the pitch axis
+// is idle and reports a bank angle in state.roll for animation. Walls stop it through the mover seam; it skims the ground.
+export function createFlightController(options = {}) {
+ const owner = 'createFlightController';
+ const input = requireInput(owner, options.input);
+ const mover = validateMover(owner, options.mover ?? createKinematicMover({ ground: options.ground, obstacles: options.obstacles }));
+ const settings = flightSettings(owner, options);
+ const names = {
+ yaw: options.yawAxis ?? 'moveX',
+ pitch: options.pitchAxis ?? 'moveForward',
+ boost: options.boost ?? 'run',
+ brake: options.brake ?? 'jump',
+ };
+ const node = validateNode(owner, options.node);
+ const startPosition = vectorOption(owner, 'position', options.position, [0, 10, 0]);
+ const state = {
+ position: startPosition,
+ previousPosition: [...startPosition],
+ velocity: [0, 0, 0],
+ yaw: numberOption(owner, 'yaw', options.yaw, 0, -1000, 1000),
+ pitch: numberOption(owner, 'pitch', options.pitch, 0, -settings.maximumPitch, settings.maximumPitch),
+ roll: 0,
+ speed: settings.cruiseSpeed,
+ grounded: false,
+ airborne: true,
+ boosting: false,
+ };
+
+ function writeNode() {
+ writeNodePose(node, state.position, state.yaw);
+ if (node && 'rotationX' in node) node.rotationX = state.pitch;
+ if (node && 'rotationZ' in node) node.rotationZ = state.roll;
+ }
+
+ function steer(stepSeconds) {
+ const yawInput = clamp(input.getAxis(names.yaw), -1, 1);
+ const pitchInput = clamp(input.getAxis(names.pitch), -1, 1);
+ state.yaw = wrapAngle(state.yaw + yawInput * settings.turnRate * stepSeconds);
+ if (pitchInput !== 0) state.pitch += pitchInput * settings.pitchRate * stepSeconds;
+ else state.pitch -= state.pitch * (1 - Math.exp(-stepSeconds / settings.levelSeconds));
+ state.pitch = clamp(state.pitch, -settings.maximumPitch, settings.maximumPitch);
+ state.roll += (-yawInput * 0.6 - state.roll) * (1 - Math.exp(-stepSeconds / 0.2));
+ }
+
+ function updateSpeed(stepSeconds) {
+ state.boosting = input.isHeld(names.boost);
+ let wantedSpeed = settings.cruiseSpeed;
+ if (input.isHeld(names.brake)) wantedSpeed = settings.brakeSpeed;
+ else if (state.boosting) wantedSpeed = settings.boostSpeed;
+ const maximumChange = settings.acceleration * stepSeconds;
+ state.speed += clamp(wantedSpeed - state.speed, -maximumChange, maximumChange);
+ }
+
+ function advance(stepSeconds) {
+ state.previousPosition = [...state.position];
+ steer(stepSeconds);
+ updateSpeed(stepSeconds);
+ const horizontal = Math.cos(state.pitch);
+ const direction = [Math.sin(state.yaw) * horizontal, Math.sin(state.pitch), -Math.cos(state.yaw) * horizontal];
+ const displacement = direction.map(component => component * state.speed * stepSeconds);
+ const body = {
+ position: [...state.position],
+ velocity: [...state.velocity],
+ grounded: false,
+ radius: settings.radius,
+ height: settings.height,
+ stepHeight: 0,
+ };
+ const result = readMoveResult(owner, mover.move(body, displacement, stepSeconds));
+ state.velocity = result.position.map((value, axis) => (value - state.position[axis]) / stepSeconds);
+ state.position = [...result.position];
+ state.grounded = result.grounded;
+ state.airborne = !result.grounded;
+ if (state.grounded && state.pitch < 0) state.pitch = 0;
+ writeNode();
+ }
+
+ return finishController({
+ name: options.name ?? 'flyer',
+ kind: 'flight',
+ state,
+ writeNode,
+ advance,
+ teleport(position, yaw) {
+ state.position = vectorOption(owner, 'teleport position', position);
+ state.previousPosition = [...state.position];
+ state.velocity = [0, 0, 0];
+ state.yaw = numberOption(owner, 'teleport yaw', yaw, state.yaw, -1000, 1000);
+ state.pitch = 0;
+ state.grounded = false;
+ state.airborne = true;
+ },
+ });
+}
+
+const MAXIMUM_REGISTERED_KINDS = 64;
+const controllerFactories = new Map([
+ ['character', createCharacterController],
+ ['vehicle', createVehicleController],
+ ['flight', createFlightController],
+]);
+const rigFactories = new Map([
+ ['follow', createFollowCamera],
+ ['firstPerson', createFirstPersonCamera],
+ ['topDown', createTopDownCamera],
+ ['orbit', createOrbitCamera],
+ ['chase', createChaseCamera],
+ ['sideScroller', createSideScrollerCamera],
+]);
+
+function register(owner, registry, kind, factory) {
+ if (typeof kind !== 'string' || kind.length === 0 || kind.length > 64) {
+ throw new TypeError(`${owner} kind must be a non-empty string of at most 64 characters, such as "boat", got ${describe(kind)}.`);
+ }
+ if (typeof factory !== 'function') {
+ throw new TypeError(`${owner} factory for "${kind}" must be a function (options) => runtime system, got ${describe(factory)}.`);
+ }
+ if (registry.has(kind)) throw new RangeError(`${owner} kind "${kind}" is already registered. Pick another name; kinds cannot be replaced.`);
+ if (registry.size >= MAXIMUM_REGISTERED_KINDS) throw new RangeError(`${owner} holds at most ${MAXIMUM_REGISTERED_KINDS} kinds.`);
+ registry.set(kind, factory);
+}
+
+function build(owner, registry, kind, options) {
+ const factory = registry.get(kind);
+ if (!factory) throw new RangeError(`${owner} has no kind "${kind}". Registered kinds: ${[...registry.keys()].join(', ')}.`);
+ return factory(options);
+}
+
+// Game code adds its own controller kind (a boat, a ball): factory(options) returns a runtime system with state.position.
+export function registerController(kind, factory) {
+ register('registerController', controllerFactories, kind, factory);
+}
+
+// A custom camera rig kind: factory(options) returns a runtime system with subject and pose(context) => { eye, target, up }.
+export function registerCameraRig(kind, factory) {
+ register('registerCameraRig', rigFactories, kind, factory);
+}
+
+export function listControllerKinds() {
+ return [...controllerFactories.keys()];
+}
+
+export function listCameraRigKinds() {
+ return [...rigFactories.keys()];
+}
+
+export function createController(kind, options = {}) {
+ const controller = build('createController', controllerFactories, kind, options);
+ const hasState = controller?.state && Array.isArray(controller.state.position);
+ if (!hasState || (typeof controller.fixedUpdate !== 'function' && typeof controller.update !== 'function')) {
+ throw new TypeError(`createController kind "${kind}" must return a runtime system with state.position and a fixedUpdate or update function.`);
+ }
+ return controller;
+}
+
+export function createCameraRigOfKind(kind, options = {}) {
+ const rig = build('createCameraRigOfKind', rigFactories, kind, options);
+ if (typeof rig?.pose !== 'function') {
+ throw new TypeError(`createCameraRigOfKind kind "${kind}" must return a rig with pose(context) giving { eye, target, up }.`);
+ }
+ return rig;
+}
+
+// Swap the controller system `name` for another kind while the game runs. It starts where the old one stood, facing the same way,
+// unless options say otherwise. Rigs that follow `state` must be pointed at the returned controller (see replaceCameraRig).
+export function replaceController(runtime, name, kind, options = {}) {
+ const previous = runtime.getSystem(name);
+ if (!previous?.state) throw new RangeError(`replaceController found no controller system named "${name}" in the runtime.`);
+ const carried = { position: [...previous.state.position], yaw: previous.state.yaw, name };
+ const controller = createController(kind, { ...carried, ...options });
+ runtime.replaceSystem(name, controller);
+ return controller;
+}
+
+// Swap the camera rig system `name` for another kind. It keeps the old subject and yaw unless options name others.
+export function replaceCameraRig(runtime, name, kind, options = {}) {
+ const previous = runtime.getSystem(name);
+ if (!previous?.subject) throw new RangeError(`replaceCameraRig found no camera rig system named "${name}" in the runtime.`);
+ const rig = createCameraRigOfKind(kind, { subject: previous.subject, yaw: previous.yaw, name, ...options });
+ runtime.replaceSystem(name, rig);
+ return rig;
+}
diff --git a/tests/player-rigs.test.js b/tests/player-rigs.test.js
new file mode 100644
index 00000000..cb8996f1
--- /dev/null
+++ b/tests/player-rigs.test.js
@@ -0,0 +1,290 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createInput } from '../src/input.js';
+import {
+ createCameraClip, createCameraRigOfKind, createChaseCamera, createCharacterController, createController, createFlightController,
+ createFollowCamera, createOrbitCamera, createSideScrollerCamera, createVehicleController, listCameraRigKinds, listControllerKinds,
+ registerCameraRig, registerController, replaceCameraRig, replaceController,
+} from '../src/player.js';
+import { createRuntime } from '../src/runtime.js';
+
+const STEP_MILLISECONDS = 1000 / 60;
+const fakeRenderer = { render: () => {} };
+const scheduler = { request: () => 1, cancel: () => {} };
+
+// Test course along -Z: stairs (z -4 to -6, 0.3 per step), a platform (z -6 to -9, 1.2 high), a gap (z -9 to -11), a ramp
+// (z -11 to -16 rising to 1.5) and a wall at z -20 (5 high, 6 wide).
+const STAIRS = [0, 1, 2, 3].map(index => ({
+ min: [-2, 0, -4 - 0.5 * (index + 1)],
+ max: [2, 0.3 * (index + 1), -4 - 0.5 * index],
+}));
+const PLATFORM = { min: [-2, 0, -9], max: [2, 1.2, -6] };
+const WALL = { min: [-3, 0, -21], max: [3, 5, -20] };
+const OBSTACLES = [...STAIRS, PLATFORM, WALL];
+
+function courseGround(x, z) {
+ if (z < -9 && z >= -11) return -50;
+ if (z < -11 && z >= -16) return (-11 - z) * 0.3;
+ if (z < -16) return 1.5;
+ return 0;
+}
+
+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(makeController, makeRig) {
+ const input = createScriptedInput();
+ const controller = makeController(input);
+ const systems = [input, controller];
+ const rig = makeRig ? makeRig(controller, input) : null;
+ if (rig) systems.push(rig);
+ const runtime = createRuntime(fakeRenderer, { mode: 'fixed', fixedStepSeconds: 1 / 60, systems, scheduler });
+ return { input, controller, rig, runtime };
+}
+
+function stepOnce(game, beforeStep) {
+ beforeStep?.();
+ game.runtime.step(STEP_MILLISECONDS);
+}
+
+function insideAnyBox(point, boxes) {
+ return boxes.some(({ min, max }) => point.every((value, axis) => value > min[axis] && value < max[axis]));
+}
+
+test('the character clears stairs, a gap and a ramp, stops at the wall, and the camera never enters it', () => {
+ const clip = createCameraClip({ obstacles: OBSTACLES, ground: courseGround });
+ const game = createGame(
+ input => createCharacterController({ input, position: [0, 0, -1], ground: courseGround, obstacles: OBSTACLES, runSpeed: 6 }),
+ (controller, input) => createFollowCamera({ subject: controller.state, input, yaw: Math.PI, clipEye: clip, followSeconds: 0 }),
+ );
+ const { input, controller, rig } = game;
+ input.press('script/forward');
+ input.press('script/run');
+ let jumpedAcrossGap = false;
+ let reachedPlatform = false;
+ let landedBeyondGap = false;
+ let lowestY = Infinity;
+ for (let index = 0; index < 600; index += 1) {
+ stepOnce(game, () => {
+ if (controller.state.position[2] < -8.4 && controller.state.grounded && !jumpedAcrossGap) {
+ jumpedAcrossGap = true;
+ input.press('script/jump');
+ } else {
+ input.release('script/jump');
+ }
+ });
+ const [x, y, z] = controller.state.position;
+ lowestY = Math.min(lowestY, y);
+ if (y >= 1.19 && z < -6.5) reachedPlatform = true;
+ if (z < -11.5 && controller.state.grounded) landedBeyondGap = true;
+ assert.ok(z > -20 + 0.4 - 1e-6, `tunnelled into the wall: z ${z} at step ${index}`);
+ const { eye } = rig.pose({ alpha: 1 });
+ assert.equal(insideAnyBox(eye, OBSTACLES), false, `camera inside a box at step ${index}: ${eye}`);
+ assert.ok(eye[1] >= courseGround(eye[0], eye[2]), `camera under the ground at step ${index}`);
+ assert.ok(Number.isFinite(x));
+ }
+ assert.ok(rig.pose({ alpha: 1 }).eye[2] > -20, 'the camera should be pulled in front of the wall, not left behind it');
+ assert.ok(reachedPlatform, 'never stood on the platform');
+ assert.ok(landedBeyondGap, 'never landed beyond the gap');
+ assert.ok(lowestY > -1, `fell into the gap (lowest y ${lowestY})`);
+ assert.ok(controller.state.position[2] > -19.7 && controller.state.position[2] < -19.5, `ended at z ${controller.state.position[2]}`);
+});
+
+test('the clip pulls the camera in front of a wall it would sit behind', () => {
+ const clip = createCameraClip({ obstacles: [WALL], padding: 0.25 });
+ const eye = clip([0, 1.5, -19.5], [0, 2, -24.5]);
+ assert.ok(eye[2] > -20 && eye[2] < -19.5, `eye z was ${eye[2]}`);
+ assert.deepEqual(clip([0, 1.5, -10], [0, 2, -5]), [0, 2, -5]);
+});
+
+test('the clip keeps the camera above sloped ground', () => {
+ const clip = createCameraClip({ ground: (x, z) => 3 + 0 * x * z, padding: 0.5 });
+ const eye = clip([0, 5, 0], [0, 0, 6]);
+ assert.ok(eye[1] >= 3.5 - 0.05, `eye y was ${eye[1]}`);
+});
+
+test('the car drives the course on its own controller and chase camera and stops at the wall', () => {
+ const clip = createCameraClip({ obstacles: OBSTACLES, ground: courseGround });
+ const game = createGame(
+ input => createVehicleController({ input, position: [0, 0, 6], ground: courseGround, obstacles: OBSTACLES }),
+ (controller, input) => createChaseCamera({ subject: controller.state, input, clipEye: clip }),
+ );
+ const { input, controller, rig } = game;
+ input.press('script/forward');
+ let topSpeed = 0;
+ let crossedGap = false;
+ for (let index = 0; index < 900; index += 1) {
+ stepOnce(game);
+ topSpeed = Math.max(topSpeed, controller.state.speed);
+ if (controller.state.position[2] < -11.5) crossedGap = true;
+ assert.ok(controller.state.position[1] > -1, `car fell into the gap at step ${index}`);
+ assert.equal(insideAnyBox(rig.pose({ alpha: 1 }).eye, OBSTACLES), false, `camera inside a box at step ${index}`);
+ }
+ assert.ok(topSpeed > 15, `top speed was ${topSpeed}`);
+ assert.ok(crossedGap, 'the car never crossed the gap');
+ assert.ok(controller.state.position[2] > -20 + 1 - 1e-6, `car went into the wall: z ${controller.state.position[2]}`);
+ assert.ok(controller.state.speed < 0.5, `car still moving at ${controller.state.speed}`);
+});
+
+test('the car steers with a bicycle model, reverses and brakes', () => {
+ const game = createGame(input => createVehicleController({ input }));
+ const { input, controller } = game;
+ input.press('script/forward');
+ for (let index = 0; index < 120; index += 1) stepOnce(game);
+ assert.ok(controller.state.forwardSpeed > 19);
+ const yawBefore = controller.state.yaw;
+ input.press('script/right');
+ for (let index = 0; index < 30; index += 1) stepOnce(game);
+ assert.ok(controller.state.yaw > yawBefore + 0.2, 'right steer should turn toward +X');
+ assert.ok(controller.state.steer > 0.9);
+ input.release('script/right');
+ input.release('script/forward');
+ input.press('script/jump');
+ for (let index = 0; index < 60; index += 1) stepOnce(game);
+ assert.equal(controller.state.braking, true);
+ assert.ok(Math.abs(controller.state.forwardSpeed) < 1e-6);
+ input.release('script/jump');
+ input.press('script/back');
+ for (let index = 0; index < 120; index += 1) stepOnce(game);
+ assert.ok(controller.state.forwardSpeed < -5.9);
+});
+
+test('the flyer climbs over the wall with its own controller and chase camera', () => {
+ const clip = createCameraClip({ obstacles: OBSTACLES, ground: courseGround });
+ const game = createGame(
+ input => createFlightController({ input, position: [0, 3, 4], ground: courseGround, obstacles: OBSTACLES }),
+ (controller, input) => createChaseCamera({ subject: controller.state, input, clipEye: clip }),
+ );
+ const { input, controller, rig } = game;
+ let highestY = 0;
+ for (let index = 0; index < 330; index += 1) {
+ stepOnce(game, () => {
+ if (index < 40) input.press('script/forward');
+ else input.release('script/forward');
+ });
+ highestY = Math.max(highestY, controller.state.position[1]);
+ assert.equal(insideAnyBox(rig.pose({ alpha: 1 }).eye, OBSTACLES), false, `camera inside a box at step ${index}`);
+ }
+ assert.ok(highestY > 6, `highest y was ${highestY}`);
+ assert.ok(controller.state.position[2] < -25, `flyer stopped at z ${controller.state.position[2]}`);
+ assert.equal(controller.state.airborne, true);
+});
+
+test('the flyer stops at the wall when it flies into it low, and skims the ground', () => {
+ const game = createGame(input => createFlightController({ input, position: [0, 2, 0], ground: (x, z) => (z < -9 ? 0 : 0), obstacles: [WALL], cruiseSpeed: 10 }));
+ const { controller } = game;
+ for (let index = 0; index < 480; index += 1) stepOnce(game);
+ assert.ok(controller.state.position[2] > -20 + 0.8 - 1e-6, `flew through the wall: z ${controller.state.position[2]}`);
+ assert.ok(controller.state.velocity[2] > -0.01, 'still moving into the wall');
+ controller.teleport([0, 2, 5], 0);
+ game.input.press('script/back');
+ for (let index = 0; index < 90; index += 1) stepOnce(game);
+ assert.equal(controller.state.grounded, true);
+ assert.equal(controller.state.pitch, 0);
+ assert.ok(controller.state.position[1] >= 0);
+});
+
+test('flight and driving are deterministic for the same inputs', () => {
+ const finalStates = [0, 1].map(() => {
+ const game = createGame(input => createFlightController({ input }));
+ game.input.press('script/right');
+ game.input.press('script/forward');
+ for (let index = 0; index < 100; index += 1) stepOnce(game);
+ return JSON.stringify(game.controller.state);
+ });
+ assert.equal(finalStates[0], finalStates[1]);
+});
+
+test('the orbit camera turns with look and zooms inside its limits', () => {
+ const input = createInput({ axes: { lookX: ['script/lookRight'], lookY: ['script/lookUp'], zoom: ['script/zoomIn'] } });
+ const subject = { position: [0, 0, 0], yaw: 0 };
+ const rig = createOrbitCamera({ subject, input, zoom: 'zoom', minimumDistance: 2, maximumDistance: 9, distance: 6 });
+ const runtime = createRuntime(fakeRenderer, { mode: 'fixed', fixedStepSeconds: 1 / 60, systems: [input, rig], scheduler });
+ input.press('script/lookRight');
+ input.press('script/zoomIn');
+ for (let index = 0; index < 40; index += 1) runtime.step(STEP_MILLISECONDS);
+ assert.ok(rig.yaw > 1, `yaw was ${rig.yaw}`);
+ assert.equal(rig.distance, 2);
+ const { eye, target } = rig.pose({ alpha: 1 });
+ approximately(Math.hypot(eye[0] - target[0], eye[1] - target[1], eye[2] - target[2]), 2);
+});
+
+test('the chase camera swings round to the subject yaw', () => {
+ const subject = { position: [0, 0, 0], yaw: 2 };
+ const rig = createChaseCamera({ subject, yaw: 0 });
+ const runtime = createRuntime(fakeRenderer, { mode: 'fixed', fixedStepSeconds: 1 / 60, systems: [rig], scheduler });
+ for (let index = 0; index < 120; index += 1) runtime.step(STEP_MILLISECONDS);
+ approximately(rig.yaw, 2, 0.01);
+});
+
+test('the side-scroller camera looks along -Z and leads the subject by its velocity', () => {
+ const subject = { position: [0, 1, 0], velocity: [5, 0, 0], yaw: 0 };
+ const rig = createSideScrollerCamera({ subject, distance: 8, lookAhead: 3, followSeconds: 0 });
+ const runtime = createRuntime(fakeRenderer, { mode: 'fixed', fixedStepSeconds: 1 / 60, systems: [rig], scheduler });
+ runtime.step(STEP_MILLISECONDS);
+ const { eye, target } = rig.pose({ alpha: 1 });
+ approximately(target[0], 3);
+ approximately(eye[0], 3);
+ approximately(eye[2] - target[2], 8);
+ approximately(eye[1], target[1]);
+});
+
+test('custom controller and rig kinds register, build and swap at runtime', () => {
+ registerController('test-boat', options => ({
+ name: options.name ?? 'boat',
+ state: { position: [...(options.position ?? [0, 0, 0])], yaw: options.yaw ?? 0 },
+ fixedUpdate() {},
+ }));
+ registerCameraRig('test-fixed', options => ({
+ name: options.name ?? 'camera',
+ subject: options.subject,
+ yaw: options.yaw ?? 0,
+ pose: () => ({ eye: [0, 10, 10], target: options.subject.position, up: [0, 1, 0] }),
+ fixedUpdate() {},
+ }));
+ assert.ok(listControllerKinds().includes('test-boat'));
+ assert.ok(listCameraRigKinds().includes('test-fixed'));
+ const game = createGame(
+ input => createController('character', { input, name: 'player', position: [1, 0, 2] }),
+ (controller, input) => createCameraRigOfKind('follow', { subject: controller.state, input, name: 'camera' }),
+ );
+ game.runtime.step(STEP_MILLISECONDS);
+ const boat = replaceController(game.runtime, 'player', 'test-boat');
+ assert.deepEqual(boat.state.position, game.controller.state.position);
+ assert.equal(game.runtime.getSystem('player'), boat);
+ const car = replaceController(game.runtime, 'player', 'vehicle', { input: game.input });
+ assert.deepEqual(car.state.position, game.controller.state.position);
+ const rig = replaceCameraRig(game.runtime, 'camera', 'test-fixed', { subject: car.state });
+ assert.equal(game.runtime.getSystem('camera'), rig);
+ assert.deepEqual(rig.pose().eye, [0, 10, 10]);
+ game.runtime.step(STEP_MILLISECONDS);
+});
+
+test('errors name the option and what to pass', () => {
+ const input = createScriptedInput();
+ assert.throws(() => createVehicleController({ input, maximumSpeed: -1 }), /createVehicleController maximumSpeed must be a number from 0 to 100, got -1/);
+ assert.throws(() => createFlightController({ input, cruiseSpeed: 1000 }), /createFlightController cruiseSpeed must be a number/);
+ assert.throws(() => createVehicleController({}), /needs options.input/);
+ assert.throws(() => createCameraClip({ padding: -1 }), /createCameraClip padding/);
+ assert.throws(() => createCameraClip({ obstacles: [{ min: [1, 1, 1], max: [0, 0, 0] }] }), /min must not exceed max/);
+ assert.throws(() => createController('missing'), /no kind "missing". Registered kinds: character/);
+ assert.throws(() => registerController('vehicle', () => ({})), /already registered/);
+ assert.throws(() => registerController('', () => ({})), /non-empty string/);
+ assert.throws(() => registerCameraRig('x-rig', null), /must be a function/);
+ registerController('test-broken', () => ({}));
+ assert.throws(() => createController('test-broken'), /must return a runtime system with state.position/);
+ assert.throws(() => createOrbitCamera({ subject: { position: [0, 0, 0] }, zoom: 'zoom' }), /needs options.input/);
+});
+
+function approximately(actual, expected, tolerance = 1e-6) {
+ assert.ok(Math.abs(actual - expected) <= tolerance, `expected ${actual} to be within ${tolerance} of ${expected}`);
+}