Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add runtime addon: live game loop with pluggable systems and update modes (#770)

Nguyen Xuan An06a06744b5e6
diff --git a/README.md b/README.md
index c4607f95..7211316b 100644
--- a/README.md
+++ b/README.md
@@ -138,6 +138,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Liquid | `67js/addons/spume` | [Baked liquid playback](https://67js.codepawl.com/spume.md) with refraction and spray |
| Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](https://67js.codepawl.com/vehicle.md) |
| 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 |
| 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
new file mode 100644
index 00000000..6b226a82
--- /dev/null
+++ b/bench/runtime-loop/index.html
@@ -0,0 +1,29 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Runtime loop sample</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #14161a; color: #e8eaed; font: 14px/1.4 system-ui, sans-serif; }
+ canvas { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; }
+ .panel { position: fixed; top: 16px; left: 16px; display: grid; gap: 12px; padding: 12px 14px; border-radius: 10px; background: rgba(20, 22, 26, 0.82); }
+ .modes { display: flex; gap: 4px; }
+ button { font: inherit; color: inherit; background: transparent; border: 0; border-radius: 6px; padding: 6px 12px; cursor: pointer; }
+ button[aria-pressed="true"] { background: rgba(255, 255, 255, 0.14); }
+ output { display: block; font-variant-numeric: tabular-nums; white-space: pre; }
+</style>
+</head>
+<body>
+<canvas></canvas>
+<div class="panel">
+ <div class="modes" role="group" aria-label="Update mode">
+ <button type="button" data-mode="fixed">Fixed</button>
+ <button type="button" data-mode="variable">Variable</button>
+ <button type="button" data-mode="both">Both, interpolated</button>
+ </div>
+ <output id="readout"></output>
+</div>
+<script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/bench/runtime-loop/main.js b/bench/runtime-loop/main.js
new file mode 100644
index 00000000..a9b8b7f4
--- /dev/null
+++ b/bench/runtime-loop/main.js
@@ -0,0 +1,123 @@
+// Sample for src/runtime.js: a ball bouncing in a fixed-step system and a cube spinning in a variable-step system,
+// shown live in each update mode. Open bench/runtime-loop/index.html with `npm run dev`; ?mode=fixed|variable|both picks the start mode.
+import { Renderer67, box, sphere } from '/src/index.js';
+import { createRuntime } from '/src/runtime.js';
+
+const GRAVITY = -9.8;
+const FIXED_RATE = 20; // Low on purpose, so the difference between fixed and interpolated is visible.
+const BOUNCE_ENERGY = 0.9;
+const BALL_RADIUS = 0.4;
+const SPIN_RADIANS_PER_SECOND = 1.5;
+
+function translation(x, y, z, scale = 1) {
+ return new Float32Array([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1]);
+}
+
+function rotationAroundY(angle, x, y, z) {
+ const cosine = Math.cos(angle);
+ const sine = Math.sin(angle);
+ return new Float32Array([cosine, 0, -sine, 0, 0, 1, 0, 0, sine, 0, cosine, 0, x, y, z, 1]);
+}
+
+const ballPart = {
+ name: 'Ball',
+ geometry: sphere(),
+ matrix: translation(-1.2, 2, 0, BALL_RADIUS),
+ material: { color: [0.9, 0.35, 0.25], metallic: 0, roughness: 0.4, emission: 0 },
+};
+const cubePart = {
+ name: 'Cube',
+ geometry: box(),
+ matrix: rotationAroundY(0, 1.2, 0.5, 0),
+ material: { color: [0.25, 0.55, 0.9], metallic: 0, roughness: 0.4, emission: 0 },
+};
+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]),
+ material: { color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.9, emission: 0 },
+};
+const parts = [groundPart, ballPart, cubePart];
+
+const physicsSystem = {
+ name: 'ball-physics',
+ previousHeight: 2,
+ height: 2,
+ velocity: 0,
+ init() {
+ this.previousHeight = this.height = 2;
+ this.velocity = 0;
+ },
+ integrate(stepSeconds) {
+ this.previousHeight = this.height;
+ this.velocity += GRAVITY * stepSeconds;
+ this.height += this.velocity * stepSeconds;
+ if (this.height < BALL_RADIUS) {
+ this.height = BALL_RADIUS;
+ this.velocity = -this.velocity * BOUNCE_ENERGY;
+ }
+ },
+ fixedUpdate(stepSeconds) {
+ this.integrate(stepSeconds);
+ },
+ // Variable mode never calls fixedUpdate, so the same physics runs on the frame time there.
+ update(deltaSeconds, context) {
+ if (context.mode === 'variable') this.integrate(deltaSeconds);
+ },
+};
+
+const spinSystem = {
+ name: 'cube-spin',
+ angle: 0,
+ update(deltaSeconds) {
+ this.angle += SPIN_RADIANS_PER_SECOND * deltaSeconds;
+ },
+};
+
+const canvas = document.querySelector('canvas');
+const renderer = new Renderer67(canvas, parts, { samples: 4, memoryBudgetMiB: 256 });
+renderer.resize();
+
+// 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, 1.2, 0.5, 0);
+ renderer.updateParts(parts);
+ return { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0], time: context.elapsedSeconds };
+}
+
+let runtime = null;
+
+function startMode(mode) {
+ runtime?.dispose();
+ runtime = createRuntime(renderer, {
+ mode,
+ fixedRate: FIXED_RATE,
+ frame: buildFrame,
+ systems: [physicsSystem, spinSystem],
+ });
+ runtime.start();
+ for (const button of document.querySelectorAll('button[data-mode]')) {
+ button.setAttribute('aria-pressed', String(button.dataset.mode === mode));
+ }
+ window.runtimeSample = runtime;
+}
+
+for (const button of document.querySelectorAll('button[data-mode]')) {
+ button.addEventListener('click', () => startMode(button.dataset.mode));
+}
+
+const readout = document.querySelector('#readout');
+setInterval(() => {
+ const stats = runtime.stats;
+ readout.textContent = [
+ `${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)}`,
+ ].join('\n');
+}, 250);
+
+const requestedMode = new URLSearchParams(location.search).get('mode');
+startMode(['fixed', 'variable', 'both'].includes(requestedMode) ? requestedMode : 'both');
diff --git a/changes/770.md b/changes/770.md
new file mode 100644
index 00000000..b8428452
--- /dev/null
+++ b/changes/770.md
@@ -0,0 +1 @@
+- `67js/addons/runtime` adds `createRuntime`, a live game loop with fixed, variable or interpolated steps, ordered pluggable systems, pause on a hidden tab and a frame-time readout (#770)
diff --git a/docs/runtime.md b/docs/runtime.md
new file mode 100644
index 00000000..f76e3cd4
--- /dev/null
+++ b/docs/runtime.md
@@ -0,0 +1,81 @@
+# Runtime: a live game loop
+
+`67js/addons/runtime` drives a renderer live. Films do not use it: a film renders every frame as a pure function of time and stays deterministic. The runtime is for a browser game, where a player, a script or a network message changes the next frame.
+
+It loads only when imported, adds no dependency, and does not touch the film path.
+
+```js
+import { Renderer67 } from '67js';
+import { createRuntime } from '67js/addons/runtime';
+
+const renderer = new Renderer67(canvas, parts);
+const runtime = createRuntime(renderer, {
+ mode: 'both',
+ fixedRate: 60,
+ frame: context => ({ eye: [0, 3, 8], target: [0, 1, 0], time: context.elapsedSeconds }),
+ systems: [inputSystem, physicsSystem, gameSystem],
+});
+runtime.start();
+```
+
+A runnable sample is `bench/runtime-loop/index.html` (`npm run dev`, then open `/bench/runtime-loop/`). It switches between the three modes and shows the frame-time readout.
+
+## Update modes
+
+| `mode` | Calls per frame | `context.alpha` |
+| --- | --- | --- |
+| `'fixed'` | `fixedUpdate(step)` as many times as whole steps fit in the elapsed time | `1` |
+| `'variable'` | `update(deltaSeconds)` once | `1` |
+| `'both'` (default) | `fixedUpdate` for the whole steps, then `update(deltaSeconds)` once | leftover time divided by the step, from 0 to 1 |
+
+Fixed steps use an accumulator. A frame that takes 25 ms at `fixedRate: 100` runs two steps and keeps 5 ms for the next frame. In `'both'` mode, draw the state between the last two fixed steps with `alpha`: `drawn = previous + (current - previous) * alpha`. That keeps a 20 Hz simulation smooth on a 144 Hz screen.
+
+Two guards stop a slow frame from spiralling. A frame longer than `maximumFrameSeconds` (default 0.25) counts as that long, and one frame runs at most `maximumStepsPerFrame` fixed steps (default 8). Time beyond that is dropped and shows up in `stats.droppedSeconds`.
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `mode` | `'both'` | `'fixed'`, `'variable'` or `'both'` |
+| `fixedStepSeconds` or `fixedRate` | `1/60` s | The fixed step, from 1/1000 to 1 s. Pass one of the two. |
+| `maximumFrameSeconds` | `0.25` | Longest frame time the simulation accepts |
+| `maximumStepsPerFrame` | `8` | Cap on fixed steps in one frame, up to 1000 |
+| `systems` | `[]` | System objects, in the order they run |
+| `frame` | `context => ({ time })` | Returns the object passed to `target.render`. Move parts with `renderer.updateParts` here. |
+| `pauseWhenHidden` | `true` | Stop frames while the tab is hidden |
+| `scheduler`, `clock`, `visibility` | browser | `{ request(callback), cancel(handle) }`, `() => milliseconds` and `{ hidden, subscribe(callback) }`, injected by tests and headless runs |
+
+The first argument is any object with `render(frame)`, such as `Renderer67`.
+
+## Runtime methods
+
+- `start()` initialises the systems once and schedules frames. `stop()` ends the loop and drops the partial step; systems stay initialised, so `start()` continues the same world.
+- `pause()` and `resume()` hold and release the loop. The time spent paused is never simulated. A hidden tab pauses the same way and resumes when it shows again.
+- `step(milliseconds)` runs one frame without a scheduler, for tests and for stepping while paused.
+- `addSystem(system, index)`, `replaceSystem(name, system)`, `removeSystem(name)`, `getSystem(name)` and `systems` (the names, in order). A system added to a started runtime is initialised at once; a replaced or removed one is disposed.
+- `dispose()` stops the loop and disposes every system in reverse order. The runtime cannot start again.
+- `stats` is the frame-time readout: `frames`, `frameMilliseconds` (last), `averageFrameMilliseconds` and `maximumFrameMilliseconds` (last 120 frames), `framesPerSecond`, `updateMilliseconds` and `renderMilliseconds` (the last frame's split; the renderer call returns when it has submitted its work, so GPU time needs a timer query), `fixedSteps`, `lastFixedSteps`, `droppedSeconds`, `alpha` and `elapsedSeconds`.
+
+## System interface
+
+Physics, input, player, animation graph, audio and game code plug in as systems. A system is a plain object. Only `name` is required; leave out any hook it does not need.
+
+```js
+const system = {
+ name: 'physics', // unique string
+ init(context) {}, // once, when the loop first starts (or when added to a started runtime)
+ fixedUpdate(step, context) {}, // each fixed step; step is in seconds
+ update(delta, context) {}, // each frame in 'variable' and 'both' mode; delta is in seconds
+ dispose(context) {}, // when removed, replaced or the runtime is disposed
+};
+```
+
+Rules a system can rely on:
+
+- Systems run in array order for every hook, and dispose in reverse order. Put input first, then physics, animation, audio and game code.
+- Hooks run on the page's main thread inside the frame. Keep them short; the cost shows in `stats.updateMilliseconds`.
+- The `context` is one shared object, read only: `runtime`, `target`, `mode`, `fixedStepSeconds`, `deltaSeconds`, `elapsedSeconds` and `alpha`. Do not keep a copy; read it when needed.
+- A hook that throws stops the loop and rethrows the error with the system and hook name in its message.
+- A system does not touch the film path, so the same scene still renders a deterministic film.
+
+Errors from the runtime name the option and say what to pass, for example `createRuntime mode must be one of fixed, variable, both`.
diff --git a/package.json b/package.json
index 715e8c57..97aad972 100644
--- a/package.json
+++ b/package.json
@@ -41,6 +41,7 @@
"docs/mesh.md",
"docs/modeling.md",
"docs/physics.md",
+ "docs/runtime.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -116,6 +117,7 @@
"./addons/replace-textured-parts": "./build/replace-textured-parts.js",
"./addons/texture-update": "./build/texture-update.js",
"./addons/cloth": "./build/cloth.js",
+ "./addons/runtime": "./build/runtime.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 05789a33..c9bf2b87 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',
- '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', '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 4a3de57e..7b34cce0 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -62,6 +62,7 @@ const addonLoaders = import.meta.glob([
'./replace-textured-parts.js',
'./texture-update.js',
'./cloth.js',
+ './runtime.js',
'./update-part-vertices.js',
]);
const moduleCache = new Map();
diff --git a/src/runtime.js b/src/runtime.js
new file mode 100644
index 00000000..16063497
--- /dev/null
+++ b/src/runtime.js
@@ -0,0 +1,362 @@
+// Live game loop: a fixed-step, variable-step or interpolated loop that runs ordered systems and then renders.
+// Films never use it. A film renders every frame as a pure function of time, so this file only adds a way to drive a
+// renderer live and changes nothing in the film path. The clock and the frame scheduler are injected, so tests run it
+// without real time. Systems (physics, input, animation, audio, game code) plug in through the interface in
+// docs/runtime.md and can be added, replaced or left out.
+
+export const RUNTIME_MODES = Object.freeze(['fixed', 'variable', 'both']);
+
+export const RUNTIME_LIMITS = Object.freeze({
+ defaultFixedStepSeconds: 1 / 60,
+ minimumFixedStepSeconds: 1 / 1000,
+ maximumFixedStepSeconds: 1,
+ defaultMaximumFrameSeconds: 0.25,
+ defaultMaximumStepsPerFrame: 8,
+ maximumStepsPerFrameLimit: 1000,
+ maximumSystems: 64,
+ frameWindow: 120,
+});
+
+const SYSTEM_HOOKS = ['init', 'fixedUpdate', 'update', 'dispose'];
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function positiveNumber(value, label, minimum, maximum) {
+ if (!Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`createRuntime ${label} must be a number from ${minimum} to ${maximum}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function validateSystem(system, existingNames) {
+ if (system === null || typeof system !== 'object') {
+ throw new TypeError(`A runtime system must be an object like { name, init, fixedUpdate, update, dispose }, got ${describe(system)}.`);
+ }
+ if (typeof system.name !== 'string' || system.name === '') {
+ throw new TypeError('A runtime system needs a unique name string, such as { name: "physics", fixedUpdate(step) {} }.');
+ }
+ for (const hook of SYSTEM_HOOKS) {
+ if (system[hook] !== undefined && typeof system[hook] !== 'function') {
+ throw new TypeError(`Runtime system "${system.name}" ${hook} must be a function or left out, got ${describe(system[hook])}.`);
+ }
+ }
+ if (existingNames.has(system.name)) {
+ throw new RangeError(`A runtime system named "${system.name}" already exists. Pass another name, or use replaceSystem to swap it.`);
+ }
+}
+
+function defaultScheduler() {
+ if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function') {
+ throw new TypeError('createRuntime found no requestAnimationFrame. Pass options.scheduler as { request(callback), cancel(handle) }.');
+ }
+ return {
+ request: callback => requestAnimationFrame(callback),
+ cancel: handle => cancelAnimationFrame(handle),
+ };
+}
+
+function defaultClock() {
+ return () => performance.now();
+}
+
+function defaultVisibility() {
+ if (typeof document === 'undefined') return { hidden: false, subscribe: () => () => {} };
+ return {
+ get hidden() { return document.hidden; },
+ subscribe(callback) {
+ document.addEventListener('visibilitychange', callback);
+ return () => document.removeEventListener('visibilitychange', callback);
+ },
+ };
+}
+
+function validateOptions(target, options) {
+ if (target === null || typeof target !== 'object' || typeof target.render !== 'function') {
+ throw new TypeError('createRuntime needs a renderer as its first argument: an object with a render(frame) method, such as a Renderer67.');
+ }
+ if (options === null || typeof options !== 'object') throw new TypeError('createRuntime options must be an object or left out.');
+ const mode = options.mode ?? 'both';
+ if (!RUNTIME_MODES.includes(mode)) {
+ throw new RangeError(`createRuntime mode must be one of ${RUNTIME_MODES.join(', ')}, got ${String(mode)}.`);
+ }
+ if (options.fixedStepSeconds !== undefined && options.fixedRate !== undefined) {
+ throw new RangeError('createRuntime takes fixedStepSeconds or fixedRate, not both.');
+ }
+ const fixedStepSeconds = options.fixedRate === undefined
+ ? options.fixedStepSeconds ?? RUNTIME_LIMITS.defaultFixedStepSeconds
+ : 1 / positiveNumber(options.fixedRate, 'fixedRate', 1, 1 / RUNTIME_LIMITS.minimumFixedStepSeconds);
+ positiveNumber(fixedStepSeconds, 'fixedStepSeconds', RUNTIME_LIMITS.minimumFixedStepSeconds, RUNTIME_LIMITS.maximumFixedStepSeconds);
+ const maximumFrameSeconds = positiveNumber(options.maximumFrameSeconds ?? RUNTIME_LIMITS.defaultMaximumFrameSeconds, 'maximumFrameSeconds', 0.001, 10);
+ const maximumStepsPerFrame = positiveNumber(options.maximumStepsPerFrame ?? RUNTIME_LIMITS.defaultMaximumStepsPerFrame, 'maximumStepsPerFrame', 1, RUNTIME_LIMITS.maximumStepsPerFrameLimit);
+ if (options.frame !== undefined && typeof options.frame !== 'function') {
+ throw new TypeError('createRuntime frame must be a function (context) => frame for target.render, or left out.');
+ }
+ if (typeof (options.pauseWhenHidden ?? true) !== 'boolean') throw new TypeError('createRuntime pauseWhenHidden must be a boolean.');
+ const systems = options.systems ?? [];
+ if (!Array.isArray(systems)) throw new TypeError('createRuntime systems must be an array of system objects, in the order they run.');
+ return { mode, fixedStepSeconds, maximumFrameSeconds, maximumStepsPerFrame, systems };
+}
+
+export function createRuntime(target, options = {}) {
+ const settings = validateOptions(target, options);
+ const { mode, fixedStepSeconds, maximumFrameSeconds, maximumStepsPerFrame } = settings;
+ const scheduler = options.scheduler ?? defaultScheduler();
+ const now = options.clock ?? defaultClock();
+ const visibility = options.visibility ?? defaultVisibility();
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
+ const buildFrame = options.frame ?? (context => ({ time: context.elapsedSeconds }));
+ const usesFixed = mode !== 'variable';
+ const usesVariable = mode !== 'fixed';
+
+ const systems = [];
+ const initialised = new Set();
+ const context = { runtime: null, target, mode, fixedStepSeconds, deltaSeconds: 0, elapsedSeconds: 0, alpha: 1 };
+ const frameTimes = [];
+ const stats = { frames: 0, fixedSteps: 0, droppedSeconds: 0, lastFixedSteps: 0, frameMilliseconds: 0, updateMilliseconds: 0, renderMilliseconds: 0 };
+
+ let running = false;
+ let manuallyPaused = false;
+ let disposed = false;
+ let handle = null;
+ let lastTime = null;
+ let accumulator = 0;
+ let unsubscribeVisibility = null;
+
+ const isPaused = () => manuallyPaused || (pauseWhenHidden && visibility.hidden === true);
+
+ function callHook(system, hook, ...args) {
+ if (!system[hook]) return;
+ try {
+ system[hook](...args, context);
+ } catch (error) {
+ error.message = `Runtime system "${system.name}" ${hook} failed: ${error.message}`;
+ throw error;
+ }
+ }
+
+ function initialise(system) {
+ if (initialised.has(system)) return;
+ initialised.add(system);
+ callHook(system, 'init');
+ }
+
+ function disposeSystem(system) {
+ if (!initialised.delete(system)) return;
+ callHook(system, 'dispose');
+ }
+
+ function cancelFrame() {
+ if (handle === null) return;
+ scheduler.cancel(handle);
+ handle = null;
+ }
+
+ function scheduleFrame() {
+ if (running && handle === null && !isPaused()) handle = scheduler.request(tick);
+ }
+
+ function recordFrameTime(milliseconds) {
+ frameTimes.push(milliseconds);
+ if (frameTimes.length > RUNTIME_LIMITS.frameWindow) frameTimes.shift();
+ }
+
+ function runFixedSteps() {
+ let steps = 0;
+ while (accumulator >= fixedStepSeconds && steps < maximumStepsPerFrame) {
+ context.deltaSeconds = fixedStepSeconds;
+ for (const system of systems) callHook(system, 'fixedUpdate', fixedStepSeconds);
+ accumulator -= fixedStepSeconds;
+ steps += 1;
+ }
+ if (accumulator >= fixedStepSeconds) {
+ stats.droppedSeconds += accumulator - (accumulator % fixedStepSeconds);
+ accumulator %= fixedStepSeconds;
+ }
+ stats.lastFixedSteps = steps;
+ stats.fixedSteps += steps;
+ }
+
+ function advance(frameSeconds) {
+ context.elapsedSeconds += frameSeconds;
+ if (usesFixed) {
+ accumulator += frameSeconds;
+ runFixedSteps();
+ }
+ if (usesVariable) {
+ context.deltaSeconds = frameSeconds;
+ for (const system of systems) callHook(system, 'update', frameSeconds);
+ }
+ context.alpha = mode === 'both' ? accumulator / fixedStepSeconds : 1;
+ }
+
+ function tick() {
+ handle = null;
+ if (!running || isPaused()) return;
+ const frameStart = now();
+ const elapsedMilliseconds = lastTime === null ? 0 : Math.max(0, frameStart - lastTime);
+ lastTime = frameStart;
+ const frameSeconds = Math.min(elapsedMilliseconds / 1000, maximumFrameSeconds);
+ try {
+ advance(frameSeconds);
+ const updateEnd = now();
+ target.render(buildFrame(context));
+ const renderEnd = now();
+ stats.updateMilliseconds = updateEnd - frameStart;
+ stats.renderMilliseconds = renderEnd - updateEnd;
+ } catch (error) {
+ stopLoop();
+ throw error;
+ }
+ stats.frames += 1;
+ stats.frameMilliseconds = elapsedMilliseconds;
+ if (stats.frames > 1) recordFrameTime(elapsedMilliseconds);
+ scheduleFrame();
+ }
+
+ function stopLoop() {
+ running = false;
+ cancelFrame();
+ lastTime = null;
+ accumulator = 0;
+ }
+
+ function onVisibilityChange() {
+ if (isPaused()) {
+ cancelFrame();
+ return;
+ }
+ lastTime = null;
+ scheduleFrame();
+ }
+
+ function assertUsable(action) {
+ if (disposed) throw new Error(`Cannot ${action}: this runtime was disposed. Call createRuntime again.`);
+ }
+
+ const runtime = {
+ get mode() { return mode; },
+ get running() { return running; },
+ get paused() { return running && isPaused(); },
+ get systems() { return systems.map(system => system.name); },
+
+ // Initialises the systems once, then schedules frames. Starting a running runtime does nothing.
+ start() {
+ assertUsable('start');
+ if (running) return runtime;
+ running = true;
+ lastTime = null;
+ try {
+ for (const system of systems) initialise(system);
+ } catch (error) {
+ running = false;
+ throw error;
+ }
+ unsubscribeVisibility ??= visibility.subscribe(onVisibilityChange);
+ scheduleFrame();
+ return runtime;
+ },
+
+ // Stops scheduling frames and drops the partial step. Systems stay initialised, so start() resumes the same world.
+ stop() {
+ stopLoop();
+ return runtime;
+ },
+
+ // Holds the loop without ending it. The time while paused is never simulated.
+ pause() {
+ manuallyPaused = true;
+ cancelFrame();
+ return runtime;
+ },
+
+ resume() {
+ assertUsable('resume');
+ manuallyPaused = false;
+ lastTime = null;
+ scheduleFrame();
+ return runtime;
+ },
+
+ // Runs one frame of `milliseconds` without the scheduler: for tests, headless runs and stepping while paused.
+ step(milliseconds = fixedStepSeconds * 1000) {
+ assertUsable('step');
+ positiveNumber(milliseconds, 'step milliseconds', 0, maximumFrameSeconds * 1000);
+ for (const system of systems) initialise(system);
+ advance(milliseconds / 1000);
+ target.render(buildFrame(context));
+ stats.frames += 1;
+ return runtime;
+ },
+
+ // Adds a system after the ones already present, or at `index`. A running runtime initialises it at once.
+ addSystem(system, index = systems.length) {
+ assertUsable('addSystem');
+ validateSystem(system, new Set(systems.map(existing => existing.name)));
+ if (systems.length >= RUNTIME_LIMITS.maximumSystems) {
+ throw new RangeError(`A runtime holds at most ${RUNTIME_LIMITS.maximumSystems} systems. Merge some, or remove one first.`);
+ }
+ if (!Number.isInteger(index) || index < 0 || index > systems.length) {
+ throw new RangeError(`addSystem index must be an integer from 0 to ${systems.length}, got ${String(index)}.`);
+ }
+ systems.splice(index, 0, system);
+ if (running) initialise(system);
+ return runtime;
+ },
+
+ // Swaps a system for another in the same place. The old one is disposed, the new one initialised if the loop has started.
+ replaceSystem(name, system) {
+ assertUsable('replaceSystem');
+ const index = systems.findIndex(existing => existing.name === name);
+ if (index < 0) throw new RangeError(`No runtime system named "${String(name)}". Present: ${runtime.systems.join(', ') || 'none'}. Use addSystem to add one.`);
+ validateSystem(system, new Set(systems.filter((_, position) => position !== index).map(existing => existing.name)));
+ const [previous] = systems.splice(index, 1, system);
+ disposeSystem(previous);
+ if (running) initialise(system);
+ return runtime;
+ },
+
+ removeSystem(name) {
+ assertUsable('removeSystem');
+ const index = systems.findIndex(existing => existing.name === name);
+ if (index < 0) throw new RangeError(`No runtime system named "${String(name)}". Present: ${runtime.systems.join(', ') || 'none'}.`);
+ const [removed] = systems.splice(index, 1);
+ disposeSystem(removed);
+ return runtime;
+ },
+
+ getSystem(name) {
+ return systems.find(system => system.name === name);
+ },
+
+ // Frame-time readout. Times are in milliseconds; the averages cover the last 120 frames.
+ get stats() {
+ const count = frameTimes.length;
+ const average = count ? frameTimes.reduce((sum, value) => sum + value, 0) / count : 0;
+ return {
+ ...stats,
+ averageFrameMilliseconds: average,
+ maximumFrameMilliseconds: count ? Math.max(...frameTimes) : 0,
+ framesPerSecond: average > 0 ? 1000 / average : 0,
+ alpha: context.alpha,
+ elapsedSeconds: context.elapsedSeconds,
+ };
+ },
+
+ // Stops the loop and disposes every system in reverse order. The runtime cannot start again.
+ dispose() {
+ if (disposed) return;
+ stopLoop();
+ unsubscribeVisibility?.();
+ unsubscribeVisibility = null;
+ disposed = true;
+ for (const system of [...systems].reverse()) disposeSystem(system);
+ systems.length = 0;
+ },
+ };
+
+ context.runtime = runtime;
+ for (const system of settings.systems) runtime.addSystem(system);
+ return runtime;
+}
diff --git a/tests/runtime.test.js b/tests/runtime.test.js
new file mode 100644
index 00000000..ec1950c8
--- /dev/null
+++ b/tests/runtime.test.js
@@ -0,0 +1,249 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createRuntime, RUNTIME_LIMITS } from '../src/runtime.js';
+
+// A manual clock and frame scheduler: one frame runs only when the test calls frame(milliseconds).
+function createHarness(options = {}) {
+ let time = 1000;
+ let pending = null;
+ let nextHandle = 1;
+ const visibilityCallbacks = new Set();
+ const visibility = {
+ hidden: false,
+ subscribe(callback) {
+ visibilityCallbacks.add(callback);
+ return () => visibilityCallbacks.delete(callback);
+ },
+ };
+ const scheduler = {
+ request(callback) {
+ pending = { callback, handle: nextHandle };
+ nextHandle += 1;
+ return pending.handle;
+ },
+ cancel(handle) {
+ if (pending?.handle === handle) pending = null;
+ },
+ };
+ const rendered = [];
+ const target = { render: frame => rendered.push(frame) };
+ const runtime = createRuntime(target, { scheduler, clock: () => time, visibility, ...options });
+ return {
+ runtime,
+ rendered,
+ visibility,
+ hasPendingFrame: () => pending !== null,
+ frame(milliseconds) {
+ time += milliseconds;
+ const { callback } = pending;
+ pending = null;
+ callback();
+ },
+ setHidden(hidden) {
+ visibility.hidden = hidden;
+ for (const callback of visibilityCallbacks) callback();
+ },
+ };
+}
+
+function recorder(name, log) {
+ return {
+ name,
+ init: () => log.push(`${name}:init`),
+ fixedUpdate: step => log.push(`${name}:fixed:${step.toFixed(4)}`),
+ update: delta => log.push(`${name}:update:${delta.toFixed(4)}`),
+ dispose: () => log.push(`${name}:dispose`),
+ };
+}
+
+const countOf = (log, kind) => log.filter(line => line.includes(`:${kind}:`)).length;
+
+test('fixed mode accumulates leftover time between frames', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'fixed', fixedRate: 100, systems: [recorder('a', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(25);
+ assert.equal(countOf(log, 'fixed'), 2);
+ harness.frame(5);
+ assert.equal(countOf(log, 'fixed'), 3);
+ assert.equal(countOf(log, 'update'), 0);
+ assert.equal(harness.runtime.stats.fixedSteps, 3);
+ assert.equal(harness.rendered.length, 3);
+});
+
+test('variable mode calls update with the frame time and no fixed update', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'variable', systems: [recorder('a', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(20);
+ harness.frame(10);
+ assert.deepEqual(log.filter(line => line.includes(':update:')), ['a:update:0.0000', 'a:update:0.0200', 'a:update:0.0100']);
+ assert.equal(countOf(log, 'fixed'), 0);
+ assert.equal(harness.runtime.stats.alpha, 1);
+});
+
+test('both mode renders with the interpolation alpha of the leftover step', () => {
+ const alphas = [];
+ const harness = createHarness({
+ mode: 'both',
+ fixedStepSeconds: 0.01,
+ frame: context => {
+ alphas.push(context.alpha);
+ return {};
+ },
+ });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(25);
+ harness.frame(10);
+ assert.equal(alphas[0], 0);
+ assert.ok(Math.abs(alphas[1] - 0.5) < 1e-9);
+ assert.ok(Math.abs(alphas[2] - 0.5) < 1e-9);
+});
+
+test('a long frame is clamped and the step count is capped', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'fixed', fixedStepSeconds: 0.01, maximumFrameSeconds: 1, maximumStepsPerFrame: 5, systems: [recorder('a', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(60000);
+ assert.equal(harness.runtime.stats.lastFixedSteps, 5);
+ assert.ok(harness.runtime.stats.droppedSeconds > 0.9);
+ harness.frame(10);
+ assert.equal(harness.runtime.stats.lastFixedSteps, 1);
+});
+
+test('systems run in order and dispose in reverse', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'both', fixedStepSeconds: 0.01, systems: [recorder('first', log), recorder('second', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(10);
+ assert.deepEqual(log.slice(0, 2), ['first:init', 'second:init']);
+ const fixedRun = log.filter(line => line.includes(':fixed:'));
+ assert.deepEqual(fixedRun.map(line => line.split(':')[0]), ['first', 'second']);
+ assert.ok(log.indexOf('first:update:0.0100') < log.indexOf('second:update:0.0100'));
+ harness.runtime.dispose();
+ assert.deepEqual(log.slice(-2), ['second:dispose', 'first:dispose']);
+});
+
+test('systems can be left out, inserted, swapped and removed', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'variable', systems: [{ name: 'game', update: () => log.push('game') }] });
+ harness.runtime.start();
+ harness.runtime.addSystem({ name: 'input', update: () => log.push('input') }, 0);
+ assert.deepEqual(harness.runtime.systems, ['input', 'game']);
+ harness.frame(0);
+ assert.deepEqual(log, ['input', 'game']);
+ const events = [];
+ harness.runtime.replaceSystem('game', { name: 'game', update: () => log.push('game2'), init: () => events.push('init2') });
+ assert.deepEqual(events, ['init2']);
+ harness.frame(10);
+ assert.deepEqual(log.slice(2), ['input', 'game2']);
+ harness.runtime.removeSystem('input');
+ assert.deepEqual(harness.runtime.systems, ['game']);
+ assert.throws(() => harness.runtime.removeSystem('input'), /No runtime system named "input"/);
+ assert.throws(() => harness.runtime.addSystem({ name: 'game' }), /already exists/);
+});
+
+test('pause holds the loop and resume does not simulate the paused time', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'variable', systems: [recorder('a', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.runtime.pause();
+ assert.equal(harness.hasPendingFrame(), false);
+ assert.equal(harness.runtime.paused, true);
+ harness.runtime.resume();
+ assert.equal(harness.hasPendingFrame(), true);
+ harness.frame(5000);
+ assert.equal(log.at(-1), 'a:update:0.0000');
+ assert.equal(harness.runtime.running, true);
+});
+
+test('a hidden tab pauses the loop and a visible tab resumes it', () => {
+ const harness = createHarness({ mode: 'variable' });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.setHidden(true);
+ assert.equal(harness.hasPendingFrame(), false);
+ harness.setHidden(false);
+ assert.equal(harness.hasPendingFrame(), true);
+ harness.frame(9000);
+ assert.equal(harness.runtime.stats.elapsedSeconds, 0);
+});
+
+test('pauseWhenHidden false keeps running in a hidden tab', () => {
+ const harness = createHarness({ mode: 'variable', pauseWhenHidden: false });
+ harness.runtime.start();
+ harness.setHidden(true);
+ harness.frame(0);
+ assert.equal(harness.hasPendingFrame(), true);
+});
+
+test('stop cancels the frame, keeps systems initialised and start resumes', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'variable', systems: [recorder('a', log)] });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.runtime.stop();
+ assert.equal(harness.hasPendingFrame(), false);
+ assert.equal(harness.runtime.running, false);
+ harness.runtime.start();
+ assert.equal(log.filter(line => line === 'a:init').length, 1);
+ assert.equal(log.includes('a:dispose'), false);
+ assert.equal(harness.hasPendingFrame(), true);
+});
+
+test('stats report frame time, average and the update and render split', () => {
+ const harness = createHarness({ mode: 'variable' });
+ harness.runtime.start();
+ harness.frame(0);
+ harness.frame(16);
+ harness.frame(20);
+ const stats = harness.runtime.stats;
+ assert.equal(stats.frames, 3);
+ assert.equal(stats.frameMilliseconds, 20);
+ assert.equal(stats.averageFrameMilliseconds, 18);
+ assert.equal(stats.maximumFrameMilliseconds, 20);
+ assert.ok(Math.abs(stats.framesPerSecond - 1000 / 18) < 1e-9);
+});
+
+test('a throwing system stops the loop and names the system', () => {
+ const harness = createHarness({ mode: 'variable', systems: [{ name: 'bad', update() { throw new Error('boom'); } }] });
+ harness.runtime.start();
+ assert.throws(() => harness.frame(0), /Runtime system "bad" update failed: boom/);
+ assert.equal(harness.runtime.running, false);
+ assert.equal(harness.hasPendingFrame(), false);
+});
+
+test('step runs one frame without a scheduler', () => {
+ const log = [];
+ const harness = createHarness({ mode: 'fixed', fixedStepSeconds: 0.01, systems: [recorder('a', log)] });
+ harness.runtime.step(20);
+ assert.equal(countOf(log, 'fixed'), 2);
+ assert.equal(harness.rendered.length, 1);
+});
+
+test('a disposed runtime refuses to start', () => {
+ const harness = createHarness();
+ harness.runtime.dispose();
+ assert.throws(() => harness.runtime.start(), /was disposed/);
+});
+
+test('input is validated with messages that say what to pass', () => {
+ const target = { render() {} };
+ const scheduler = { request: () => 1, cancel() {} };
+ assert.throws(() => createRuntime({}, { scheduler }), /render\(frame\)/);
+ assert.throws(() => createRuntime(target, { scheduler, mode: 'turbo' }), /one of fixed, variable, both/);
+ assert.throws(() => createRuntime(target, { scheduler, fixedRate: 0 }), /fixedRate must be a number/);
+ assert.throws(() => createRuntime(target, { scheduler, fixedRate: 60, fixedStepSeconds: 0.01 }), /not both/);
+ assert.throws(() => createRuntime(target, { scheduler, maximumStepsPerFrame: RUNTIME_LIMITS.maximumStepsPerFrameLimit + 1 }), /maximumStepsPerFrame/);
+ assert.throws(() => createRuntime(target, { scheduler, systems: {} }), /array of system objects/);
+ assert.throws(() => createRuntime(target, { scheduler, systems: [{ update() {} }] }), /unique name/);
+ assert.throws(() => createRuntime(target, { scheduler, systems: [{ name: 'x', update: 3 }] }), /update must be a function/);
+ assert.throws(() => createRuntime(target, { scheduler, frame: 3 }), /frame must be a function/);
+ assert.throws(() => createRuntime(target), /requestAnimationFrame/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index fff0d8bd..77e18347 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -105,6 +105,7 @@ export default defineConfig({
'gaussian-splats': 'src/gaussian-splats.js',
'texture-update': 'src/texture-update.js',
cloth: 'src/cloth.js',
+ runtime: 'src/runtime.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.