3D engine that AI agents drive
Test the split worlds, add the load measurement and the change note (closes #445)
Nguyen Xuan An1270e5999a4c
diff --git a/changes/445.md b/changes/445.mdnew file mode 100644index 00000000..e20ace74--- /dev/null+++ b/changes/445.md@@ -0,0 +1,5 @@+- Draw the showcase worlds from a small first part and stream the rest in (closes #445). Each of `public/showcase/port`, `airport` and `datacenter` is now `scene.glb` (the ground and the hero the opening camera frames) plus `scene.rest.glb`, with a 128x64 `sky.preview.hdr` for the first frame. `scripts/split-showcase-glb.mjs` regenerates the split from the one-piece GLB: every compressed vertex stream, texture and material is copied byte for byte, node transforms are kept, and only the shared meshopt index stream is decoded and encoded again (lossless). The page draws the first part, starts the rest the moment it is in, adds it with `replaceParts`, swaps in the full sky and puts the parts back in the one-piece order. The loading chip shows real megabytes from the first request to the last (for example `3.2 of 13.4 MB`, sizes from `Content-Length`). Core size is unchanged (entry:core +0 B); the logic is in `src/showcase.js` and `src/showcase-download.js`.+- Measured in headless Chrome on a local `vite preview` build, cache off, link throttled to 5 Mbps with no added latency, two runs each (`scripts/measure-showcase-load.mjs`). First frame, before to after: port 22.0-22.1 s to 3.9-4.4 s, airport 27.3-27.5 s to 4.2-4.7 s, datacenter 22.8-23.0 s to 4.0-4.1 s. The first frame needs 2.5-2.7 MB: about 0.4 MB of page code and 1.8-2.2 MB of first part. Final frame: port 22.0-22.1 s to 22.1-22.6 s, airport 27.3-27.5 s to 28.7-29.4 s, datacenter 22.8-23.0 s to 22.9-23.1 s. Bytes for the whole world: port 13.39 to 13.43 MB, airport 18.10 to 18.87 MB (its first part shares textures with the ramp equipment, so they travel twice), datacenter 14.04 to 14.09 MB.+- On an unthrottled link the first frame comes at 0.4-0.9 s instead of 1.3-1.9 s, and the final frame at 1.3-3.6 s instead of 1.3-2.0 s (one airport run took 5.0 s on a busy machine), because the rest decodes and joins after the first frame.+- The final frame matches the one-piece render pixel for pixel in all three worlds at the same camera: mean difference 0 and maximum difference 0 (1280x720 for airport and datacenter; the port draws 632x355 there, which its 512 MiB memory budget allows, before and after).+- Texture memory once loaded: airport 161 to 196 MiB, because a texture that both parts use is decoded once per file; the port (447 MiB) and the datacenter (196 MiB) hold the same as before.diff --git a/scripts/measure-showcase-load.mjs b/scripts/measure-showcase-load.mjsnew file mode 100644index 00000000..4c61340b--- /dev/null+++ b/scripts/measure-showcase-load.mjs@@ -0,0 +1,170 @@+// Measures how long each showcase world takes to show its first frame and its final frame, and the bytes fetched by then,+// in headless Chrome on a throttled or unthrottled link. It also saves the final 1280x720 frame as raw RGBA so two builds can+// be compared pixel for pixel with `--compare <a.rgba> <b.rgba>`.+//+// node scripts/measure-showcase-load.mjs --origin http://127.0.0.1:4173 [--mbps 5] [--scenes port,airport,datacenter] [--runs 1] [--out directory --label name]+// node scripts/measure-showcase-load.mjs --compare before.rgba after.rgba+//+// The first frame is the first instanced draw on the showcase canvas. The final frame is the first draw after the page reports+// every part of the world is in (builds without staged loading report it as soon as the world is on screen).+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { chromium } from 'playwright';++const CHROME_PATH = 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const VIEWPORT = { width: 1280, height: 720 };+const FIRST_FRAME_MARKER = 'first-frame-drawn';++function parseArguments(argv) {+ const options = { origin: 'http://127.0.0.1:4173', mbps: 0, scenes: ['port', 'airport', 'datacenter'], runs: 1, out: null, label: 'build', compare: null, resources: false, timeoutSeconds: 180 };+ for (let index = 0; index < argv.length; index++) {+ const flag = argv[index];+ if (flag === '--origin') options.origin = argv[++index];+ else if (flag === '--mbps') options.mbps = Number(argv[++index]);+ else if (flag === '--scenes') options.scenes = argv[++index].split(',');+ else if (flag === '--runs') options.runs = Number(argv[++index]);+ else if (flag === '--out') options.out = argv[++index];+ else if (flag === '--label') options.label = argv[++index];+ else if (flag === '--resources') options.resources = true;+ else if (flag === '--timeout') options.timeoutSeconds = Number(argv[++index]);+ else if (flag === '--compare') options.compare = [argv[++index], argv[++index]];+ else throw new Error(`Unknown argument ${flag}.`);+ }+ return options;+}++function compareFrames([firstPath, secondPath]) {+ const first = readFileSync(firstPath);+ const second = readFileSync(secondPath);+ if (first.length !== second.length) throw new Error(`Frames differ in size: ${first.length} and ${second.length} bytes.`);+ let sum = 0;+ let maximum = 0;+ for (let index = 0; index < first.length; index++) {+ const difference = Math.abs(first[index] - second[index]);+ sum += difference;+ if (difference > maximum) maximum = difference;+ }+ console.log(JSON.stringify({ bytes: first.length, meanDifference: sum / first.length, maximumDifference: maximum }));+}++// Runs in the page before any script: stamps the first draw and the first draw after the world is complete.+function installFrameTimers(marker) {+ window.__loadTimes = { firstFrame: null, finalFrame: null };+ const drawInstanced = WebGL2RenderingContext.prototype.drawElementsInstanced;+ let completeSeen = false;+ WebGL2RenderingContext.prototype.drawElementsInstanced = function (...drawArguments) {+ const now = performance.now();+ if (window.__loadTimes.firstFrame === null && this.canvas.id === 'showcase-viewport') {+ window.__loadTimes.firstFrame = now;+ console.debug(marker);+ }+ if (completeSeen && window.__loadTimes.finalFrame === null) window.__loadTimes.finalFrame = now;+ return drawInstanced.apply(this, drawArguments);+ };+ const watch = () => {+ const showcase = window.__showcase;+ if (showcase && (showcase.complete === undefined || showcase.complete === true)) completeSeen = true;+ requestAnimationFrame(watch);+ };+ requestAnimationFrame(watch);+}++async function measureOnce(browser, options, sceneId) {+ const context = await browser.newContext({ viewport: VIEWPORT, deviceScaleFactor: 1 });+ const page = await context.newPage();+ const session = await context.newCDPSession(page);+ await session.send('Network.enable');+ await session.send('Network.setCacheDisabled', { cacheDisabled: true });+ if (options.mbps > 0) {+ await session.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: options.mbps * 1e6 / 8, uploadThroughput: options.mbps * 1e6 / 8 });+ }+ let totalBytes = 0;+ const urlOfRequest = new Map();+ const bytesOfUrl = new Map();+ session.on('Network.requestWillBeSent', event => urlOfRequest.set(event.requestId, event.request.url));+ session.on('Network.dataReceived', event => {+ totalBytes += event.dataLength;+ const url = urlOfRequest.get(event.requestId) ?? event.requestId;+ bytesOfUrl.set(url, (bytesOfUrl.get(url) ?? 0) + event.dataLength);+ });+ await page.addInitScript(installFrameTimers, FIRST_FRAME_MARKER);+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ let bytesAtFirstFrame = 0;+ let resourcesAtFirstFrame = [];+ page.on('console', message => {+ if (message.type() === 'error') errors.push(message.text());+ if (message.text() === FIRST_FRAME_MARKER) {+ bytesAtFirstFrame = totalBytes;+ resourcesAtFirstFrame = [...bytesOfUrl].map(([url, bytes]) => ({ url: url.replace(options.origin, ''), bytes }));+ }+ });+ await page.goto(`${options.origin}/showcase.html?scene=${sceneId}`, { waitUntil: 'commit' });+ let timedOut = false;+ try {+ await page.waitForFunction(() => window.__loadTimes?.finalFrame !== null && window.__loadTimes?.finalFrame !== undefined, null, { timeout: options.timeoutSeconds * 1000, polling: 50 });+ } catch {+ timedOut = true;+ errors.push(`no final frame; status: ${await page.evaluate(() => document.querySelector('#showcase-status')?.textContent)}`);+ }+ const times = await page.evaluate(() => ({ ...window.__loadTimes }));+ const memory = await page.evaluate(() => {+ const renderer = window.__showcase?.renderer;+ return renderer ? { textureMiB: Math.round(renderer.textureBytes / 1048576), geometryMiB: Math.round(renderer.geometryBytes / 1048576) } : null;+ });+ const result = {+ scene: sceneId,+ mbps: options.mbps,+ timedOut,+ memory,+ firstFrameSeconds: Number((times.firstFrame / 1000).toFixed(2)),+ finalFrameSeconds: times.finalFrame === null ? null : Number((times.finalFrame / 1000).toFixed(2)),+ megabytesAtFirstFrame: Number((bytesAtFirstFrame / 1e6).toFixed(2)),+ totalMegabytes: Number((totalBytes / 1e6).toFixed(2)),+ errors,+ };+ if (options.resources) result.resourcesAtFirstFrame = resourcesAtFirstFrame.sort((a, b) => b.bytes - a.bytes).slice(0, 12);+ if (options.out && !timedOut) {+ const pixels = await page.evaluate(async () => {+ const showcase = window.__showcase;+ const canvasElement = document.querySelector('#showcase-viewport');+ canvasElement.style.cssText = 'width:1280px;height:720px;max-width:none;max-height:none;position:fixed;left:0;top:0;aspect-ratio:auto';+ window.dispatchEvent(new Event('resize'));+ showcase.draw();+ const canvas = document.querySelector('#showcase-viewport');+ const copy = document.createElement('canvas');+ copy.width = canvas.width;+ copy.height = canvas.height;+ const copyContext = copy.getContext('2d');+ copyContext.drawImage(canvas, 0, 0);+ const data = copyContext.getImageData(0, 0, copy.width, copy.height).data;+ let binary = '';+ const chunk = 0x8000;+ for (let offset = 0; offset < data.length; offset += chunk) binary += String.fromCharCode(...data.subarray(offset, offset + chunk));+ return { width: copy.width, height: copy.height, base64: btoa(binary) };+ });+ mkdirSync(options.out, { recursive: true });+ writeFileSync(join(options.out, `${sceneId}-${options.label}.rgba`), Buffer.from(pixels.base64, 'base64'));+ result.frame = `${pixels.width}x${pixels.height}`;+ }+ await context.close();+ return result;+}++const options = parseArguments(process.argv.slice(2));+if (options.compare) {+ compareFrames(options.compare);+} else {+ const browser = await chromium.launch({+ executablePath: CHROME_PATH,+ headless: true,+ args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-webgl'],+ });+ try {+ for (const sceneId of options.scenes) {+ for (let run = 0; run < options.runs; run++) console.log(JSON.stringify(await measureOnce(browser, options, sceneId)));+ }+ } finally {+ await browser.close();+ }+}diff --git a/tests/showcase-port-weight.test.js b/tests/showcase-port-weight.test.jsindex 768eb372..6748f405 100644--- a/tests/showcase-port-weight.test.js+++ b/tests/showcase-port-weight.test.js@@ -1,22 +1,57 @@import assert from 'node:assert/strict';import { readFile } from 'node:fs/promises';import test from 'node:test';+import { parseRadianceHdr } from '../src/hdri.js';const SHOWCASE_SOURCE = new URL('../src/showcase.js', import.meta.url);const MEGABYTE = 1024 * 1024;-const BYTE_BUDGET_BY_WORLD = { port: 16 * MEGABYTE, airport: 16 * MEGABYTE, datacenter: 16 * MEGABYTE };+const WORLDS = ['port', 'airport', 'datacenter'];+// The first part is what a visitor waits for: at 5 Mbps every megabyte is about 1.7 s, and the first frame is due within 5 s.+const FIRST_PART_BYTE_BUDGET = 3.1 * MEGABYTE;+const REST_PART_BYTE_BUDGET = 16 * MEGABYTE;function readGltfJson(buffer) {const jsonLength = buffer.readUInt32LE(12);return JSON.parse(buffer.subarray(20, 20 + jsonLength).toString('utf8'));}-for (const [world, budget] of Object.entries(BYTE_BUDGET_BY_WORLD)) {- test(`the ${world} showcase GLB keeps its vertex data meshopt-compressed`, async () => {- const buffer = await readFile(new URL(`../public/showcase/${world}/scene.glb`, import.meta.url));- const document = readGltfJson(buffer);- assert.ok(document.extensionsRequired.includes('EXT_meshopt_compression'));- assert.ok(buffer.length < budget, `${world} scene.glb is ${buffer.length} bytes, budget ${budget}`);+async function readWorld(world) {+ const directory = new URL(`../public/showcase/${world}/`, import.meta.url);+ const description = JSON.parse(await readFile(new URL('scene.json', directory), 'utf8'));+ const first = await readFile(new URL('scene.glb', directory));+ const rest = await readFile(new URL('scene.rest.glb', directory));+ return { directory, description, first, rest };+}++for (const world of WORLDS) {+ test(`the ${world} showcase loads in two meshopt-compressed parts, the first small enough to draw quickly`, async () => {+ const { description, first, rest } = await readWorld(world);+ for (const buffer of [first, rest]) {+ assert.ok(readGltfJson(buffer).extensionsRequired.includes('EXT_meshopt_compression'));+ }+ assert.ok(first.length < FIRST_PART_BYTE_BUDGET, `${world} scene.glb is ${first.length} bytes, budget ${FIRST_PART_BYTE_BUDGET}`);+ assert.ok(rest.length < REST_PART_BYTE_BUDGET, `${world} scene.rest.glb is ${rest.length} bytes, budget ${REST_PART_BYTE_BUDGET}`);+ assert.equal(description.glb, `/showcase/${world}/scene.glb`);+ assert.deepEqual(description.glbRest, [`/showcase/${world}/scene.rest.glb`]);+ });++ test(`the ${world} showcase parts hold meshes and keep every skinned part in the first`, async () => {+ const { first, rest } = await readWorld(world);+ const firstDocument = readGltfJson(first);+ const restDocument = readGltfJson(rest);+ assert.ok(firstDocument.nodes.some(node => node.mesh !== undefined));+ assert.ok(restDocument.nodes.some(node => node.mesh !== undefined));+ assert.equal(restDocument.skins, undefined, 'the renderer cannot add a skinned part to a scene that is already drawing');+ });++ test(`the ${world} showcase has a small preview sky that parses`, async () => {+ const { directory, description } = await readWorld(world);+ assert.equal(description.hdriPreview, `/showcase/${world}/sky.preview.hdr`);+ const preview = await readFile(new URL('sky.preview.hdr', directory));+ assert.ok(preview.length < 256 * 1024);+ const { width, height, data } = parseRadianceHdr(preview);+ assert.ok(width > 0 && height > 0);+ assert.ok(data.some(value => value > 0));});}@@ -25,3 +60,10 @@ test('the showcase page supplies the meshopt decoder to the glTF loader', asyncassert.match(source, /meshopt_decoder\.module\.js/);assert.match(source, /decoders/);});++test('the showcase page draws the first part before it streams the rest', async () => {+ const source = await readFile(SHOWCASE_SOURCE, 'utf8');+ assert.match(source, /glbRest/);+ assert.match(source, /replaceParts/);+ assert.match(source, /replace-textured-parts/);+});