Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add deterministic animation, motion example and portrait media export

Nguyen Xuan An3a3036a7a6ba
diff --git a/motion.html b/motion.html
new file mode 100644
index 00000000..6bacd5c8
--- /dev/null
+++ b/motion.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#171c20" />
+ <meta name="description" content="A deterministic 67.js animation with keyframe tracks and landscape, portrait and square compositions." />
+ <title>Clockwork orbit · 67.js</title>
+ </head>
+ <body>
+ <main>
+ <header class="interface motion-header">
+ <a class="brand" href="./index.html" aria-label="67.js home">67<span>.js</span></a>
+ <nav aria-label="Scenes"><a href="./object.html">Object</a><a href="./nature.html">Nature</a><a href="./film.html">Film</a><a href="./motion.html" aria-current="page">Motion</a></nav>
+ </header>
+ <section class="motion-stage" data-aspect="landscape" aria-label="Clockwork orbit animation">
+ <canvas id="motion-canvas" tabindex="0" aria-label="Animated clockwork mechanism. Use Space to pause and arrow keys to move through the timeline."></canvas>
+ </section>
+ <section class="interface motion-controls" aria-label="Animation controls">
+ <div class="description"><h1>Clockwork orbit</h1><p>A mechanism in motion, sampled from keyframes</p></div>
+ <div class="playback-controls"><button id="motion-play" aria-label="Play animation">▶ Play</button><button id="motion-replay">Replay</button><label for="motion-aspect">Frame <select id="motion-aspect"><option value="landscape">16:9 Landscape</option><option value="portrait">9:16 Portrait</option><option value="square">1:1 Square</option></select></label></div>
+ <label class="timeline-label" for="motion-time">Timeline <output id="motion-clock">0.0 / 12.0 s</output></label>
+ <input id="motion-time" type="range" min="0" max="12" step="0.01" value="0" />
+ <div class="motion-details"><span id="motion-shot">Shot 1 of 3</span><span id="motion-stat"></span></div>
+ </section>
+ <p class="interface motion-error" id="motion-error" role="status" hidden></p>
+ </main>
+ <script type="module" src="/src/motion-player.js"></script>
+ </body>
+</html>
diff --git a/scripts/render-media.mjs b/scripts/render-media.mjs
index a469c5ba..4e8130bb 100644
--- a/scripts/render-media.mjs
+++ b/scripts/render-media.mjs
@@ -1,5 +1,5 @@
import { chromium } from 'playwright';
-import { spawn, execFile } from 'node:child_process';
+import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { mkdir, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
@@ -9,162 +9,203 @@ import { RENDER_PRESETS } from '../src/budget.js';
function argumentsFrom(values) {
const result = {};
+ const allowed = new Set(['kind', 'backend', 'scene', 'preset', 'width', 'height', 'fps', 'duration', 'time', 'memory', 'assembly', 'output', 'audio', 'encoder', 'start', 'aspect']);
for (let index = 0; index < values.length; index += 2) {
if (!values[index].startsWith('--') || values[index + 1] === undefined) throw new Error('Every option needs a value.');
- result[values[index].slice(2)] = values[index + 1];
+ const name = values[index].slice(2);
+ if (!allowed.has(name)) throw new Error(`Unknown render option: ${name}`);
+ result[name] = values[index + 1];
}
return result;
}
-const options = argumentsFrom(process.argv.slice(2));
-const kind = options.kind ?? 'image';
-const backend = options.backend ?? 'gpu';
-const scene = options.scene ?? 'film';
-const presetName = options.preset ?? (backend === 'cpu' ? 'cpu' : 'balanced');
-const preset = RENDER_PRESETS[presetName];
-if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object'].includes(scene)) throw new Error('Unknown render kind, backend, scene or preset.');
-const numberOption = (name, fallback, minimum, maximum) => {
- const value = Number(options[name] ?? fallback);
- if (!Number.isFinite(value) || value < minimum || value > maximum) throw new Error(`${name} must be between ${minimum} and ${maximum}.`);
- return value;
-};
-const width = Math.round(numberOption('width', preset.width, 64, 4096));
-const height = Math.round(numberOption('height', preset.height, 64, 4096));
-const fps = numberOption('fps', preset.fps, 1, 60);
-const duration = numberOption('duration', 32, 0.1, 120);
-const time = numberOption('time', 3, 0, 32);
-const memory = numberOption('memory', preset.memoryBudgetMiB, 32, 1024);
-const assembly = numberOption('assembly', 0, 0, 1);
-const output = resolve(options.output ?? `artifacts/${scene}-${backend}.${kind === 'video' ? 'mp4' : 'png'}`);
-await mkdir(dirname(output), { recursive: true });
-const root = fileURLToPath(new URL('..', import.meta.url));
-const ffmpeg = process.platform === 'win32' ? resolve(process.env.USERPROFILE, '.local/bin/ffmpeg.exe') : 'ffmpeg';
-const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
-const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--config', 'scripts/render-vite.config.mjs', '--host', '127.0.0.1', '--port', '5181', '--strictPort'], { cwd: root, windowsHide: true, stdio: 'pipe' });
-let browser;
-let encoder;
-let encoderError = '';
-let peakNodeBytes = 0;
-let peakBrowserHeap = 0;
-let peakEstimatedRenderBytes = 0;
-let maximumPendingFrames = 0;
-let firstFrameBytes = 0;
-let actualRenderSize;
-const started = performance.now();
-const progress = [];
-try {
- await new Promise((resolveStarted, reject) => {
- const timeout = setTimeout(() => reject(new Error('Render server did not start.')), 15000);
- server.stdout.on('data', (data) => {
- if (data.toString().includes('127.0.0.1:5181')) { clearTimeout(timeout); resolveStarted(); }
- });
- server.on('error', reject);
- server.on('exit', (code) => { clearTimeout(timeout); reject(new Error(`Render server exited ${code}.`)); });
- });
- const args = ['--enable-webgl', '--ignore-gpu-blocklist'];
- if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
- browser = await chromium.launch({ headless: true, ...(existsSync(chrome) ? { executablePath: chrome } : {}), args });
- const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
- const errors = [];
- page.on('pageerror', (error) => errors.push(error.message));
- const route = scene === 'object' ? 'object.html' : `${scene}.html`;
- const query = new URLSearchParams({ export: '1', width: String(width), height: String(height), memory: String(memory), samples: String(backend === 'cpu' ? 1 : preset.samples) });
- await page.goto(`http://127.0.0.1:5181/${route}?${query}`);
- await page.waitForFunction((mode) => mode === 'film' ? window.__filmReady : mode === 'nature' ? window.__nature : window.__studio, scene, { timeout: 60000 });
- if (scene !== 'film') await page.evaluate(({ memory, width, height, samples, scene, assembly }) => {
- const canvas = document.querySelector('canvas');
- canvas.style.cssText = `position:fixed;inset:0;width:${width}px;height:${height}px`;
- document.querySelectorAll('main > :not(canvas)').forEach((element) => {
- element.hidden = true;
- element.style.setProperty('display', 'none', 'important');
- });
- const renderer = scene === 'object' ? window.__studio.renderer : window.__nature.renderer;
- renderer.memoryBudgetMiB = memory;
- renderer.pixelRatio = 1;
- renderer.samples = samples;
- renderer.resize();
- if (scene === 'object') {
- window.__studio.state.exporting = true;
- window.__studio.state.assembly = assembly;
- renderer.projection[8] = 0;
- window.renderAt = () => renderer.render(window.__studio.camera());
- } else window.renderAt = (time) => window.__nature.renderAt(time);
- }, { memory, width, height, samples: backend === 'cpu' ? 1 : preset.samples, scene, assembly });
- const session = await page.context().newCDPSession(page);
- const render = async (seconds) => {
- await page.evaluate((value) => {
- if (window.renderAt) window.renderAt(value);
- else window.__nature.renderAt(value);
- }, seconds);
- const rendererPlan = await page.evaluate(() => {
- const renderer = window.__film?.renderer ?? window.__nature?.renderer ?? window.__studio?.renderer;
- return renderer.memoryPlan;
- });
- peakEstimatedRenderBytes = Math.max(peakEstimatedRenderBytes, rendererPlan.estimatedBytes);
- actualRenderSize = { width: rendererPlan.width, height: rendererPlan.height, reduced: rendererPlan.reduced };
- if (rendererPlan.estimatedBytes > memory * 1024 ** 2) throw new Error('Render target exceeded the configured memory budget.');
- const nodeBytes = process.memoryUsage().rss;
- peakNodeBytes = Math.max(peakNodeBytes, nodeBytes);
- if (nodeBytes > 512 * 1024 ** 2) throw new Error('Capture process exceeded 512 MiB. Export stopped before buffering more frames.');
+export function parseRenderOptions(values) {
+ const options = argumentsFrom(values);
+ const kind = options.kind ?? 'image';
+ const backend = options.backend ?? 'gpu';
+ const scene = options.scene ?? 'film';
+ const presetName = options.preset ?? (backend === 'cpu' ? 'cpu' : 'balanced');
+ const preset = RENDER_PRESETS[presetName];
+ const aspect = options.aspect ?? 'landscape';
+ if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object', 'motion', 'view2d'].includes(scene) || !['landscape', 'portrait', 'square'].includes(aspect)) throw new Error('Unknown render kind, backend, scene, aspect or preset.');
+ const numberOption = (name, fallback, minimum, maximum) => {
+ const value = Number(options[name] ?? fallback);
+ if (!Number.isFinite(value) || value < minimum || value > maximum) throw new Error(`${name} must be between ${minimum} and ${maximum}.`);
+ return value;
};
- async function capture(seconds) {
- await render(seconds);
- const image = await page.screenshot({ type: 'png', animations: 'disabled' });
- if (!firstFrameBytes) firstFrameBytes = image.byteLength;
- return image;
- }
- if (kind === 'video') {
- const codec = options.encoder ?? 'cpu';
- if (!['cpu', 'gpu'].includes(codec)) throw new Error('Encoder must be cpu or gpu.');
- const audioPath = resolve(options.audio ?? 'artifacts/critical-score.wav');
- const audioArguments = existsSync(audioPath) ? ['-i', audioPath] : [];
- const codecArguments = codec === 'gpu' ? ['-c:v', 'h264_nvenc', '-preset', 'p5', '-cq', '20'] : ['-c:v', 'libx264', '-preset', 'fast', '-crf', '18', '-threads', '2'];
- const encodingArguments = ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-vcodec', 'png', '-i', 'pipe:0', ...audioArguments, ...codecArguments, '-pix_fmt', 'yuv420p', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-movflags', '+faststart', ...(audioArguments.length ? ['-c:a', 'aac', '-b:a', '192k', '-shortest'] : []), output];
- encoder = spawn(ffmpeg, encodingArguments, { windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] });
- encoder.stderr.on('data', (data) => { encoderError += data.toString(); });
- encoder.on('error', (error) => { encoderError += error.message; });
- encoder.stdin.on('error', (error) => { encoderError += error.message; });
- const finished = once(encoder, 'close');
- const frameCount = Math.ceil(duration * fps);
- for (let frame = 0; frame < frameCount; frame++) {
- const image = await capture(frame / fps);
- maximumPendingFrames = Math.max(maximumPendingFrames, 1);
- if (encoder.exitCode !== null) throw new Error(`Video encoder stopped: ${encoderError}`);
- if (!encoder.stdin.write(image)) await once(encoder.stdin, 'drain');
- if (frame % 48 === 0) {
- const { usedSize } = await session.send('Runtime.getHeapUsage');
- peakBrowserHeap = Math.max(peakBrowserHeap, usedSize);
- if (usedSize > 256 * 1024 ** 2) throw new Error('Browser JavaScript heap exceeded 256 MiB. Export stopped.');
- const message = `Rendered ${frame + 1}/${frameCount} frames`;
- progress.push(message);
- console.log(message);
- }
+ const shorter = Math.min(preset.width, preset.height);
+ const longer = Math.max(preset.width, preset.height);
+ const ratio = aspect === 'portrait' ? 9 / 16 : aspect === 'square' ? 1 : 16 / 9;
+ let defaultWidth = aspect === 'landscape' ? longer : shorter;
+ let defaultHeight = aspect === 'portrait' ? longer : shorter;
+ if (options.width !== undefined && options.height === undefined) defaultHeight = Number(options.width) / ratio;
+ if (options.height !== undefined && options.width === undefined) defaultWidth = Number(options.height) * ratio;
+ const width = Math.round(numberOption('width', defaultWidth, 64, 4096));
+ const height = Math.round(numberOption('height', defaultHeight, 64, 4096));
+ if (kind === 'video' && (width % 2 || height % 2)) throw new Error('Video dimensions must be even for yuv420p output.');
+ const fps = numberOption('fps', preset.fps, 1, 60);
+ const duration = numberOption('duration', scene === 'motion' ? 12 : 32, 0.1, 120);
+ const time = numberOption('time', 3, 0, 3600);
+ const start = numberOption('start', 0, 0, 3600);
+ const memory = numberOption('memory', preset.memoryBudgetMiB, 32, 1024);
+ const assembly = numberOption('assembly', 0, 0, 1);
+ const output = resolve(options.output ?? `artifacts/${scene}-${backend}.${kind === 'video' ? 'mp4' : 'png'}`);
+ const encoderBackend = options.encoder ?? 'cpu';
+ if (!['cpu', 'gpu'].includes(encoderBackend)) throw new Error('Encoder must be cpu or gpu.');
+ const audio = options.audio ?? (scene === 'film' ? 'artifacts/critical-score.wav' : null);
+ return { options, kind, backend, scene, presetName, preset, aspect, width, height, fps, duration, time, start, memory, assembly, output, encoderBackend, audio };
+}
+
+export async function renderMedia(values = process.argv.slice(2)) {
+ const plan = parseRenderOptions(values);
+ const { options, kind, backend, scene, presetName, preset, aspect, width, height, fps, time, start, memory, assembly, output, encoderBackend } = plan;
+ let duration = plan.duration;
+ await mkdir(dirname(output), { recursive: true });
+ const root = fileURLToPath(new URL('..', import.meta.url));
+ const ffmpeg = process.platform === 'win32' ? resolve(process.env.USERPROFILE, '.local/bin/ffmpeg.exe') : 'ffmpeg';
+ const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--config', 'scripts/render-vite.config.mjs', '--host', '127.0.0.1', '--port', '5181', '--strictPort'], { cwd: root, windowsHide: true, stdio: 'pipe' });
+ let browser;
+ let encoder;
+ let encoderError = '';
+ let peakNodeBytes = 0;
+ let peakBrowserHeap = 0;
+ let peakEstimatedRenderBytes = 0;
+ let maximumPendingFrames = 0;
+ let firstFrameBytes = 0;
+ let actualRenderSize;
+ const started = performance.now();
+ try {
+ await new Promise((resolveStarted, reject) => {
+ const timeout = setTimeout(() => reject(new Error('Render server did not start.')), 15000);
+ server.stdout.on('data', (data) => {
+ if (data.toString().includes('127.0.0.1:5181')) { clearTimeout(timeout); resolveStarted(); }
+ });
+ server.on('error', reject);
+ server.on('exit', (code) => { clearTimeout(timeout); reject(new Error(`Render server exited ${code}.`)); });
+ });
+ const args = ['--enable-webgl', '--ignore-gpu-blocklist'];
+ if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
+ browser = await chromium.launch({ headless: true, ...(existsSync(chrome) ? { executablePath: chrome } : {}), args });
+ const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ const route = scene === 'object' ? 'object.html' : `${scene}.html`;
+ const query = new URLSearchParams({ export: '1', width: String(width), height: String(height), aspect, memory: String(memory), samples: String(backend === 'cpu' ? 1 : preset.samples) });
+ await page.goto(`http://127.0.0.1:5181/${route}?${query}`);
+ await page.waitForFunction((mode) => window.__scene?.renderer || (mode === 'film' ? window.__filmReady : mode === 'nature' ? window.__nature?.renderer : mode === 'object' ? window.__studio?.renderer : false), scene, { timeout: 60000 });
+ const sceneDuration = await page.evaluate(() => window.__scene?.duration ?? (window.__film ? 32 : null));
+ if (Number.isFinite(sceneDuration) && sceneDuration > 0) {
+ if (start >= sceneDuration) throw new Error('Start time must precede the end of the scene.');
+ if (options.duration === undefined) duration = Math.min(120, sceneDuration - start);
+ else if (kind === 'video' && start + duration > sceneDuration + 1e-8) throw new Error('The requested video extends beyond the scene duration.');
+ if (kind === 'image' && time > sceneDuration) throw new Error('Image time exceeds the scene duration.');
+ }
+ if (scene !== 'film') await page.evaluate(({ memory, width, height, samples, scene, assembly }) => {
+ const canvas = document.querySelector('canvas');
+ canvas.style.cssText = `position:fixed;inset:0;width:${width}px;height:${height}px`;
+ document.querySelectorAll('body > *, main > *').forEach((element) => {
+ if (element === canvas || element.contains(canvas)) return;
+ element.hidden = true;
+ element.style.setProperty('display', 'none', 'important');
+ });
+ window.__scene?.pause?.();
+ const renderer = window.__scene?.renderer ?? (scene === 'object' ? window.__studio.renderer : window.__nature.renderer);
+ renderer.memoryBudgetMiB = memory;
+ renderer.pixelRatio = 1;
+ renderer.samples = samples;
+ renderer.resize();
+ if (window.__scene) return;
+ if (scene === 'object') {
+ window.__studio.state.exporting = true;
+ window.__studio.state.assembly = assembly;
+ renderer.projection[8] = 0;
+ window.renderAt = () => renderer.render(window.__studio.camera());
+ } else window.renderAt = (time) => window.__nature.renderAt(time);
+ }, { memory, width, height, samples: backend === 'cpu' ? 1 : preset.samples, scene, assembly });
+ const session = await page.context().newCDPSession(page);
+ const render = async (seconds) => {
+ if (errors.length) throw new Error(`Browser render errors: ${errors.join('; ')}`);
+ await page.evaluate((value) => {
+ if (window.__scene) window.__scene.renderAt(value);
+ else if (window.renderAt) window.renderAt(value);
+ else window.__nature.renderAt(value);
+ }, seconds);
+ const rendererPlan = await page.evaluate(() => {
+ const renderer = window.__scene?.renderer ?? window.__film?.renderer ?? window.__nature?.renderer ?? window.__studio?.renderer;
+ const glError = renderer.context.getError();
+ if (glError !== 0) throw new Error(`WebGL render error ${glError}.`);
+ return renderer.memoryPlan;
+ });
+ peakEstimatedRenderBytes = Math.max(peakEstimatedRenderBytes, rendererPlan.estimatedBytes);
+ actualRenderSize = { width: rendererPlan.width, height: rendererPlan.height, reduced: rendererPlan.reduced };
+ if (rendererPlan.estimatedBytes > memory * 1024 ** 2) throw new Error('Render target exceeded the configured memory budget.');
+ const nodeBytes = process.memoryUsage().rss;
+ peakNodeBytes = Math.max(peakNodeBytes, nodeBytes);
+ if (nodeBytes > 512 * 1024 ** 2) throw new Error('Capture process exceeded 512 MiB. Export stopped before buffering more frames.');
+ };
+ async function capture(seconds) {
+ await render(seconds);
+ const image = await page.screenshot({ type: 'png', animations: 'disabled' });
+ if (!firstFrameBytes) firstFrameBytes = image.byteLength;
+ return image;
}
- encoder.stdin.end();
- const [exitCode] = await finished;
- if (exitCode !== 0) throw new Error(`Video encoding failed: ${encoderError}`);
- } else if (kind === 'stills') {
- for (const seconds of [2.5, 7.5, 11.5, 15, 18, 22, 25, 29.5]) {
- const image = await capture(seconds);
- await writeFile(resolve(dirname(output), `frame-${seconds.toFixed(1)}.png`), image);
+ if (kind === 'video') {
+ const audioPath = plan.audio ? resolve(plan.audio) : null;
+ if (options.audio && !existsSync(audioPath)) throw new Error('The selected audio file was not found.');
+ const audioArguments = audioPath && existsSync(audioPath) ? ['-ss', String(start), '-i', audioPath] : [];
+ const codecArguments = encoderBackend === 'gpu' ? ['-c:v', 'h264_nvenc', '-preset', 'p5', '-cq', '20'] : ['-c:v', 'libx264', '-preset', 'fast', '-crf', '18', '-threads', '2'];
+ const encodingArguments = ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-vcodec', 'png', '-i', 'pipe:0', ...audioArguments, ...codecArguments, '-pix_fmt', 'yuv420p', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-movflags', '+faststart', ...(audioArguments.length ? ['-c:a', 'aac', '-b:a', '192k', '-shortest'] : []), output];
+ encoder = spawn(ffmpeg, encodingArguments, { windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] });
+ encoder.stderr.on('data', (data) => { encoderError += data.toString(); });
+ encoder.on('error', (error) => { encoderError += error.message; });
+ encoder.stdin.on('error', (error) => { encoderError += error.message; });
+ const finished = once(encoder, 'close');
+ const frameCount = Math.ceil(duration * fps);
+ for (let frame = 0; frame < frameCount; frame++) {
+ const image = await capture(start + frame / fps);
+ maximumPendingFrames = Math.max(maximumPendingFrames, 1);
+ if (encoder.exitCode !== null) throw new Error(`Video encoder stopped: ${encoderError}`);
+ if (!encoder.stdin.write(image)) await once(encoder.stdin, 'drain');
+ if (frame % 48 === 0) {
+ const { usedSize } = await session.send('Runtime.getHeapUsage');
+ peakBrowserHeap = Math.max(peakBrowserHeap, usedSize);
+ if (usedSize > 256 * 1024 ** 2) throw new Error('Browser JavaScript heap exceeded 256 MiB. Export stopped.');
+ const message = `Rendered ${frame + 1}/${frameCount} frames`;
+ console.log(message);
+ }
+ }
+ encoder.stdin.end();
+ const [exitCode] = await finished;
+ if (exitCode !== 0) throw new Error(`Video encoding failed: ${encoderError}`);
+ } else if (kind === 'stills') {
+ const stillTimes = scene === 'film' && start === 0 && options.duration === undefined
+ ? [2.5, 7.5, 11.5, 15, 18, 22, 25, 29.5]
+ : Array.from({ length: 8 }, (_, index) => start + duration * (index + 0.5) / 8);
+ for (const seconds of stillTimes) {
+ const image = await capture(seconds);
+ await writeFile(resolve(dirname(output), `frame-${seconds.toFixed(1)}.png`), image);
+ }
+ } else {
+ await writeFile(output, await capture(time));
}
- } else {
- await writeFile(output, await capture(time));
+ if (errors.length) throw new Error(`Browser render errors: ${errors.join('; ')}`);
+ const graphics = await page.evaluate(() => {
+ const renderer = window.__scene?.renderer ?? window.__film?.renderer ?? window.__nature?.renderer ?? window.__studio?.renderer;
+ const context = renderer.context;
+ const extension = context.getExtension('WEBGL_debug_renderer_info');
+ return { gpu: extension ? context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unavailable', samples: renderer.samples, glError: context.getError() };
+ });
+ if (graphics.glError !== 0) throw new Error(`WebGL render error ${graphics.glError}.`);
+ if (backend === 'cpu' && !graphics.gpu.toLowerCase().includes('swiftshader')) throw new Error('CPU backend did not select SwiftShader.');
+ const report = { scene, kind, backend, preset: presetName, aspect, start, encoder: kind === 'video' ? encoderBackend : null, assembly: scene === 'object' ? assembly : null, width, height, actualRenderSize, fps, duration: kind === 'video' ? duration : null, memoryBudgetMiB: memory, peakEstimatedRenderBytes, peakNodeBytes, peakBrowserHeap, maximumPendingFrames, firstFrameBytes, elapsedSeconds: (performance.now() - started) / 1000, graphics, output: basename(output), errors };
+ await writeFile(`${output}.json`, JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report, null, 2));
+ } finally {
+ if (encoder && encoder.exitCode === null) encoder.kill();
+ await browser?.close();
+ server.kill();
}
- if (errors.length) throw new Error(`Browser render errors: ${errors.join('; ')}`);
- const graphics = await page.evaluate(() => {
- const renderer = window.__film?.renderer ?? window.__nature?.renderer ?? window.__studio?.renderer;
- const context = renderer.context;
- const extension = context.getExtension('WEBGL_debug_renderer_info');
- return { gpu: extension ? context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unavailable', samples: renderer.samples, glError: context.getError() };
- });
- if (graphics.glError !== 0) throw new Error(`WebGL render error ${graphics.glError}.`);
- if (backend === 'cpu' && !graphics.gpu.toLowerCase().includes('swiftshader')) throw new Error('CPU backend did not select SwiftShader.');
- const report = { scene, kind, backend, preset: presetName, assembly: scene === 'object' ? assembly : null, width, height, actualRenderSize, fps, duration: kind === 'video' ? duration : null, memoryBudgetMiB: memory, peakEstimatedRenderBytes, peakNodeBytes, peakBrowserHeap, maximumPendingFrames, firstFrameBytes, elapsedSeconds: (performance.now() - started) / 1000, graphics, output: basename(output), errors };
- await writeFile(`${output}.json`, JSON.stringify(report, null, 2));
- console.log(JSON.stringify(report, null, 2));
-} finally {
- if (encoder && encoder.exitCode === null) encoder.kill();
- await browser?.close();
- server.kill();
}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await renderMedia();
diff --git a/src/animation.js b/src/animation.js
new file mode 100644
index 00000000..5ada5cb4
--- /dev/null
+++ b/src/animation.js
@@ -0,0 +1,135 @@
+import { mat4, quat } from 'gl-matrix';
+
+const PROPERTY_SIZES = { translation: 3, rotation: 4, scale: 3, value: 1, emission: 1, metallic: 1, roughness: 1 };
+const INTERPOLATIONS = new Set(['LINEAR', 'STEP', 'SMOOTH']);
+
+function normalizedValue(property, value) {
+ const size = PROPERTY_SIZES[property];
+ if (size === 1) {
+ if (!Number.isFinite(value)) throw new TypeError('Numeric keyframes must be finite.');
+ if (property === 'emission' && value < 0) throw new RangeError('Emission keyframes cannot be negative.');
+ if (['metallic', 'roughness'].includes(property) && (value > 1 || value < 0 || property === 'roughness' && value === 0)) {
+ throw new RangeError(`${property} keyframes must stay within their material range.`);
+ }
+ return value;
+ }
+ if ((!Array.isArray(value) && !ArrayBuffer.isView(value)) || value.length !== size || !Array.from(value).every(Number.isFinite)) {
+ throw new TypeError(`${property} keyframes need ${size} finite values.`);
+ }
+ const result = Array.from(value);
+ if (property === 'rotation') {
+ const length = Math.hypot(...result);
+ if (length < 1e-8) throw new RangeError('Rotation keyframes cannot be zero quaternions.');
+ return Object.freeze(result.map(component => component / length));
+ }
+ if (property === 'scale' && result.some(component => component <= 0)) throw new RangeError('Scale keyframes must stay positive.');
+ return Object.freeze(result);
+}
+
+/** Keyframes are absolute local transforms. Input order does not affect sampling. */
+export function createAnimationClip({ duration, loop = false, tracks = [] } = {}) {
+ if (!Number.isFinite(duration) || duration <= 0) throw new RangeError('Clip duration must be positive and finite.');
+ if (typeof loop !== 'boolean' || !Array.isArray(tracks)) throw new TypeError('Clip loop must be boolean and tracks must be an array.');
+ const properties = new Set();
+ const compiled = tracks.map(track => {
+ if (!track || typeof track.target !== 'string' || !track.target.trim()) throw new TypeError('Every track needs a target name.');
+ if (!Object.hasOwn(PROPERTY_SIZES, track.property)) throw new RangeError(`Unknown animation property: ${track.property}`);
+ const identity = `${track.target}\u0000${track.property}`;
+ if (properties.has(identity)) throw new RangeError('Each target property can have only one track.');
+ properties.add(identity);
+ const interpolation = track.interpolation ?? 'LINEAR';
+ if (!INTERPOLATIONS.has(interpolation)) throw new RangeError(`Unknown interpolation: ${interpolation}`);
+ if (!Array.isArray(track.keyframes) || !track.keyframes.length) throw new RangeError('Tracks need at least one keyframe.');
+ const keyframes = track.keyframes.map(keyframe => {
+ if (!keyframe || !Number.isFinite(keyframe.time) || keyframe.time < 0 || keyframe.time > duration) {
+ throw new RangeError('Keyframe times must be within the clip duration.');
+ }
+ return Object.freeze({ time: keyframe.time, value: normalizedValue(track.property, keyframe.value) });
+ }).sort((first, second) => first.time - second.time);
+ for (let index = 1; index < keyframes.length; index++) {
+ if (keyframes[index].time === keyframes[index - 1].time) throw new RangeError('Keyframe times must be distinct.');
+ }
+ return Object.freeze({ target: track.target, property: track.property, interpolation, keyframes: Object.freeze(keyframes) });
+ });
+ return Object.freeze({ duration, loop, tracks: Object.freeze(compiled) });
+}
+
+function sampleTrack(track, time) {
+ const keyframes = track.keyframes;
+ const first = keyframes[0];
+ const last = keyframes[keyframes.length - 1];
+ const copy = value => typeof value === 'number' ? value : [...value];
+ if (time <= first.time) return copy(first.value);
+ if (time >= last.time) return copy(last.value);
+ let lower = 0;
+ let upper = keyframes.length - 1;
+ while (upper - lower > 1) {
+ const middle = Math.floor((lower + upper) / 2);
+ if (keyframes[middle].time <= time) lower = middle;
+ else upper = middle;
+ }
+ const start = keyframes[lower];
+ const end = keyframes[upper];
+ if (track.interpolation === 'STEP') return copy(start.value);
+ let progress = (time - start.time) / (end.time - start.time);
+ if (track.interpolation === 'SMOOTH') progress = progress * progress * (3 - 2 * progress);
+ if (track.property === 'rotation') return Array.from(quat.slerp(quat.create(), start.value, end.value, progress));
+ if (typeof start.value === 'number') return start.value + (end.value - start.value) * progress;
+ return start.value.map((value, axis) => value + (end.value[axis] - value) * progress);
+}
+
+export function sampleAnimationClip(clip, time) {
+ if (!Number.isFinite(time)) throw new TypeError('Animation time must be finite.');
+ const clipTime = clip.loop ? ((time % clip.duration) + clip.duration) % clip.duration : Math.max(0, Math.min(clip.duration, time));
+ return clip.tracks.map(track => ({ target: track.target, property: track.property, value: sampleTrack(track, clipTime) }));
+}
+
+/** Bind once before playback. Matrix identities and untracked initial components stay stable. */
+export function createAnimationPlayer(clip, parts) {
+ const namedParts = new Map();
+ for (const part of parts) {
+ if (namedParts.has(part.name)) throw new RangeError(`Duplicate animated part name: ${part.name}`);
+ namedParts.set(part.name, part);
+ }
+ const bindings = new Map();
+ for (const track of clip.tracks) {
+ const part = namedParts.get(track.target);
+ if (!part) throw new RangeError(`Animation target was not found: ${track.target}`);
+ if (track.property === 'value') throw new RangeError('Value tracks are sampled directly, rather than bound to parts.');
+ if (!bindings.has(track.target)) {
+ if (!(part.matrix instanceof Float32Array) || part.matrix.length !== 16 || !Array.from(part.matrix).every(Number.isFinite)) {
+ throw new TypeError('Animated parts need a finite Float32Array matrix.');
+ }
+ const translation = mat4.getTranslation(new Float32Array(3), part.matrix);
+ const scale = mat4.getScaling(new Float32Array(3), part.matrix);
+ if (Array.from(scale).some(value => value < 1e-8)) throw new RangeError('Animated matrices must have nonzero scale.');
+ const rotationMatrix = mat4.clone(part.matrix);
+ for (let column = 0; column < 3; column++) {
+ for (let row = 0; row < 3; row++) rotationMatrix[column * 4 + row] /= scale[column];
+ }
+ if (mat4.determinant(rotationMatrix) < 0.9999) throw new RangeError('Animated matrices must use rotation and positive scale without shear.');
+ const rotation = quat.normalize(quat.create(), mat4.getRotation(quat.create(), rotationMatrix));
+ bindings.set(track.target, { part, translation, scale, rotation });
+ }
+ }
+ return {
+ clip,
+ apply(time) {
+ const sampled = sampleAnimationClip(clip, time);
+ const transforms = new Map();
+ for (const value of sampled) {
+ const binding = bindings.get(value.target);
+ if (['emission', 'metallic', 'roughness'].includes(value.property)) {
+ binding.part.material = { ...binding.part.material, [value.property]: value.value };
+ } else {
+ if (!transforms.has(value.target)) transforms.set(value.target, { ...binding });
+ transforms.get(value.target)[value.property] = value.value;
+ }
+ }
+ for (const transform of transforms.values()) {
+ mat4.fromRotationTranslationScale(transform.part.matrix, transform.rotation, transform.translation, transform.scale);
+ }
+ return parts;
+ },
+ };
+}
diff --git a/src/motion-player.js b/src/motion-player.js
new file mode 100644
index 00000000..e477b95f
--- /dev/null
+++ b/src/motion-player.js
@@ -0,0 +1,155 @@
+import './motion-style.css';
+import { Renderer67 } from './renderer.js';
+import { createMotionScene, MOTION_DURATION } from './motion.js';
+
+const query = new URLSearchParams(location.search);
+const exporting = query.get('export') === '1';
+const canvas = document.querySelector('#motion-canvas');
+const stage = document.querySelector('.motion-stage');
+const slider = document.querySelector('#motion-time');
+const playButton = document.querySelector('#motion-play');
+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
+const scene = createMotionScene();
+const state = { time: 0, playing: false, aspect: ['landscape', 'portrait', 'square'].includes(query.get('aspect')) ? query.get('aspect') : 'landscape' };
+let renderer;
+let scheduledFrame = 0;
+let playbackOrigin = 0;
+
+function option(name, fallback, minimum, maximum) {
+ const raw = query.get(name);
+ const value = raw === null ? fallback : Number(raw);
+ return Number.isFinite(value) ? Math.max(minimum, Math.min(maximum, value)) : fallback;
+}
+
+if (exporting) {
+ document.body.classList.add('export-mode');
+ stage.style.width = `${option('width', 1280, 64, 4096)}px`;
+ stage.style.height = `${option('height', 720, 64, 4096)}px`;
+}
+stage.dataset.aspect = state.aspect;
+document.querySelector('#motion-aspect').value = state.aspect;
+
+function showError(error) {
+ setPlaying(false);
+ const notice = document.querySelector('#motion-error');
+ notice.textContent = `⚠ Animation could not render: ${error.message}. Reload the page to retry.`;
+ notice.hidden = false;
+ window.__motionError = error.message;
+}
+
+function renderAt(time) {
+ const frame = scene.sample(time, state.aspect);
+ renderer.updateParts(scene.parts, { shadows: true });
+ renderer.render({ ...frame.camera, time: frame.time, exposure: frame.exposure, effects: frame.effects });
+ state.time = frame.time;
+ slider.value = String(state.time);
+ slider.setAttribute('aria-valuetext', `${state.time.toFixed(1)} of ${MOTION_DURATION} seconds`);
+ document.querySelector('#motion-clock').value = `${state.time.toFixed(1)} / ${MOTION_DURATION.toFixed(1)} s`;
+ document.querySelector('#motion-shot').textContent = `Shot ${frame.shot + 1} of 3`;
+ document.querySelector('#motion-stat').textContent = `${Math.round(renderer.triangles / 1000)}k triangles · ${renderer.batches.length} draws · ${Math.round(renderer.memoryPlan.estimatedBytes / 1048576)} MB estimated`;
+ return frame;
+}
+
+function setPlaying(playing) {
+ state.playing = playing && !document.hidden;
+ cancelAnimationFrame(scheduledFrame);
+ scheduledFrame = 0;
+ playButton.textContent = state.playing ? 'Ⅱ Pause' : state.time >= MOTION_DURATION ? '▶ Play again' : '▶ Play';
+ playButton.setAttribute('aria-label', state.playing ? 'Pause animation' : 'Play animation');
+ if (state.playing) {
+ if (state.time >= MOTION_DURATION) renderAt(0);
+ playbackOrigin = performance.now() - state.time * 1000;
+ scheduledFrame = requestAnimationFrame(advance);
+ }
+}
+
+function advance(timestamp) {
+ scheduledFrame = 0;
+ if (!state.playing || document.hidden) return;
+ try {
+ renderAt((timestamp - playbackOrigin) / 1000);
+ if (state.time >= MOTION_DURATION) setPlaying(false);
+ else scheduledFrame = requestAnimationFrame(advance);
+ } catch (error) { showError(error); }
+}
+
+function initializeRenderer() {
+ renderer = new Renderer67(canvas, scene.parts, {
+ ground: false, hdr: true, pixelRatio: exporting ? 1 : 1.25,
+ samples: option('samples', 4, 1, 8), memoryBudgetMiB: option('memory', 256, 32, 1024),
+ });
+ renderAt(state.time);
+}
+
+playButton.addEventListener('click', () => { if (renderer) setPlaying(!state.playing); });
+document.querySelector('#motion-replay').addEventListener('click', () => {
+ if (!renderer) return;
+ setPlaying(false);
+ renderAt(0);
+ if (!reducedMotion.matches) setPlaying(true);
+});
+slider.addEventListener('input', () => {
+ if (!renderer) return;
+ setPlaying(false);
+ renderAt(Number(slider.value));
+});
+document.querySelector('#motion-aspect').addEventListener('change', event => {
+ state.aspect = event.target.value;
+ stage.dataset.aspect = state.aspect;
+ if (renderer) {
+ renderer.resize();
+ renderAt(state.time);
+ }
+});
+canvas.addEventListener('keydown', event => {
+ if (!renderer) return;
+ if (event.code === 'Space') {
+ event.preventDefault();
+ setPlaying(!state.playing);
+ } else if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
+ event.preventDefault();
+ setPlaying(false);
+ const time = event.key === 'Home' ? 0 : event.key === 'End' ? MOTION_DURATION : state.time + (event.key === 'ArrowRight' ? 0.25 : -0.25);
+ renderAt(time);
+ }
+});
+const resizeObserver = new ResizeObserver(() => {
+ if (!renderer) return;
+ renderer.resize();
+ renderAt(state.time);
+});
+resizeObserver.observe(canvas);
+document.addEventListener('visibilitychange', () => { if (document.hidden) setPlaying(false); });
+reducedMotion.addEventListener('change', event => { if (event.matches) setPlaying(false); });
+canvas.addEventListener('webglcontextlost', event => {
+ event.preventDefault();
+ setPlaying(false);
+ renderer?.dispose();
+ renderer = null;
+});
+canvas.addEventListener('webglcontextrestored', () => {
+ try { initializeRenderer(); } catch (error) { showError(error); }
+});
+window.addEventListener('pagehide', () => {
+ setPlaying(false);
+ resizeObserver.disconnect();
+ renderer?.dispose();
+ renderer = null;
+});
+window.addEventListener('pageshow', event => {
+ if (!event.persisted) return;
+ try { initializeRenderer(); resizeObserver.observe(canvas); } catch (error) { showError(error); }
+});
+window.__scene = {
+ get renderer() { return renderer; },
+ duration: MOTION_DURATION,
+ parts: scene.parts,
+ state,
+ renderAt: time => { setPlaying(false); return renderAt(time); },
+ pause: () => setPlaying(false),
+};
+window.__motion = { scene, state, get renderer() { return renderer; }, renderAt };
+try {
+ initializeRenderer();
+ if (!exporting && !reducedMotion.matches) setPlaying(true);
+} catch (error) { showError(error); }
diff --git a/src/motion-style.css b/src/motion-style.css
new file mode 100644
index 00000000..61f111e6
--- /dev/null
+++ b/src/motion-style.css
@@ -0,0 +1,46 @@
+:root { font-family: system-ui, sans-serif; color: #e9edeb; background: #171c20; color-scheme: dark; font-synthesis: none; }
+* { box-sizing: border-box; }
+body { margin: 0; }
+main { min-height: 100dvh; padding: 24px 30px; }
+a { color: inherit; text-decoration: none; }
+button, select, input { font: inherit; }
+button, select { background: #2e363d; border: 0; border-radius: 6px; color: inherit; padding: 10px 14px; cursor: pointer; }
+button:hover, select:hover { background: #39454b; }
+:focus-visible { outline: 2px solid #a9ddc7; outline-offset: 4px; }
+.motion-header { max-width: 1320px; margin: 0 auto 22px; display: flex; align-items: center; gap: 32px; }
+.brand { font-size: 27px; font-weight: 650; letter-spacing: -1.2px; }
+.brand span { color: #b6c2c5; font-weight: 400; }
+nav { display: flex; gap: 6px; }
+nav a { padding: 8px 12px; border-radius: 6px; font-size: 14px; }
+nav a[aria-current], nav a:hover { background: #ffffff0a; }
+.motion-stage { aspect-ratio: 16 / 9; width: min(100%, 1120px); max-height: calc(100dvh - 270px); margin: auto; overflow: hidden; background: #252b30; border-radius: 10px; }
+.motion-stage[data-aspect='portrait'] { aspect-ratio: 9 / 16; width: min(100%, calc((100dvh - 270px) * 9 / 16)); }
+.motion-stage[data-aspect='square'] { aspect-ratio: 1; width: min(100%, calc(100dvh - 270px)); }
+canvas { width: 100%; height: 100%; display: block; }
+canvas:focus-visible { outline-offset: -5px; }
+.motion-controls { max-width: 1120px; margin: 21px auto 0; display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 16px 20px; }
+h1 { margin: 0 0 5px; font-size: 23px; letter-spacing: -.6px; font-weight: 550; }
+.description p { margin: 0; color: #b4c1c6; font-size: 13px; }
+.playback-controls { display: flex; align-items: center; gap: 10px; font-size: 13px; }
+.playback-controls label { display: flex; align-items: center; gap: 8px; color: #b4c1c6; }
+.timeline-label { grid-column: 1 / -1; display: flex; justify-content: space-between; font-size: 13px; color: #b4c1c6; }
+output { font-variant-numeric: tabular-nums; }
+input[type='range'] { grid-column: 1 / -1; margin: -8px 0 0; width: 100%; accent-color: #a9ddc7; cursor: pointer; }
+.motion-details { grid-column: 1 / -1; display: flex; justify-content: space-between; color: #a3b3b9; font-size: 12px; gap: 15px; }
+.motion-error { background: #edf0ed; color: #914622; padding: 16px 20px; border-radius: 8px; max-width: 1120px; margin: 20px auto; font-size: 14px; }
+.export-mode main { padding: 0; min-height: 0; }
+.export-mode .interface { display: none !important; }
+.export-mode .motion-stage { position: fixed; inset: 0; max-height: none; margin: 0; border-radius: 0; }
+[hidden] { display: none !important; }
+@media (max-width: 700px) {
+ main { padding: 18px 18px 28px; }
+ .motion-header { gap: 16px; margin-bottom: 20px; }
+ nav { gap: 0; }
+ nav a { padding: 8px; font-size: 12px; }
+ .motion-controls { grid-template-columns: 1fr; gap: 17px; }
+ .playback-controls { justify-content: space-between; gap: 7px; }
+ .playback-controls button, .playback-controls select { padding: 10px; font-size: 12px; }
+ .motion-stage { max-height: calc(100dvh - 330px); }
+ .motion-stage[data-aspect='portrait'] { width: min(100%, calc((100dvh - 330px) * 9 / 16)); }
+ .motion-stage[data-aspect='square'] { width: min(100%, calc(100dvh - 330px)); }
+}
diff --git a/src/motion.js b/src/motion.js
new file mode 100644
index 00000000..b7954802
--- /dev/null
+++ b/src/motion.js
@@ -0,0 +1,111 @@
+import { mat4, quat } from 'gl-matrix';
+import { box, cylinder, sphere, torus } from './geometry.js';
+import { createAnimationClip, createAnimationPlayer, sampleAnimationClip } from './animation.js';
+
+export const MOTION_DURATION = 12;
+
+function rotation(axis, angle) {
+ return Array.from(quat.setAxisAngle(quat.create(), axis, angle));
+}
+
+function transform(position, scale, angles = [0, 0, 0]) {
+ return mat4.fromRotationTranslationScale(mat4.create(), quat.fromEuler(quat.create(), ...angles), position, scale);
+}
+
+function surface(color, metallic, roughness, emission = 0) {
+ return { tag: emission ? 'light' : 'mechanism', color, metallic, roughness, emission };
+}
+
+function cameraClip(start, end, fov) {
+ return createAnimationClip({ duration: 4, tracks: [
+ { target: 'eye', property: 'translation', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: start }, { time: 4, value: end }] },
+ { target: 'fov', property: 'value', keyframes: [{ time: 0, value: fov }] },
+ ] });
+}
+
+/** One geometry graph and one bound player serve every frame and aspect ratio. */
+export function createMotionScene() {
+ const parts = [];
+ const tracks = [];
+ const meshes = { ring: torus(0.045, 64, 10), collar: cylinder(32), plate: box(0.07, 4), bead: sphere(20, 12), bolt: cylinder(8) };
+ const gold = surface([0.52, 0.29, 0.075], 0.87, 0.28);
+ const dark = surface([0.018, 0.029, 0.033], 0.72, 0.36);
+ const steel = surface([0.32, 0.4, 0.43], 0.93, 0.23);
+ const glow = surface([0.035, 0.58, 0.37], 0.14, 0.26, 3.2);
+ const amber = surface([0.74, 0.16, 0.025], 0.1, 0.3, 1.7);
+
+ function add(name, mesh, position, scale, material, angles) {
+ parts.push({ name, geometry: meshes[mesh], matrix: transform(position, scale, angles), material });
+ return name;
+ }
+ function spin(name, axis, turns = 1, duration = MOTION_DURATION) {
+ tracks.push({ target: name, property: 'rotation', keyframes: Array.from({ length: 9 }, (_, index) => ({ time: duration * index / 8, value: rotation(axis, index / 8 * Math.PI * 2 * turns) })) });
+ }
+
+ add('Reactor housing', 'collar', [0, 0, 0], [0.64, 1.15, 0.64], dark);
+ for (let layer = 0; layer < 5; layer++) {
+ const height = -0.52 + layer * 0.26;
+ const name = add(`Rotor ${layer}`, 'collar', [0, height, 0], [0.75, 0.09, 0.75], layer % 2 ? steel : gold);
+ spin(name, [0, 1, 0], layer % 2 ? -1 : 1);
+ for (let tooth = 0; tooth < 20; tooth++) {
+ const angle = tooth / 20 * Math.PI * 2;
+ const name = add(`Rotor ${layer} tooth ${tooth}`, 'plate', [Math.cos(angle) * 0.73, height, Math.sin(angle) * 0.73], [0.16, 0.085, 0.13], layer % 2 ? steel : gold, [0, -angle * 180 / Math.PI, 0]);
+ tracks.push({ target: name, property: 'translation', keyframes: Array.from({ length: 17 }, (_, index) => {
+ const rotationAngle = angle + index / 16 * Math.PI * 2 * (layer % 2 ? -1 : 1);
+ return { time: index / 16 * MOTION_DURATION, value: [Math.cos(rotationAngle) * 0.73, height, Math.sin(rotationAngle) * 0.73] };
+ }) });
+ tracks.push({ target: name, property: 'rotation', keyframes: Array.from({ length: 17 }, (_, index) => ({ time: index / 16 * MOTION_DURATION, value: rotation([0, 1, 0], -angle - index / 16 * Math.PI * 2 * (layer % 2 ? -1 : 1)) })) });
+ }
+ }
+ add('Core lens', 'bead', [0, 0.74, 0], [0.38, 0.38, 0.38], glow);
+ tracks.push({ target: 'Core lens', property: 'emission', interpolation: 'SMOOTH', keyframes: [
+ { time: 0, value: 0.7 }, { time: 3, value: 3.2 }, { time: 6, value: 5 }, { time: 9, value: 2.5 }, { time: 12, value: 0.7 },
+ ] });
+ for (let ring = 0; ring < 3; ring++) {
+ const radius = 1.1 + ring * 0.27;
+ const name = add(`Gimbal ${ring}`, 'ring', [0, 0.12, 0], [radius, radius, radius], ring === 1 ? steel : gold);
+ const axis = ring === 0 ? [1, 0, 0] : ring === 1 ? [0, 1, 0] : [0, 0, 1];
+ spin(name, axis, ring === 1 ? -1 : 1);
+ }
+ for (let pod = 0; pod < 8; pod++) {
+ const angle = pod / 8 * Math.PI * 2;
+ const name = add(`Orbit pod ${pod}`, 'bead', [Math.cos(angle) * 1.8, 0.2, Math.sin(angle) * 1.8], [0.115, 0.115, 0.115], pod % 2 ? glow : amber);
+ tracks.push({ target: name, property: 'translation', interpolation: 'SMOOTH', keyframes: Array.from({ length: 25 }, (_, index) => {
+ const progress = index / 24;
+ const orbit = angle + progress * Math.PI * 2;
+ const radius = 1.8 + Math.sin(progress * Math.PI) * 0.2;
+ return { time: progress * MOTION_DURATION, value: [Math.cos(orbit) * radius, 0.25 + Math.sin(orbit * 2) * 0.65, Math.sin(orbit) * radius] };
+ }) });
+ }
+ for (let index = 0; index < 16; index++) {
+ const angle = index / 16 * Math.PI * 2;
+ add(`Housing fastener ${index}`, 'bolt', [Math.cos(angle) * 0.51, 0.61, Math.sin(angle) * 0.51], [0.033, 0.1, 0.033], steel);
+ }
+ add('Lower spindle', 'collar', [0, -0.9, 0], [0.13, 0.75, 0.13], steel);
+ add('Spindle tip', 'bead', [0, -1.31, 0], [0.18, 0.18, 0.18], gold);
+ const clip = createAnimationClip({ duration: MOTION_DURATION, tracks });
+ const player = createAnimationPlayer(clip, parts);
+ const cameras = [
+ cameraClip([4.8, 2.7, 7.4], [3.5, 1.8, 6.1], 40),
+ cameraClip([3.2, 0.85, 4.7], [1.1, 1.8, 4.3], 38),
+ cameraClip([-4.4, 2.6, 7], [-2.7, 1.5, 7.7], 42),
+ ];
+
+ function sample(time, aspect = 'landscape') {
+ if (!Number.isFinite(time)) throw new TypeError('Motion time must be finite.');
+ if (!['landscape', 'portrait', 'square'].includes(aspect)) throw new RangeError('Unknown motion aspect.');
+ const current = Math.max(0, Math.min(MOTION_DURATION, time));
+ player.apply(current);
+ const shot = Math.min(2, Math.floor(current / 4));
+ const cameraValues = Object.fromEntries(sampleAnimationClip(cameras[shot], current - shot * 4).map(value => [value.target, value.value]));
+ const framing = aspect === 'portrait' ? 2.35 : aspect === 'square' ? 1.18 : 1;
+ return {
+ time: current,
+ shot,
+ camera: { eye: cameraValues.eye.map(value => value * framing), target: [0, 0.1, 0], fov: cameraValues.fov },
+ effects: { bloom: { strength: 0.32, threshold: 0.82, radius: 1.4 }, saturation: 0.95, contrast: 1.07, temperature: 0.06, vignette: 0.17, grain: 0.012 },
+ exposure: 1,
+ };
+ }
+ return { name: 'Clockwork orbit', duration: MOTION_DURATION, parts, clip, player, sample };
+}
diff --git a/tests/animation.test.js b/tests/animation.test.js
new file mode 100644
index 00000000..ce2514b5
--- /dev/null
+++ b/tests/animation.test.js
@@ -0,0 +1,114 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat4, quat } from 'gl-matrix';
+import { createAnimationClip, createAnimationPlayer, sampleAnimationClip } from '../src/animation.js';
+import { createMotionScene } from '../src/motion.js';
+
+function valueClip(interpolation = 'LINEAR', loop = false) {
+ return createAnimationClip({ duration: 4, loop, tracks: [{ target: 'value', property: 'value', interpolation, keyframes: [{ time: 4, value: 8 }, { time: 0, value: 0 }, { time: 2, value: 4 }] }] });
+}
+
+test('keyframes normalize input order, clamp endpoints and sample independently of call order', () => {
+ const clip = valueClip();
+ const value = time => sampleAnimationClip(clip, time)[0].value;
+ assert.equal(value(-10), 0);
+ assert.equal(value(100), 8);
+ assert.equal(value(1.5), 3);
+ value(3);
+ assert.equal(value(1.5), 3);
+ assert.equal(value(2), 4);
+ assert.deepEqual(clip.tracks[0].keyframes.map(key => key.time), [0, 2, 4]);
+ assert.ok(Object.isFrozen(clip.tracks[0].keyframes));
+});
+
+test('STEP and SMOOTH interpolation retain their endpoint behavior', () => {
+ const step = valueClip('STEP');
+ assert.equal(sampleAnimationClip(step, 1.99)[0].value, 0);
+ assert.equal(sampleAnimationClip(step, 2)[0].value, 4);
+ assert.equal(sampleAnimationClip(step, 4)[0].value, 8);
+ const smooth = valueClip('SMOOTH');
+ assert.equal(sampleAnimationClip(smooth, 0.5)[0].value, 0.625);
+ assert.equal(sampleAnimationClip(smooth, 1)[0].value, 2);
+});
+
+test('looping wraps exact endpoints and negative times', () => {
+ const clip = valueClip('LINEAR', true);
+ assert.equal(sampleAnimationClip(clip, 4)[0].value, 0);
+ assert.equal(sampleAnimationClip(clip, 5)[0].value, 2);
+ assert.equal(sampleAnimationClip(clip, -1)[0].value, 6);
+});
+
+test('quaternion keyframes normalize and interpolate the shortest arc', () => {
+ const clip = createAnimationClip({ duration: 2, tracks: [{ target: 'part', property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 2] }, { time: 2, value: [0, 0, 0, -3] }] }] });
+ const rotation = sampleAnimationClip(clip, 1)[0].value;
+ assert.ok(Math.abs(Math.hypot(...rotation) - 1) < 1e-6);
+ assert.ok(Math.abs(rotation[3]) > 0.999);
+ const halfTurn = createAnimationClip({ duration: 2, tracks: [{ target: 'part', property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: 2, value: [0, 1, 0, 0] }] }] });
+ const midpoint = sampleAnimationClip(halfTurn, 1)[0].value;
+ assert.ok(Math.abs(midpoint[1] - Math.SQRT1_2) < 1e-6);
+});
+
+test('bound animation preserves matrix identities and initial untracked transform components', () => {
+ const matrix = mat4.fromRotationTranslationScale(mat4.create(), quat.fromEuler(quat.create(), 0, 35, 0), [1, 2, 3], [2, 3, 4]);
+ const mesh = {};
+ const part = { name: 'part', matrix, geometry: mesh, material: { emission: 0, roughness: 0.5 } };
+ const initialBasis = Array.from(matrix.slice(0, 12));
+ const clip = createAnimationClip({ duration: 2, tracks: [
+ { target: 'part', property: 'translation', keyframes: [{ time: 0, value: [1, 2, 3] }, { time: 2, value: [5, 6, 7] }] },
+ { target: 'part', property: 'emission', keyframes: [{ time: 0, value: 0 }, { time: 2, value: 2 }] },
+ ] });
+ const player = createAnimationPlayer(clip, [part]);
+ player.apply(1);
+ const midpoint = Array.from(matrix);
+ player.apply(2);
+ player.apply(1);
+ assert.deepEqual(Array.from(matrix), midpoint);
+ assert.equal(part.matrix, matrix);
+ assert.equal(part.geometry, mesh);
+ assert.equal(part.material.emission, 1);
+ assert.deepEqual(Array.from(matrix.slice(12, 15)), [3, 4, 5]);
+ const scale = mat4.getScaling(new Float32Array(3), matrix);
+ assert.ok(scale.every((value, axis) => Math.abs(value - [2, 3, 4][axis]) < 1e-5));
+ assert.ok(Array.from(matrix.slice(0, 12)).every((value, axis) => Math.abs(value - initialBasis[axis]) < 1e-5));
+});
+
+test('motion sampling keeps geometry and matrix identities and frames portrait around the same focal point', () => {
+ const scene = createMotionScene();
+ const matrices = scene.parts.map(part => part.matrix);
+ const meshes = scene.parts.map(part => part.geometry);
+ const portrait = scene.sample(6, 'portrait');
+ const expected = scene.parts.map(part => Array.from(part.matrix));
+ scene.sample(2);
+ scene.sample(11);
+ scene.sample(6);
+ for (let index = 0; index < scene.parts.length; index++) {
+ assert.equal(scene.parts[index].matrix, matrices[index]);
+ assert.equal(scene.parts[index].geometry, meshes[index]);
+ assert.deepEqual(Array.from(scene.parts[index].matrix), expected[index]);
+ assert.ok(Array.from(scene.parts[index].matrix).every(Number.isFinite));
+ }
+ assert.equal(scene.sample(3.99).shot, 0);
+ assert.equal(scene.sample(4).shot, 1);
+ assert.equal(scene.sample(8).shot, 2);
+ assert.deepEqual(portrait.camera.target, scene.sample(6).camera.target);
+ assert.ok(Math.hypot(...portrait.camera.eye) > Math.hypot(...scene.sample(6).camera.eye));
+ assert.equal(scene.duration, 12);
+ assert.equal(new Set(meshes).size, 5);
+});
+
+test('invalid tracks, values and bindings fail explicitly', () => {
+ const track = { target: 'part', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] };
+ assert.throws(() => createAnimationClip({ duration: 0 }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, loop: 'yes' }), TypeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, interpolation: 'CUBIC' }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, property: 'unknown' }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, keyframes: [] }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, keyframes: [{ time: 0, value: [NaN, 0, 0] }] }] }), TypeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [track, track] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, keyframes: [track.keyframes[0], track.keyframes[0]] }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, keyframes: [{ time: 2, value: [0, 0, 0] }] }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 0] }] }] }), RangeError);
+ assert.throws(() => createAnimationClip({ duration: 1, tracks: [{ ...track, property: 'scale', keyframes: [{ time: 0, value: [0, 1, 1] }] }] }), RangeError);
+ assert.throws(() => sampleAnimationClip(valueClip(), Infinity), TypeError);
+ assert.throws(() => createAnimationPlayer(createAnimationClip({ duration: 1, tracks: [track] }), []), RangeError);
+});
diff --git a/tests/export-options.test.js b/tests/export-options.test.js
new file mode 100644
index 00000000..945ad560
--- /dev/null
+++ b/tests/export-options.test.js
@@ -0,0 +1,53 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { parseRenderOptions } from '../scripts/render-media.mjs';
+
+test('motion portrait exports derive dimensions and duration without launching a browser', () => {
+ const options = parseRenderOptions(['--scene', 'motion', '--kind', 'video', '--aspect', 'portrait', '--backend', 'cpu']);
+ assert.equal(options.width, 360);
+ assert.equal(options.height, 640);
+ assert.equal(options.duration, 12);
+ assert.equal(options.start, 0);
+ assert.equal(options.audio, null);
+});
+
+test('square and explicit dimensions preserve their selected compositions', () => {
+ const square = parseRenderOptions(['--aspect', 'square']);
+ assert.equal(square.width, 720);
+ assert.equal(square.height, 720);
+ const explicit = parseRenderOptions(['--aspect', 'portrait', '--width', '800', '--height', '1200']);
+ assert.equal(explicit.width, 800);
+ assert.equal(explicit.height, 1200);
+ const width = parseRenderOptions(['--aspect', 'portrait', '--width', '360']);
+ assert.equal(width.height, 640);
+ const height = parseRenderOptions(['--aspect', 'landscape', '--height', '540']);
+ assert.equal(height.width, 960);
+});
+
+test('only film selects the original soundtrack automatically', () => {
+ assert.equal(parseRenderOptions(['--scene', 'film']).audio, 'artifacts/critical-score.wav');
+ for (const scene of ['object', 'nature', 'motion', 'view2d']) assert.equal(parseRenderOptions(['--scene', scene]).audio, null);
+ assert.equal(parseRenderOptions(['--scene', 'motion', '--audio', 'my-score.wav']).audio, 'my-score.wav');
+});
+
+test('new options retain start offsets and legacy renderer presets', () => {
+ const options = parseRenderOptions(['--scene', 'view2d', '--backend', 'cpu', '--start', '2.5', '--duration', '4']);
+ assert.equal(options.scene, 'view2d');
+ assert.equal(options.width, 640);
+ assert.equal(options.height, 360);
+ assert.equal(options.duration, 4);
+ assert.equal(options.start, 2.5);
+ const film = parseRenderOptions([]);
+ assert.equal(film.scene, 'film');
+ assert.equal(film.duration, 32);
+ assert.equal(film.width, 1280);
+ assert.equal(film.height, 720);
+});
+
+test('invalid export options fail before starting resources', () => {
+ for (const args of [
+ ['--aspect', 'diagonal'], ['--start', '-1'], ['--start', 'NaN'], ['--duration', '0'],
+ ['--width', '0'], ['--backend', 'unknown'], ['--scene', 'unknown'], ['--encoder', 'unknown'],
+ ['--unknown', 'value'], ['--aspect'], ['--kind', 'video', '--width', '101', '--height', '100'],
+ ]) assert.throws(() => parseRenderOptions(args));
+});