Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Play physics live in the web export and ship a crate-pocket puzzle sample (#777)

Nguyen Xuan Ane087f21727ef
diff --git a/changes/777.md b/changes/777.md
new file mode 100644
index 00000000..d59a77fc
--- /dev/null
+++ b/changes/777.md
@@ -0,0 +1 @@
+- A game with `game.physics: true` now exports to the web: the page steps the recipe physics section live with Jolt at a fixed 60 Hz, the engine and its wasm ship beside the page and load by relative URL, and a crate-pocket physics puzzle joins the creature and driving samples (#777)
diff --git a/docs/game.md b/docs/game.md
index 9f9899f3..114b53b3 100644
--- a/docs/game.md
+++ b/docs/game.md
@@ -45,7 +45,7 @@ A scene recipe can carry a `game` section. It names the node the player controls
| `input` | `keyboard` | `keyboard` (WASD move, arrows look, Space jump, Shift run), `gamepad` (adds the first pad) or `touch` (adds a left-half stick and tap to jump) |
| `player.animation` | none | An [animation graph](animation-graph.md) for the player, see [Animation and NPCs](#animation-and-npcs) |
| `npcs` | none | Up to 16 characters that walk a path through their own graph, see [Animation and NPCs](#animation-and-npcs) |
-| `physics` | `false` | Accepted. The web export refuses `true` until the physics engine can be bundled |
+| `physics` | `false` | `true` plays the recipe's `physics` section live, see [Physics](#physics) |
| `ground` | 0 | Height of the walkable ground in metres |
| `rules` | none | A [game rules](game-rules.md) document, checked when it is set |
@@ -55,7 +55,7 @@ A rules part named like a scene node is hidden and shown with it, which is how a
`scene_export_web` writes one folder: `index.html`, `game.json` (the recipe) and `engine/` (the built 67js modules, found by following the imports from `build/game.js`). It runs from any static host with no server code, and the folder is bounded: the engine stays under 12 MiB, the recipe under 1 MiB, and the newest four builds are kept. Placed catalog assets (and the assets whose clips a character retargets) are copied to `assets/<id>.glb`, up to 64 MiB together; grown vegetation is refused with the fix. The page shows the variables and the verdict in a corner label and exposes the running game as `window.__game` (`rules.state`, `controller.state`, `scene`, `runtime`).
-`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome, with a head-bob animation graph that the page must play. `node scripts/smoke-game-web.mjs bin/67js-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera. The `character` sample walks a placed, retargeted humanoid (idle and walk clips of another file) to a goal, and checks that the page loads `assets/<id>.glb` and the character's limbs move.
+`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome, with a head-bob animation graph that the page must play. `node scripts/smoke-game-web.mjs bin/67js-mcp.mjs puzzle` plays the [physics puzzle](#physics). `node scripts/smoke-game-web.mjs bin/67js-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera. The `character` sample walks a placed, retargeted humanoid (idle and walk clips of another file) to a goal, and checks that the page loads `assets/<id>.glb` and the character's limbs move.
## From code
@@ -65,7 +65,18 @@ const game = await startGame(canvas, recipe, { replay, showStatus: true });
game.dispose();
```
-`startGame` loads the scene modules the recipe needs, builds the scene and renderer, and runs input, controller, camera rig and rules as [runtime](runtime.md) systems. Each frame it moves the player node with `set-node`, so a large scene pays a scene update per frame. Not yet in the web build: live physics, sound and post effects.
+`startGame` loads the scene modules the recipe needs, builds the scene and renderer, and runs input, controller, camera rig and rules as [runtime](runtime.md) systems. Each frame it moves the player node with `set-node`, so a large scene pays a scene update per frame. Not yet in the web build: sound and post effects.
+
+## Physics
+
+`game.physics: true` plays the recipe's `physics` section (the `set-physics` bodies, with the limits of [physics](physics.md)) live. `startGame` loads `game-physics.js` and the Jolt engine only for such a recipe, so other games and exports do not grow. The engine steps in the fixed update of the runtime at 60 Hz, after the controller and before the rules, and each dynamic body's node follows it through `set-node`. The same recipe gives the same poses on every run in the same engine build; `window.__game.physics` is the [physics system](physics-runtime.md) (`getPose`, `stepCount`, `applyImpulse`, queries).
+
+- The player node can be a `kinematic` body (shape `capsule`, `box` or `ball`): the controller drives it, so the player pushes dynamic bodies and is never pushed back.
+- A rules part named like a dynamic body reports that body's position, so a zone, a tag and `enter` work on crates and balls.
+- Give every fixed body `shape: "box"` (or `ball`, `capsule`, `convex`): the default `trimesh` is not built. Joints, ragdolls, trimesh and compound shapes are refused with the field to change, and `physics.duration` is only the length of the recorded film.
+- The web export copies `jolt-physics.wasm.js` and its `.wasm` file to `engine/physics/` (about 3 MiB) and gives the page their URL, so Jolt fetches the wasm from beside the page. Nothing loads from another origin: a `physicsUrl` on another origin is refused. The `jolt-physics` package must be installed to export.
+
+The `puzzle` sample of `scripts/smoke-game-web.mjs` is two plank crates, two marble plates in brick pockets and an iron gate on a stone floor (pattern materials). The player walks into the first crate and pushes it onto its plate, crosses over and pushes the second; when both plates are pressed the gate part is hidden and the game is won. The smoke checks that the page loads only its own files, that the wasm comes from `engine/physics/`, that both crates moved, and that an export without physics carries no `engine/physics/` folder.
## Animation and NPCs
diff --git a/scripts/smoke-game-web.mjs b/scripts/smoke-game-web.mjs
index f77cd3f9..cf7bbdab 100644
--- a/scripts/smoke-game-web.mjs
+++ b/scripts/smoke-game-web.mjs
@@ -19,7 +19,7 @@ setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
const CHROME_PATH = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const directory = await mkdtemp(join(tmpdir(), '67js-game-web-'));
const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
-const MIME_TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.glb': 'model/gltf-binary' };
+const MIME_TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.glb': 'model/gltf-binary', '.wasm': 'application/wasm' };
const assetsDirectory = join(directory, 'assets');
await mkdir(assetsDirectory);
@@ -176,10 +176,78 @@ function characterSample() {
return { recipe, game, replay, title: 'Retargeted walk', expectedScore: undefined, assetFiles, expectedAssets: [sourceId, heroId] };
}
-const SAMPLES = { creature: creatureSample, drive: driveSample, character: characterSample };
+// Key events [sample, source, value] that push the crate on the left, cross over and push the crate on the right.
+const PUZZLE_REPLAY_EVENTS = [
+ [1, 'keyboard/KeyW', 1], [100, 'keyboard/KeyW', 0],
+ [105, 'keyboard/KeyS', 1], [184, 'keyboard/KeyS', 0], [186, 'keyboard/KeyD', 1], [286, 'keyboard/KeyD', 0],
+ [290, 'keyboard/KeyW', 1], [369, 'keyboard/KeyW', 0],
+];
+
+// A physics puzzle: push both crates into their pockets on the marble plates. The player is a kinematic body, the crates are
+// dynamic bodies that the page steps with Jolt, and a rules zone sees a crate by its node id. Both plates pressed opens the gate.
+function puzzleSample() {
+ const POCKET_X = [-2.5, 2.5];
+ const PLATE_Z = -6;
+ const plateZoneIds = ['plate-zone-a', 'plate-zone-b'];
+ const crateIds = ['crate-a', 'crate-b'];
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0.03 }, { id: 'cylinder', type: 'cylinder', segments: 24 }, { id: 'dome', type: 'sphere' }],
+ materials: [
+ { id: 'flagstone', color: [1, 1, 1], roughness: 0.9, pattern: { type: 'stone', size: 2 } },
+ { id: 'planks', color: [1, 1, 1], roughness: 0.75, pattern: { type: 'planks', size: 1 } },
+ { id: 'bricks', color: [1, 1, 1], roughness: 0.95, pattern: { type: 'bricks', size: 1 } },
+ { id: 'marble', color: [1, 1, 1], roughness: 0.3, pattern: { type: 'marble', size: 1 } },
+ { id: 'iron', color: [1, 1, 1], metallic: 0.9, roughness: 0.45, pattern: { type: 'metal', size: 0.5 } },
+ { id: 'cloth', color: [1, 1, 1], roughness: 0.8, pattern: { type: 'fabric', size: 0.25 } },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'block', material: 'flagstone', translation: [0, -0.25, -4], scale: [14, 0.5, 14] },
+ { id: 'hero', geometry: 'cylinder', material: 'cloth', translation: [POCKET_X[0], 0.8, 0], scale: [0.7, 1.6, 0.7] },
+ ...POCKET_X.flatMap((x, index) => [
+ { id: crateIds[index], geometry: 'block', material: 'planks', translation: [x, 0.5, -2.5], scale: [1, 1, 1] },
+ { id: `plate-${'ab'[index]}`, geometry: 'block', material: 'marble', translation: [x, 0.02, PLATE_Z], scale: [1.4, 0.04, 1.4] },
+ { id: `wall-${'ab'[index]}`, geometry: 'block', material: 'bricks', translation: [x, 0.75, -7.1], scale: [2, 1.5, 0.4] },
+ ]),
+ { id: 'gate', geometry: 'block', material: 'iron', translation: [0, 1, -7.1], scale: [2.4, 2, 0.3] },
+ { id: 'beacon', geometry: 'dome', material: 'iron', translation: [0, 2.4, -7.1], scale: [0.5, 0.5, 0.5] },
+ ],
+ physics: {
+ duration: 1,
+ bodies: [
+ { node: 'floor', type: 'fixed', shape: 'box' },
+ { node: 'hero', type: 'kinematic', shape: 'capsule' },
+ ...crateIds.map(node => ({ node, shape: 'box', density: 0.6, friction: 0.6 })),
+ ...['wall-a', 'wall-b'].map(node => ({ node, type: 'fixed', shape: 'box' })),
+ ],
+ },
+ camera: { eye: [0, 7, 7], target: [0, 0, -4], fov: 50 },
+ };
+ const game = {
+ player: { node: 'hero', footOffset: 0.8 },
+ camera: 'top-down',
+ input: 'keyboard',
+ physics: true,
+ rules: {
+ version: 1,
+ variables: { pressed: 0 },
+ zones: POCKET_X.map((x, index) => ({ id: plateZoneIds[index], shape: 'box', center: [x, 0.5, PLATE_Z], size: [1.4, 2, 1.4] })),
+ parts: [{ id: 'hero', tags: ['player'] }, { id: 'gate', tags: ['gate'] }, ...crateIds.map(id => ({ id, tags: ['crate'] }))],
+ rules: [
+ ...plateZoneIds.map(zone => ({ id: `press-${zone}`, once: true, when: { type: 'enter', zone, tag: 'crate' }, do: [{ type: 'add', variable: 'pressed', value: 1 }] })),
+ { id: 'open-gate', when: { type: 'variable', expression: ['>=', 'pressed', 2] }, do: [{ type: 'hide', part: 'gate' }, { type: 'win' }] },
+ ],
+ },
+ };
+ // Walk forward and push the first crate into its pocket; back off, cross to the second crate and push it in too.
+ const replay = { version: 1, samples: 460, truncated: false, events: PUZZLE_REPLAY_EVENTS };
+ return { recipe, game, replay, title: 'Crate pockets', expectedScore: undefined, puzzle: { crateIds, minimumTravel: 2 } };
+}
+
+const SAMPLES = { creature: creatureSample, drive: driveSample, character: characterSample, puzzle: puzzleSample };
const sampleName = process.argv[3] ?? 'creature';
assert.ok(SAMPLES[sampleName], `Unknown sample "${sampleName}". Use one of: ${Object.keys(SAMPLES).join(', ')}.`);
-const { recipe, game, replay, title, expectedScore, headRestHeight, assetFiles = {}, expectedAssets = [] } = SAMPLES[sampleName]();
+const { recipe, game, replay, title, expectedScore, headRestHeight, assetFiles = {}, expectedAssets = [], puzzle } = SAMPLES[sampleName]();
for (const [name, bytes] of Object.entries(assetFiles)) await writeFile(join(assetsDirectory, name), bytes);
function serveFolder(folder) {
@@ -198,6 +266,7 @@ function serveFolder(folder) {
}
let browser;
+let pageContext;
let server;
try {
await client.connect(transport);
@@ -219,9 +288,17 @@ try {
await writeFile(join(folder, 'replay.json'), JSON.stringify(replay));
server = await serveFolder(folder);
- browser = await chromium.launch({ executablePath: CHROME_PATH, headless: true, args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'] });
- const page = await browser.newPage({ viewport: { width: 640, height: 400 } });
+ // GAME_SMOKE_CHROME_ARGS replaces the Chrome flags (a Linux GPU box needs Vulkan ones); GAME_SMOKE_VIDEO_DIR records the page as a 640x360 clip.
+ const chromeArgs = process.env.GAME_SMOKE_CHROME_ARGS ? process.env.GAME_SMOKE_CHROME_ARGS.split(' ') : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'];
+ browser = await chromium.launch({ executablePath: CHROME_PATH, headless: true, args: chromeArgs });
+ const videoDirectory = process.env.GAME_SMOKE_VIDEO_DIR;
+ const viewport = videoDirectory ? { width: 640, height: 360 } : { width: 640, height: 400 };
+ pageContext = await browser.newContext({ viewport, ...(videoDirectory ? { recordVideo: { dir: videoDirectory, size: viewport } } : {}) });
+ const page = await pageContext.newPage();
const problems = [];
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ const requested = [];
+ page.on('request', request => requested.push(request.url()));
page.on('pageerror', error => problems.push(error.message));
page.on('console', message => { if (message.type() === 'error') problems.push(message.text()); });
await page.goto(`http://127.0.0.1:${server.address().port}/?replay=replay.json`);
@@ -258,6 +335,19 @@ try {
const speed = await page.evaluate(() => window.__game.animation.get('speed'));
assert.ok(speed >= 0, 'the exported page has a live animation graph with a speed parameter');
}
+ const hasPhysicsFiles = await readFile(join(folder, 'engine/physics/jolt-physics.wasm.wasm')).then(() => true, () => false);
+ assert.equal(hasPhysicsFiles, Boolean(puzzle), 'only an export with game.physics carries the physics engine');
+ if (puzzle) {
+ // The page stepped the world: both crates were pushed along the floor by the kinematic player, and the gate part opened.
+ const crates = await page.evaluate(ids => ({ steps: window.__game.physics.stepCount, poses: ids.map(id => window.__game.physics.getPose(id).translation) }), puzzle.crateIds);
+ assert.ok(crates.steps > 100, `physics stepped ${crates.steps} times`);
+ for (const translation of crates.poses) assert.ok(translation[2] < -2.5 - puzzle.minimumTravel, `a crate was pushed to z ${translation[2]}`);
+ assert.equal(state.variables.pressed, 2);
+ const stray = requested.filter(url => !url.startsWith(origin) && !url.startsWith('data:'));
+ assert.deepEqual(stray, [], 'the page loads nothing from another origin');
+ assert.ok(requested.some(url => url === `${origin}/engine/physics/jolt-physics.wasm.wasm`), 'the wasm file loads from beside the page');
+ console.log(JSON.stringify({ crates: crates.poses }));
+ }
for (const id of expectedAssets) assert.ok(await readFile(join(folder, 'assets', `${id}.glb`)), `the export writes assets/${id}.glb`);
await page.screenshot({ path: join(directory, 'won.png') });
console.log(JSON.stringify({ ok: true, bytes: exported.bytes, files: exported.files, step: state.step, screenshot: join(directory, 'won.png') }));
@@ -265,6 +355,7 @@ try {
console.error(diagnostics);
throw error;
} finally {
+ await pageContext?.close();
await browser?.close();
server?.close();
await client.close();
diff --git a/scripts/web-export.mjs b/scripts/web-export.mjs
index 8966bbe7..0e996aad 100644
--- a/scripts/web-export.mjs
+++ b/scripts/web-export.mjs
@@ -1,23 +1,34 @@
import { copyFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
+import { gamePhysicsProblem, hasTexturedMaterial } from '../src/game-needs.js';
// Writes a playable game as one folder that any static host can serve: index.html, game.json (the recipe with its game
// section) and engine/ (the built 67js modules that index.html imports, found by following the import statements from
// build/game.js). There is no server code. The folder is bounded, so an export never fills the disk.
-export const WEB_EXPORT_LIMITS = Object.freeze({ maxEngineBytes: 12 * 1024 * 1024, maxEngineFiles: 400, maxTitleLength: 64, maxRecipeBytes: 1024 * 1024, maxAssetBytes: 64 * 1024 * 1024 });
+export const WEB_EXPORT_LIMITS = Object.freeze({ maxEngineBytes: 12 * 1024 * 1024, maxEngineFiles: 400, maxTitleLength: 64, maxRecipeBytes: 1024 * 1024, maxAssetBytes: 64 * 1024 * 1024, maxPhysicsBytes: 8 * 1024 * 1024 });
const ASSET_ID = /^[a-f0-9]{64}$/;
+// The physics engine ships beside the page: Jolt's loader fetches the .wasm file that sits next to it by a relative URL.
+const PHYSICS_DIRECTORY = 'engine/physics';
+const PHYSICS_LOADER = 'jolt-physics.wasm.js';
+const PHYSICS_WASM = 'jolt-physics.wasm.wasm';
+// The chunk that loads the physics engine; an export without physics leaves it and what only it needs out.
+const PHYSICS_ENTRY_CHUNK = /^game-physics(?:-|[.])/;
+// The texture swap addon, loaded for a recipe with a pattern or a map.
+const TEXTURED_ENTRY_CHUNK = /^replace-textured-parts(?:-|[.])/;
+
const ENTRY_MODULE = 'game.js';
const IMPORT_PATTERN = /(?:from\s*|import\s*\(\s*|import\s*)["'](\.\/[A-Za-z0-9_.-]+\.js)["']/g;
/** Every module file build/game.js needs, including the ones it loads on demand, as names relative to the build folder. */
-export async function engineModuleNames(buildDirectory) {
+export async function engineModuleNames(buildDirectory, { physics = false, textured = false } = {}) {
const found = new Set();
const pending = [ENTRY_MODULE];
while (pending.length) {
const name = pending.pop();
- if (found.has(name)) continue;
+ if (found.has(name) || (!physics && PHYSICS_ENTRY_CHUNK.test(name)) || (!textured && TEXTURED_ENTRY_CHUNK.test(name))) continue;
let source;
try {
source = await readFile(join(buildDirectory, name), 'utf8');
@@ -33,6 +44,18 @@ export async function engineModuleNames(buildDirectory) {
return [...found].sort();
}
+// The Jolt loader and its wasm file from the optional jolt-physics package, which must be installed to export a game with physics.
+async function joltFiles() {
+ let loaderPath;
+ try {
+ loaderPath = createRequire(import.meta.url).resolve('jolt-physics/wasm');
+ } catch {
+ throw new Error('A game with physics needs the "jolt-physics" package to bundle its engine. Install it with `npm install jolt-physics`, or set game.physics to false with set-game.');
+ }
+ const wasmPath = join(dirname(loaderPath), PHYSICS_WASM);
+ return Promise.all([[PHYSICS_LOADER, loaderPath], [PHYSICS_WASM, wasmPath]].map(async ([name, path]) => ({ name, path, bytes: (await stat(path)).size })));
+}
+
function escapeHtml(text) {
return text.replace(/[&<>"']/g, character => `&#${character.charCodeAt(0)};`);
}
@@ -43,7 +66,7 @@ function pageTitle(title) {
}
/** The page. `?replay=name.json` plays a recording from the same folder instead of the keyboard, for tests and demos. */
-export function indexHtml(title, assetUrls = {}) {
+export function indexHtml(title, assetUrls = {}, physicsUrl = undefined) {
return `<!doctype html>
<html lang="en">
<head>
@@ -62,7 +85,7 @@ const recipe = await (await fetch('./game.json')).json();
const replayName = new URLSearchParams(location.search).get('replay');
const replay = /^[\\w.-]+\\.json$/.test(replayName ?? '') ? await (await fetch('./' + replayName)).json() : undefined;
const assetUrls = ${JSON.stringify(assetUrls)};
-window.__game = await startGame(canvas, recipe, { replay, assetUrls });
+${physicsUrl ? `const physicsUrl = ${JSON.stringify(physicsUrl)};\n` : ''}window.__game = await startGame(canvas, recipe, { replay, assetUrls${physicsUrl ? ', physicsUrl' : ''} });
</script>
</body>
</html>
@@ -75,7 +98,9 @@ window.__game = await startGame(canvas, recipe, { replay, assetUrls });
*/
export async function writeWebBuild({ recipe, buildDirectory, outputDirectory, title, assets = new Map() }) {
if (!recipe?.game) throw new Error('This scene has no game. Add one with scene_apply set-game (fields: scene_capabilities topic game), then export again.');
- if (recipe.game.physics) throw new Error('game.physics is true, and the web export does not bundle the physics engine yet. Set game.physics to false with set-game.');
+ const withPhysics = recipe.game.physics === true;
+ const physicsProblem = withPhysics ? gamePhysicsProblem(recipe) : null;
+ if (physicsProblem) throw new Error(physicsProblem);
if (recipe.nodes?.some(node => node.vegetation)) throw new Error('The web export does not carry grown vegetation yet. Remove it, or build the plants from geometry.');
const missing = (recipe.nodes ?? []).filter(node => node.asset && !assets.has(node.asset.id)).map(node => node.id);
if (missing.length) throw new Error(`The web export needs the bytes of the catalog assets placed by ${missing.join(', ')}. Pass them as assets (asset id to Buffer).`);
@@ -83,13 +108,18 @@ export async function writeWebBuild({ recipe, buildDirectory, outputDirectory, t
const recipeText = JSON.stringify(recipe);
if (Buffer.byteLength(recipeText) > WEB_EXPORT_LIMITS.maxRecipeBytes) throw new RangeError(`The recipe is larger than ${WEB_EXPORT_LIMITS.maxRecipeBytes} bytes. Simplify the scene.`);
- const names = await engineModuleNames(buildDirectory);
+ const names = await engineModuleNames(buildDirectory, { physics: withPhysics, textured: hasTexturedMaterial(recipe) });
let engineBytes = 0;
for (const name of names) engineBytes += (await stat(join(buildDirectory, name))).size;
if (engineBytes > WEB_EXPORT_LIMITS.maxEngineBytes) throw new RangeError(`The engine is ${engineBytes} bytes, above the ${WEB_EXPORT_LIMITS.maxEngineBytes} byte limit. Rebuild the package.`);
+ const physicsFiles = withPhysics ? await joltFiles() : [];
+ const physicsBytes = physicsFiles.reduce((total, file) => total + file.bytes, 0);
+ if (physicsBytes > WEB_EXPORT_LIMITS.maxPhysicsBytes) throw new RangeError(`The physics engine is ${physicsBytes} bytes, above the ${WEB_EXPORT_LIMITS.maxPhysicsBytes} byte limit.`);
await mkdir(join(outputDirectory, 'engine'), { recursive: true });
for (const name of names) await copyFile(join(buildDirectory, name), join(outputDirectory, 'engine', name));
+ if (withPhysics) await mkdir(join(outputDirectory, PHYSICS_DIRECTORY), { recursive: true });
+ for (const file of physicsFiles) await copyFile(file.path, join(outputDirectory, PHYSICS_DIRECTORY, file.name));
await writeFile(join(outputDirectory, 'game.json'), recipeText);
const assetUrls = {};
let assetBytes = 0;
@@ -101,8 +131,8 @@ export async function writeWebBuild({ recipe, buildDirectory, outputDirectory, t
await writeFile(join(outputDirectory, 'assets', `${id}.glb`), bytes);
assetUrls[id] = `./assets/${id}.glb`;
}
- const html = indexHtml(title, assetUrls);
+ const html = indexHtml(title, assetUrls, withPhysics ? `./${PHYSICS_DIRECTORY}/${PHYSICS_LOADER}` : undefined);
await writeFile(join(outputDirectory, 'index.html'), html);
- const totalBytes = engineBytes + assetBytes + Buffer.byteLength(recipeText) + Buffer.byteLength(html);
- return { directory: dirname(join(outputDirectory, 'index.html')), files: names.length + 2 + assets.size, engineModules: names.length, bytes: totalBytes };
+ const totalBytes = engineBytes + physicsBytes + assetBytes + Buffer.byteLength(recipeText) + Buffer.byteLength(html);
+ return { directory: dirname(join(outputDirectory, 'index.html')), files: names.length + physicsFiles.length + 2 + assets.size, engineModules: names.length, bytes: totalBytes };
}
diff --git a/src/agent-physics.js b/src/agent-physics.js
index 90f8caf2..66f1b166 100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@ -417,6 +417,11 @@ function layerBits(layers) {
return layers.reduce((bits, layer) => bits | (1 << layer), 0);
}
+/** The recorded-physics definition of a recipe section without a ragdoll, for a live physics system. `geometries` maps geometry ids to geometry data. */
+export function liveAgentPhysicsDefinition(physics, recipe, geometries) {
+ return physicsDefinition(physics, recipe, geometries, null);
+}
+
function physicsDefinition(physics, recipe, geometries, ragdoll) {
const nodes = new Map(recipe.nodes.map(node => [node.id, node]));
const definition = { bodies: [], colliders: [], joints: [] };
diff --git a/src/game-needs.js b/src/game-needs.js
new file mode 100644
index 00000000..6df8e437
--- /dev/null
+++ b/src/game-needs.js
@@ -0,0 +1,21 @@
+// What a game recipe needs from the runtime, as pure data checks. startGame loads an optional piece only when a recipe needs it,
+// and the web export copies that piece only when the same check says so, so a plain game does not carry the physics engine or the
+// texture swap code.
+
+const UNSUPPORTED_SHAPES = ['trimesh', 'cone', 'compound'];
+
+/** Why a recipe cannot play physics in a game (the engine is Jolt), or null. */
+export function gamePhysicsProblem(recipe) {
+ const physics = recipe.physics;
+ if (!physics?.bodies?.length) return 'game.physics is true, but the recipe has no physics section with bodies. Add one with set-physics, or set game.physics to false with set-game.';
+ if (physics.joints?.length || physics.ragdoll) return 'The game physics engine builds no joints or ragdolls yet. Remove physics.joints and physics.ragdoll, or set game.physics to false with set-game.';
+ const unsupported = physics.bodies.find(body => UNSUPPORTED_SHAPES.includes(body.shape));
+ if (unsupported) return `Body "${unsupported.node}" has shape ${unsupported.shape}, which the game physics engine does not build. Use box, ball, capsule or convex (give a fixed body shape "box": its default is trimesh).`;
+ return null;
+}
+
+// A textured part is swapped by replaceParts only once the replace-textured-parts addon is loaded, and the first scene update
+// after a pattern or map bake can swap the parts.
+export function hasTexturedMaterial(recipe) {
+ return (recipe.materials ?? []).some(material => Object.keys(material).some(key => key === 'pattern' || key === 'map' || key.endsWith('Map')));
+}
diff --git a/src/game-physics.js b/src/game-physics.js
new file mode 100644
index 00000000..7849aa37
--- /dev/null
+++ b/src/game-physics.js
@@ -0,0 +1,75 @@
+// Live physics for a game scene. The recipe's physics section names the bodies (the same section the film bake reads, with
+// the same limits); the game steps them with Jolt in the fixed update of the runtime and moves their nodes with set-node.
+// This file loads only for a recipe whose game has physics true, so other games do not carry the engine.
+import { liveAgentPhysicsDefinition } from './agent-physics.js';
+import { gamePhysicsProblem } from './game-needs.js';
+import { loadJoltEngine, joltAdapter } from './physics-jolt.js';
+import { createPhysicsSystem } from './physics-runtime.js';
+
+export const GAME_PHYSICS_STEP_SECONDS = 1 / 60;
+
+// The page gives a URL to the engine files it ships. Only the page's own origin is loaded, so a recipe cannot pull code from elsewhere.
+function sameOriginModuleUrl(physicsUrl) {
+ if (physicsUrl === undefined) return undefined;
+ const base = globalThis.location?.href ?? import.meta.url;
+ const url = new URL(physicsUrl, base);
+ const origin = globalThis.location?.origin;
+ if (origin && url.origin !== origin) throw new Error(`physicsUrl must be on the page's own origin (${origin}), got ${url.origin}. Ship the physics files next to the page.`);
+ return url.href;
+}
+
+/**
+ * Build the physics of a game. `scene` is the agent scene (its parts give each body's geometry), `playerNode` and
+ * `playerFootOffset` name the node the controller moves (a kinematic body when it is in the physics section) and
+ * `physicsUrl` is where the page keeps jolt-physics.wasm.js. Returns `{ system, bodies, poseOperations, dispose }`.
+ */
+export async function createGamePhysics({ recipe, scene, playerNode, physicsUrl }) {
+ const problem = gamePhysicsProblem(recipe);
+ if (problem) throw new Error(problem);
+ const partsByNode = new Map(scene.parts.map(part => [part.name, part]));
+ const geometries = new Map();
+ for (const node of recipe.nodes) {
+ if (node.geometry !== undefined && partsByNode.has(node.id)) geometries.set(node.geometry, partsByNode.get(node.id).geometry);
+ }
+ const definition = liveAgentPhysicsDefinition(recipe.physics, recipe, geometries);
+ await loadJoltEngine({ moduleUrl: sameOriginModuleUrl(physicsUrl) });
+ const system = await createPhysicsSystem(definition, { adapter: joltAdapter, timestep: GAME_PHYSICS_STEP_SECONDS });
+ const bodies = new Map(recipe.physics.bodies.map(body => [body.node, body]));
+ const sentPoses = new Map();
+
+ return {
+ system,
+ bodies,
+ playerIsBody: bodies.get(playerNode)?.type === 'kinematic',
+ /** Drive the kinematic player body to the controller position, then step the world once. */
+ fixedUpdate(stepSeconds, context, playerPosition, playerYaw) {
+ if (playerPosition) {
+ system.setKinematicPose(playerNode, {
+ translation: playerPosition,
+ rotation: [0, Math.sin(playerYaw / 2), 0, Math.cos(playerYaw / 2)],
+ });
+ }
+ system.fixedUpdate(stepSeconds, context);
+ },
+ /** Position of a dynamic body, for the rules; undefined for any other node. */
+ positionOf(nodeId) {
+ return bodies.get(nodeId)?.type === 'dynamic' ? system.getPose(nodeId).translation : undefined;
+ },
+ /** set-node operations for the dynamic bodies that moved since the last call. */
+ poseOperations() {
+ const operations = [];
+ for (const [nodeId, body] of bodies) {
+ if (body.type !== 'dynamic') continue;
+ const { translation, rotation } = system.getPose(nodeId);
+ const last = sentPoses.get(nodeId);
+ if (last && last.every((value, index) => value === (index < 3 ? translation[index] : rotation[index - 3]))) continue;
+ sentPoses.set(nodeId, [...translation, ...rotation]);
+ operations.push({ type: 'set-node', id: nodeId, translation, rotation });
+ }
+ return operations;
+ },
+ dispose() {
+ system.dispose();
+ },
+ };
+}
diff --git a/src/game-setup-notes.js b/src/game-setup-notes.js
index 956faf92..82dce91b 100644
--- a/src/game-setup-notes.js
+++ b/src/game-setup-notes.js
@@ -1,13 +1,13 @@
// What scene_capabilities topic game says. It sits beside game-setup.js, not in the agent scene capabilities, so the core agent-scene bundle does not carry it; the MCP runtime adds it to the scene capabilities. A test keeps the names in step with game-setup.js.
export const GAME_CAPABILITIES = Object.freeze({
field: 'recipe.game, set with set-game (null clears). Plain data, never code.',
- fields: 'player {node (a node id; its children move with it), controller character|vehicle (an arcade car: W throttle, S reverse, A/D steer, Space brakes), walkSpeed 3, runSpeed 6, jumpSpeed 7 (0-100 m/s), maximumSpeed 20 (vehicle top speed, 0-100 m/s), footOffset 0 (m from the node origin down to the feet)}, camera, input, physics (bool, false), ground (height in m, 0), rules (game rules document).',
+ fields: 'player {node (a node id; its children move with it), controller character|vehicle (an arcade car: W throttle, S reverse, A/D steer, Space brakes), walkSpeed 3, runSpeed 6, jumpSpeed 7 (0-100 m/s), maximumSpeed 20 (vehicle top speed, 0-100 m/s), footOffset 0 (m from the node origin down to the feet)}, camera, input, physics (bool, false; true needs a set-physics section), ground (height in m, 0), rules (game rules document).',
cameras: Object.freeze(['follow', 'first-person', 'top-down', 'chase']),
inputPresets: Object.freeze({ keyboard: 'WASD and arrows move and look, Space jumps, Shift runs', gamepad: 'keyboard plus the first gamepad (stick 0, jump on button 0)', touch: 'keyboard plus a left-half virtual stick and tap to jump' }),
rules: 'version 1, variables, zones {id, shape sphere|box, center, radius|size}, parts {id, tags, position}, prefabs, rules [{id, once, when, if, do}]. The rules part named like the player node follows the player; a part named like a node is hidden or shown with it. Triggers enter|exit|contact|input|timer|variable (input actions: jump, run); actions set|add|show|hide|spawn|animation|sound|win|lose|restart. Full list: docs/game-rules.md.',
animation: 'player.animation, or npcs[].animation: { clips, parameters, boneGroups, layers, rootMotion, drive }. clips {name: {duration s, loop true, tracks [{target (a CHILD node id of the character, never the character), property translation|rotation, keyframes [{time, value}]}]}}, 1 to 16 clips. parameters, boneGroups, layers (states with clip or 1D/2D blend, transitions, masks) and rootMotion {bone, facing, scale} are the animation graph definition of docs/animation-graph.md, with clip names from clips. drive maps a graph parameter to a controller value (speed|intentSpeed|airborne); default is speed from intentSpeed with rootMotion, else speed. With rootMotion the clips move the player.',
npcs: 'npcs [{node, path [[x, z] ...] up to 256 points, cruiseSpeed 2.2 m/s, footOffset 0, yaw 0, animation}], up to 16. Each NPC node is separate from the player and from other NPCs. Its animation needs rootMotion and a number parameter "speed": the path follower sets speed to blend idle, walk and run, moves by the root motion, turns at corners and stops at the last point.',
- notes: 'Use camera chase with a vehicle. Yaw 0 faces -Z; W moves forward. Zone checks use the feet position. physics true is accepted but the web export refuses it for now. scene_export_web writes the playable folder.',
+ notes: 'Use camera chase with a vehicle. Yaw 0 faces -Z; W moves forward. Zone checks use the feet position. physics true plays the recipe physics section (set-physics bodies, no joints) live with Jolt: bodies become real crates and balls, a kinematic body on the player node pushes them, and a rules zone sees a dynamic body by its node id. scene_export_web writes the playable folder.',
animationExample: Object.freeze({
type: 'set-game',
game: Object.freeze({
diff --git a/src/game.js b/src/game.js
index 452fceec..7f9aaf1c 100644
--- a/src/game.js
+++ b/src/game.js
@@ -8,6 +8,7 @@ import { createInput, gamepadSource, keyboardSource } from './input.js';
import { replaySource, touchSource } from './input-sources.js';
import { createCharacterController, createChaseCamera, createFirstPersonCamera, createFollowCamera, createTopDownCamera, createVehicleController } from './player.js';
import { createGameRules } from './game-rules.js';
+import { hasTexturedMaterial } from './game-needs.js';
// Plays the `game` section of a scene recipe in a page: the scene, the input preset, the character controller, the camera rig
// and the game rules, all run by the live runtime. scene_export_web writes a folder whose index.html calls startGame.
@@ -95,6 +96,11 @@ function createStatusLine(canvas) {
return element;
}
+function withoutPhysics(recipe) {
+ const { physics, ...rest } = recipe;
+ return rest;
+}
+
function modelYawOf(animation) {
return animation?.assetNode ? GLTF_FACING_YAW : 0;
}
@@ -112,7 +118,7 @@ async function loadAnimationRuntime() {
/**
* Start the game a recipe describes on a canvas and return its parts: `scene`, `runtime`, `rules`, `input`, `controller`, `renderer`
- * and `dispose()`. Options: `replay` (a recording from recordInput; the keyboard is not attached) `showStatus` (default true) `assets` (decoded catalog assets by assetCopyKey) or `assetUrls` (asset id to GLB URL, which startGame fetches and decodes) and `createRenderer` (tests pass a stand-in for the WebGL renderer).
+ * and `dispose()`. Options: `replay` (a recording from recordInput; the keyboard is not attached) `showStatus` (default true) `assets` (decoded catalog assets by assetCopyKey) or `assetUrls` (asset id to GLB URL, which startGame fetches and decodes), `physicsUrl` (where the page keeps jolt-physics.wasm.js, on its own origin; a recipe with game.physics true needs it unless the jolt-physics package resolves) and `createRenderer` (tests pass a stand-in for the WebGL renderer).
*/
export async function startGame(canvas, recipe, options = {}) {
const cleanups = [];
@@ -138,13 +144,16 @@ function runCleanups(cleanups) {
while (cleanups.length > 0) cleanups.pop()();
}
-async function buildGame(canvas, recipe, { replay, showStatus = true, assets: providedAssets, assetUrls, createRenderer = (...rendererArguments) => new Renderer67(...rendererArguments) }, cleanups) {
+async function buildGame(canvas, recipe, { replay, showStatus = true, assets: providedAssets, assetUrls, physicsUrl, createRenderer = (...rendererArguments) => new Renderer67(...rendererArguments) }, cleanups) {
const setup = recipe.game;
if (!setup) throw new Error('startGame needs a recipe with a game section. Add one with the set-game operation.');
- await loadAgentSceneModules(recipe);
+ // Live physics replaces the recorded bake of the same section, so the scene is built without it.
+ const sceneRecipe = setup.physics ? withoutPhysics(recipe) : recipe;
+ await loadAgentSceneModules(sceneRecipe);
+ if (hasTexturedMaterial(recipe)) await import('./replace-textured-parts.js');
// The exported page gives URLs; the assets load only for a recipe that places or retargets a catalog asset.
const assets = providedAssets ?? (assetUrls ? await (await import('./game-assets.js')).loadGameAssets(recipe, assetUrls) : undefined);
- const scene = createAgentScene(recipe, {}, { assets });
+ const scene = createAgentScene(sceneRecipe, {}, { assets });
const { game } = scene.exportRecipe();
const placement = agentGroundPlacement(scene.parts, scene.environment);
const environment = litEnvironment(scene, Boolean(placement));
@@ -185,8 +194,14 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, assets: pr
});
rig = cameraRigFor(game.camera, controller, input);
+ const physics = game.physics ? await (await import('./game-physics.js')).createGamePhysics({ recipe, scene, playerNode: game.player.node, physicsUrl }) : null;
+ if (physics) cleanups.push(() => physics.dispose());
+ const physicsSystem = physics && {
+ name: 'game-physics',
+ fixedUpdate: (stepSeconds, context) => physics.fixedUpdate(stepSeconds, context, physics.playerIsBody ? [controller.state.position[0], controller.state.position[1] + footOffset, controller.state.position[2]] : null, body.rotationY),
+ };
const nodeIds = new Set(recipe.nodes.map(node => node.id));
- const rules = game.rules ? createGameRules(game.rules, { input, getPartPosition: id => (id === game.player.node ? [...controller.state.position] : undefined) }) : null;
+ const rules = game.rules ? createGameRules(game.rules, { input, getPartPosition: id => (id === game.player.node ? [...controller.state.position] : physics?.positionOf(id)) }) : null;
const shownNodes = new Map();
const animatedCharacters = [];
const animationSystems = [];
@@ -215,6 +230,7 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, assets: pr
const operations = [characterOperation(game.player.node, position, body.rotationY, footOffset, modelYawOf(playerAnimation))];
for (const npc of npcs) operations.push(characterOperation(npc.node, npc.follower.state.position, npc.follower.state.yaw, npc.footOffset, npc.modelYaw));
for (const animation of animatedCharacters) operations.push(...animation.operations());
+ if (physics) operations.push(...physics.poseOperations());
for (const part of rules?.state.parts ?? []) {
if (!nodeIds.has(part.id) || part.id === game.player.node || shownNodes.get(part.id) === part.visible) continue;
shownNodes.set(part.id, part.visible);
@@ -238,7 +254,7 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, assets: pr
const baseCamera = scene.camera;
const runtime = createRuntime(renderer, {
fixedRate: 60,
- systems: [input, controller, ...animationSystems, rig, ...(rules ? [rules] : []), sceneSystem],
+ systems: [input, controller, ...animationSystems, rig, ...(physicsSystem ? [physicsSystem] : []), ...(rules ? [rules] : []), sceneSystem],
frame: context => ({ ...baseCamera, ...rig.pose(context), environment, time: context.elapsedSeconds }),
});
cleanups.push(() => runtime.dispose());
@@ -248,5 +264,5 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, assets: pr
resize();
runtime.start();
- return { scene, runtime, rules, input, controller, renderer, animation: playerAnimation?.graph ?? null, npcs };
+ return { scene, runtime, rules, input, controller, renderer, physics: physics?.system ?? null, animation: playerAnimation?.graph ?? null, npcs };
}
diff --git a/src/physics-jolt.js b/src/physics-jolt.js
index 13500a03..351562ea 100644
--- a/src/physics-jolt.js
+++ b/src/physics-jolt.js
@@ -16,9 +16,12 @@ const INSTALL_HINT = 'Install it with `npm install jolt-physics`, or build the s
let joltPromise;
let joltModule;
-/** Load the Jolt wasm module once. */
-export function loadJoltEngine() {
- joltPromise ??= import('jolt-physics').then(async module => {
+/**
+ * Load the Jolt wasm module once. A page that ships its own copy passes `moduleUrl`, the absolute URL of
+ * jolt-physics.wasm.js; that file fetches the .wasm file next to it, so nothing loads from another origin.
+ */
+export function loadJoltEngine({ moduleUrl } = {}) {
+ joltPromise ??= (moduleUrl === undefined ? import('jolt-physics') : import(/* @vite-ignore */ moduleUrl)).then(async module => {
joltModule = await (module.default ?? module)();
return joltModule;
}, error => {
diff --git a/tests/game-physics.test.js b/tests/game-physics.test.js
new file mode 100644
index 00000000..317122a9
--- /dev/null
+++ b/tests/game-physics.test.js
@@ -0,0 +1,193 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { access, mkdtemp, readdir, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createAgentScene } from '../src/agent-scene.js';
+import { loadPhysicsEngine } from '../src/agent-physics.js';
+import { startGame } from '../src/game.js';
+import { gamePhysicsProblem, hasTexturedMaterial } from '../src/game-needs.js';
+import { engineModuleNames, indexHtml, writeWebBuild, WEB_EXPORT_LIMITS } from '../scripts/web-export.mjs';
+
+const EMPTY_RECORDING = { version: 1, samples: 0, events: [] };
+const STEP_MILLISECONDS = 1000 / 60;
+
+// A crate dropped on a floor, and a pocket zone the crate must land in. The player stands off to one side.
+function physicsRecipe(overrides = {}) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],
+ nodes: [
+ { id: 'floor', geometry: 'block', material: 'paint', translation: [0, -0.25, 0], scale: [10, 0.5, 10] },
+ { id: 'hero', geometry: 'block', material: 'paint', translation: [4, 0.8, 0], scale: [0.6, 1.6, 0.6] },
+ { id: 'crate', geometry: 'block', material: 'paint', translation: [0, 3, 0] },
+ ],
+ physics: {
+ duration: 1,
+ bodies: [{ node: 'floor', type: 'fixed', shape: 'box' }, { node: 'hero', type: 'kinematic', shape: 'capsule' }, { node: 'crate', shape: 'box' }],
+ },
+ game: {
+ player: { node: 'hero', footOffset: 0.8 }, camera: 'follow', input: 'keyboard', physics: true, ground: 0,
+ rules: {
+ version: 1,
+ zones: [{ id: 'pocket', shape: 'box', center: [0, 0.5, 0], size: [2, 2, 2] }],
+ parts: [{ id: 'hero', tags: ['player'] }, { id: 'crate', tags: ['crate'] }],
+ rules: [{ id: 'land', when: { type: 'enter', zone: 'pocket', tag: 'crate' }, do: [{ type: 'win' }] }],
+ },
+ },
+ ...overrides,
+ };
+}
+
+// The recipe as the MCP session exports it: normalised, with the physics section checked against its nodes.
+async function exportedRecipe(overrides) {
+ await loadPhysicsEngine();
+ return createAgentScene(physicsRecipe(overrides)).exportRecipe();
+}
+
+function standInRenderer() {
+ return { render() {}, resize() {}, updateParts() {}, replaceParts() {}, dispose() {} };
+}
+
+async function playFor(recipe, seconds) {
+ const game = await startGame({}, recipe, { replay: EMPTY_RECORDING, showStatus: false, createRenderer: () => standInRenderer() });
+ for (let step = 0; step < seconds * 60; step++) game.runtime.step(STEP_MILLISECONDS);
+ return game;
+}
+
+function withAnimationFrameStubs() {
+ const previous = { request: globalThis.requestAnimationFrame, cancel: globalThis.cancelAnimationFrame };
+ globalThis.requestAnimationFrame = () => 1;
+ globalThis.cancelAnimationFrame = () => {};
+ return () => {
+ globalThis.requestAnimationFrame = previous.request;
+ globalThis.cancelAnimationFrame = previous.cancel;
+ };
+}
+
+test('a game with physics steps its bodies, moves their nodes and lets a rules zone see them', async () => {
+ const restore = withAnimationFrameStubs();
+ try {
+ const game = await playFor(await exportedRecipe(), 2);
+ assert.equal(game.physics.adapter, 'jolt');
+ const crate = game.physics.getPose('crate').translation;
+ assert.ok(Math.abs(crate[1] - 0.5) < 0.05, `the crate rests on the floor, y ${crate[1]}`);
+ const node = game.scene.exportRecipe().nodes.find(candidate => candidate.id === 'crate');
+ assert.ok(Math.abs(node.translation[1] - crate[1]) < 1e-6, 'the crate node follows its body');
+ assert.equal(game.rules.state.status, 'won', 'the crate landing in the pocket zone fires the rule');
+ game.dispose();
+ } finally {
+ restore();
+ }
+});
+
+test('the same recipe plays the same physics twice', async () => {
+ const restore = withAnimationFrameStubs();
+ try {
+ const poses = [];
+ for (let run = 0; run < 2; run++) {
+ const game = await playFor(await exportedRecipe(), 1);
+ poses.push(JSON.stringify(game.physics.getPose('crate')));
+ game.dispose();
+ }
+ assert.equal(poses[0], poses[1]);
+ } finally {
+ restore();
+ }
+});
+
+test('the kinematic player body pushes a dynamic crate', async () => {
+ const restore = withAnimationFrameStubs();
+ try {
+ const recipe = await exportedRecipe();
+ recipe.nodes.find(node => node.id === 'crate').translation = [3, 0.5, 0];
+ delete recipe.game.rules;
+ const walkRight = { version: 1, samples: 120, truncated: false, events: [[1, 'keyboard/KeyA', 1]] };
+ const game = await startGame({}, recipe, { replay: walkRight, showStatus: false, createRenderer: () => standInRenderer() });
+ for (let step = 0; step < 120; step++) game.runtime.step(STEP_MILLISECONDS);
+ assert.ok(game.physics.getPose('crate').translation[0] < 2.5, 'walking left drives the crate along');
+ game.dispose();
+ } finally {
+ restore();
+ }
+});
+
+test('a game without physics starts none and does not load the engine files', async () => {
+ const restore = withAnimationFrameStubs();
+ try {
+ const recipe = await exportedRecipe();
+ recipe.game.physics = false;
+ delete recipe.game.rules;
+ const game = await startGame({}, recipe, { replay: EMPTY_RECORDING, showStatus: false, createRenderer: () => standInRenderer() });
+ assert.equal(game.physics, null);
+ game.dispose();
+ } finally {
+ restore();
+ }
+});
+
+test('a physics game without a body list, with joints or with an unsupported shape says what to change', () => {
+ assert.match(gamePhysicsProblem({}), /no physics section with bodies.*set-physics/);
+ assert.match(gamePhysicsProblem(physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'crate', type: 'dynamic', shape: 'box' }], joints: [{ type: 'fixed' }] } })), /no joints or ragdolls/);
+ assert.match(gamePhysicsProblem(physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'floor', type: 'fixed', shape: 'trimesh' }] } })), /Body "floor" has shape trimesh.*shape "box"/);
+ assert.equal(gamePhysicsProblem(physicsRecipe()), null);
+});
+
+test('the page may only load the physics engine from its own origin', async () => {
+ const recipe = await exportedRecipe();
+ const previous = globalThis.location;
+ globalThis.location = { href: 'http://example.test/index.html', origin: 'http://example.test' };
+ try {
+ await assert.rejects(
+ startGame({}, recipe, { replay: EMPTY_RECORDING, showStatus: false, physicsUrl: 'https://evil.test/jolt-physics.wasm.js', createRenderer: () => standInRenderer() }),
+ /physicsUrl must be on the page's own origin/,
+ );
+ } finally {
+ globalThis.location = previous;
+ }
+});
+
+async function physicsBuild() {
+ const build = await mkdtemp(join(tmpdir(), '67js-physics-build-'));
+ await writeFile(join(build, 'game.js'), 'import { a } from "./chunk-a.js";\nconst physics = () => import("./game-physics-abc123.js");\nconst swap = () => import("./replace-textured-parts.js");\n');
+ await writeFile(join(build, 'chunk-a.js'), 'export const a = 1;');
+ await writeFile(join(build, 'game-physics-abc123.js'), 'import "./physics-runtime.js";');
+ await writeFile(join(build, 'physics-runtime.js'), 'export {};');
+ await writeFile(join(build, 'replace-textured-parts.js'), 'export {};');
+ return build;
+}
+
+test('the web export bundles the physics engine and its wasm beside the page only for a physics game', async () => {
+ const build = await physicsBuild();
+ assert.deepEqual(await engineModuleNames(build), ['chunk-a.js', 'game.js']);
+ assert.deepEqual(await engineModuleNames(build, { physics: true, textured: true }), ['chunk-a.js', 'game-physics-abc123.js', 'game.js', 'physics-runtime.js', 'replace-textured-parts.js']);
+
+ const plain = join(await mkdtemp(join(tmpdir(), '67js-web-plain-')), 'site');
+ await writeWebBuild({ recipe: physicsRecipe({ game: { ...physicsRecipe().game, physics: false } }), buildDirectory: build, outputDirectory: plain });
+ assert.deepEqual((await readdir(join(plain, 'engine'))).sort(), ['chunk-a.js', 'game.js']);
+ await assert.rejects(access(join(plain, 'engine', 'physics')));
+
+ const withPhysics = join(await mkdtemp(join(tmpdir(), '67js-web-physics-')), 'site');
+ const summary = await writeWebBuild({ recipe: physicsRecipe(), buildDirectory: build, outputDirectory: withPhysics });
+ assert.deepEqual((await readdir(join(withPhysics, 'engine', 'physics'))).sort(), ['jolt-physics.wasm.js', 'jolt-physics.wasm.wasm']);
+ assert.ok(summary.bytes > 1024 * 1024 && summary.bytes < WEB_EXPORT_LIMITS.maxEngineBytes, `physics export bytes ${summary.bytes}`);
+ const html = await (await import('node:fs/promises')).readFile(join(withPhysics, 'index.html'), 'utf8');
+ assert.match(html, /const physicsUrl = "\.\/engine\/physics\/jolt-physics\.wasm\.js";/);
+ assert.match(html, /startGame\(canvas, recipe, \{ replay, assetUrls, physicsUrl \}\)/);
+ assert.doesNotMatch(html, /https?:\/\//);
+ assert.doesNotMatch(indexHtml('plain'), /physicsUrl/);
+});
+
+test('the web export refuses physics it cannot play before it writes anything', async () => {
+ const build = await physicsBuild();
+ const recipe = physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'crate', shape: 'box' }], joints: [{ type: 'fixed', bodyA: 'crate', bodyB: 'floor' }] } });
+ await assert.rejects(writeWebBuild({ recipe, buildDirectory: build, outputDirectory: join(await mkdtemp(join(tmpdir(), '67js-web-refuse-')), 'site') }), /no joints or ragdolls/);
+});
+
+test('only a recipe with a pattern or a map is textured', () => {
+ assert.equal(hasTexturedMaterial(physicsRecipe()), false);
+ assert.equal(hasTexturedMaterial({ materials: [{ id: 'm', pattern: { type: 'bricks' } }] }), true);
+ assert.equal(hasTexturedMaterial({ materials: [{ id: 'm', normalMap: 'x' }] }), true);
+});
diff --git a/tests/game-setup.test.js b/tests/game-setup.test.js
index 452fa941..d7e3510b 100644
--- a/tests/game-setup.test.js
+++ b/tests/game-setup.test.js
@@ -124,7 +124,7 @@ test('the web export refuses what it cannot play and says how to fix it', async
const out = () => mkdtemp(join(tmpdir(), '67js-web-refuse-'));
const game = { player: { node: 'creature' } };
await assert.rejects(async () => writeWebBuild({ recipe: recipeWith(), buildDirectory: build, outputDirectory: await out() }), /no game.*set-game/);
- await assert.rejects(async () => writeWebBuild({ recipe: recipeWith({ ...game, physics: true }), buildDirectory: build, outputDirectory: await out() }), /Set game\.physics to false/);
+ await assert.rejects(async () => writeWebBuild({ recipe: recipeWith({ ...game, physics: true }), buildDirectory: build, outputDirectory: await out() }), /no physics section.*set game\.physics to false/s);
const placed = recipeWith(game);
placed.nodes.push({ id: 'tree', asset: { id: 'a'.repeat(64) } });
await assert.rejects(async () => writeWebBuild({ recipe: placed, buildDirectory: build, outputDirectory: await out() }), /needs the bytes of the catalog assets placed by tree/);