3D engine that AI agents drive
Home hero: start the first world with the page and add a light path
Nguyen Xuan Anc323b51ce90b
diff --git a/changes/884.md b/changes/884.mdnew file mode 100644index 00000000..ea2229e1--- /dev/null+++ b/changes/884.md@@ -0,0 +1 @@+- The home hero starts its first world's download with the page, ships a lighter Port, and shows the poster with a "Play live 3D" button instead of fetching 3D on save-data, 2g/3g or 4 GB devices (#884)diff --git a/index.html b/index.htmlindex 01a6ac17..1ad627dc 100644--- a/index.html+++ b/index.html@@ -16,6 +16,33 @@<meta property="og:image:alt" content="A container port rendered live by 67js" /><meta name="twitter:card" content="summary_large_image" /><link rel="canonical" href="https://67js.codepawl.com/" />+ <script id="hero-mode">+ // Decides how the home hero loads before the page body parses, so a fast visitor's first world starts downloading with the poster+ // and a visitor on a light connection downloads no 3D at all. hero-loop.js reads window.__heroMode: 'live', 'deferred' (a phone,+ // starts after the poster and an idle moment) or 'poster' (no 3D until the visitor presses Play live 3D).+ (function () {+ var connection = navigator.connection || {};+ var slowTypes = ['slow-2g', '2g', '3g'];+ var lightPath = connection.saveData === true || slowTypes.indexOf(connection.effectiveType) !== -1 || (navigator.deviceMemory !== undefined && navigator.deviceMemory <= 4);+ var phone = matchMedia('(max-width: 700px)').matches;+ var query = new URLSearchParams(location.search);+ var forcedLive = query.has('capture') || query.has('measure') || query.has('scout');+ var mode = forcedLive ? 'live' : lightPath ? 'poster' : phone ? 'deferred' : 'live';+ window.__heroMode = mode;+ document.documentElement.dataset.heroMode = mode;+ if (mode !== 'live') return;+ // Plain fetches, not <link rel=preload>: a preload that fetch() should have reused failed now and then, with no error to read.+ // hero-lab/loop/world.js takes these promises by URL and falls back to its own request when one is missing or failed.+ var prefetched = window.__heroPrefetch = {};+ ['/showcase/port/scene.json', '/showcase/port/scene.glb', '/showcase/port/scene.rest.glb', '/showcase/port/sky.hdr'].forEach(function (href) {+ prefetched[href] = fetch(href).then(function (response) {+ if (!response.ok) throw new Error(href + ' is not available (' + response.status + ')');+ return response.blob();+ });+ prefetched[href].catch(function () {});+ });+ })();+ </script><title>67js · 3D engine that AI agents drive</title><link rel="icon" href="/favicon.svg" /></head>@@ -44,6 +71,7 @@<div class="scene-bar"><div class="attribution" id="attribution" hidden></div><div class="credits-panel" id="credits-panel" hidden></div>+ <button class="play-live" id="play-live" type="button" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path class="play-icon" d="M8 5.5v13l10-6.5-10-6.5Z"/><circle class="play-wait" cx="12" cy="12" r="8"/></svg><span class="play-label">Play live 3D</span></button><nav class="scene-tabs" id="scene-tabs" aria-label="Scenes"></nav><button class="credits-toggle" id="credits-toggle" type="button" aria-expanded="false" aria-controls="credits-panel"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8v.1"/></svg><span class="credits-label">Credits</span></button></div>diff --git a/public/showcase/port/scene.glb b/public/showcase/port/scene.glbindex 51a7c34b..0fe78c40 100644Binary files a/public/showcase/port/scene.glb and b/public/showcase/port/scene.glb differdiff --git a/public/showcase/port/scene.rest.glb b/public/showcase/port/scene.rest.glbindex 050e4e6d..5b9ac5d8 100644Binary files a/public/showcase/port/scene.rest.glb and b/public/showcase/port/scene.rest.glb differdiff --git a/scripts/recode-glb-textures.mjs b/scripts/recode-glb-textures.mjsnew file mode 100644index 00000000..011d77f8--- /dev/null+++ b/scripts/recode-glb-textures.mjs@@ -0,0 +1,136 @@+// Re-encodes the PNG and JPEG textures of an already prepared GLB (meshopt geometry stays byte for byte) as WebP,+// and shrinks the ones larger than a cap. Used to lighten a showcase world without touching its meshes.+//+// node scripts/recode-glb-textures.mjs <input.glb> <output.glb> [--webp-quality 80] [--max-texture 4096]+//+// An image is kept as it is when the WebP is not smaller. Nothing is read from the network.+import { readFileSync, writeFileSync } from 'node:fs';+import sharp from 'sharp';++const GLB_MAGIC = 0x46546c67;+const JSON_CHUNK = 0x4e4f534a;+const BINARY_CHUNK = 0x004e4942;++export function parseArguments(argv) {+ const options = { webpQuality: 80, maxTexture: 4096 };+ const positional = [];+ for (let index = 0; index < argv.length; index++) {+ const name = argv[index];+ if (!name.startsWith('--')) {+ positional.push(name);+ continue;+ }+ const value = Number(argv[++index]);+ const key = name.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());+ if (!(key in options) || !Number.isFinite(value) || value <= 0) throw new Error(`Unknown or invalid option ${name}.`);+ options[key] = value;+ }+ if (positional.length !== 2) throw new Error('Pass <input.glb> and <output.glb>.');+ return { input: positional[0], output: positional[1], options };+}++export function readGlb(buffer) {+ if (buffer.readUInt32LE(0) !== GLB_MAGIC) throw new Error('Not a GLB file.');+ const jsonLength = buffer.readUInt32LE(12);+ if (buffer.readUInt32LE(16) !== JSON_CHUNK) throw new Error('The GLB has no JSON chunk.');+ const json = JSON.parse(buffer.subarray(20, 20 + jsonLength).toString('utf8'));+ const binaryStart = 20 + jsonLength;+ if (buffer.readUInt32LE(binaryStart + 4) !== BINARY_CHUNK) throw new Error('The GLB has no binary chunk.');+ const binaryLength = buffer.readUInt32LE(binaryStart);+ return { json, binary: buffer.subarray(binaryStart + 8, binaryStart + 8 + binaryLength) };+}++export function writeGlb(json, binary) {+ const jsonBytes = Buffer.from(JSON.stringify(json), 'utf8');+ const jsonPadded = Buffer.concat([jsonBytes, Buffer.alloc((4 - (jsonBytes.length % 4)) % 4, 0x20)]);+ const binaryPadded = Buffer.concat([binary, Buffer.alloc((4 - (binary.length % 4)) % 4)]);+ const header = Buffer.alloc(12);+ header.writeUInt32LE(GLB_MAGIC, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(12 + 8 + jsonPadded.length + 8 + binaryPadded.length, 8);+ const jsonHeader = Buffer.alloc(8);+ jsonHeader.writeUInt32LE(jsonPadded.length, 0);+ jsonHeader.writeUInt32LE(JSON_CHUNK, 4);+ const binaryHeader = Buffer.alloc(8);+ binaryHeader.writeUInt32LE(binaryPadded.length, 0);+ binaryHeader.writeUInt32LE(BINARY_CHUNK, 4);+ return Buffer.concat([header, jsonHeader, jsonPadded, binaryHeader, binaryPadded]);+}++async function recodeImage(original, options) {+ const metadata = await sharp(original).metadata();+ const longest = Math.max(metadata.width, metadata.height);+ let pipeline = sharp(original);+ if (longest > options.maxTexture) {+ const scale = options.maxTexture / longest;+ pipeline = pipeline.resize({ width: Math.round(metadata.width * scale), height: Math.round(metadata.height * scale) });+ }+ const converted = await pipeline.webp({ quality: options.webpQuality, effort: 6, alphaQuality: 90 }).toBuffer();+ return converted.length < original.length ? converted : null;+}++// The bytes a buffer view really owns in the first buffer: a meshopt view keeps its data in the extension, not in the view.+function dataRangeOf(view) {+ const meshopt = view.extensions?.EXT_meshopt_compression;+ if (meshopt) return { owner: meshopt, buffer: meshopt.buffer ?? 0 };+ return { owner: view, buffer: view.buffer ?? 0 };+}++export async function recodeGlbTextures(buffer, options) {+ const { json, binary } = readGlb(buffer);+ const recodedByView = new Map();+ let imageBytesBefore = 0;+ for (const image of json.images ?? []) {+ const view = json.bufferViews[image.bufferView];+ const original = binary.subarray(view.byteOffset ?? 0, (view.byteOffset ?? 0) + view.byteLength);+ imageBytesBefore += original.length;+ if (image.mimeType !== 'image/png' && image.mimeType !== 'image/jpeg') continue;+ const converted = await recodeImage(original, options);+ if (!converted) continue;+ recodedByView.set(image.bufferView, converted);+ image.mimeType = 'image/webp';+ }++ const chunks = [];+ let offset = 0;+ const append = bytes => {+ const start = offset;+ chunks.push(bytes);+ offset += bytes.length;+ const padding = (4 - (offset % 4)) % 4;+ if (padding) {+ chunks.push(Buffer.alloc(padding));+ offset += padding;+ }+ return start;+ };+ let imageBytesAfter = 0;+ json.bufferViews.forEach((view, index) => {+ const { owner, buffer: bufferIndex } = dataRangeOf(view);+ if (bufferIndex !== 0) return;+ const replacement = recodedByView.get(index);+ const bytes = replacement ?? binary.subarray(owner.byteOffset ?? 0, (owner.byteOffset ?? 0) + owner.byteLength);+ if (json.images?.some(image => image.bufferView === index)) imageBytesAfter += bytes.length;+ owner.byteOffset = append(bytes);+ owner.byteLength = bytes.length;+ });++ if (json.images?.some(image => image.mimeType === 'image/webp')) {+ const used = new Set([...(json.extensionsUsed ?? []), 'EXT_texture_webp']);+ const required = new Set([...(json.extensionsRequired ?? []), 'EXT_texture_webp']);+ json.extensionsUsed = [...used];+ json.extensionsRequired = [...required];+ }+ const packed = Buffer.concat(chunks);+ json.buffers[0].byteLength = packed.length;+ return { glb: writeGlb(json, packed), imageBytesBefore, imageBytesAfter, inputBytes: buffer.length };+}++async function main() {+ const { input, output, options } = parseArguments(process.argv.slice(2));+ const result = await recodeGlbTextures(readFileSync(input), options);+ writeFileSync(output, result.glb);+ console.log(JSON.stringify({ inputBytes: result.inputBytes, outputBytes: result.glb.length, imageBytesBefore: result.imageBytesBefore, imageBytesAfter: result.imageBytesAfter }));+}++if (import.meta.url === `file:///${process.argv[1].replace(/\\/g, '/')}`) await main();diff --git a/src/hero-lab/hero-loop.js b/src/hero-lab/hero-loop.jsindex 6359b163..2a1218cb 100644--- a/src/hero-lab/hero-loop.js+++ b/src/hero-lab/hero-loop.js@@ -261,18 +261,72 @@ function tick(seconds) {paintIndicator(incoming ? 1 : prefersReducedMotion ? 0 : activeSeconds / scene.seconds);}-// The poster is the largest paint, so the first world's download (about 12 MB) starts only after the poster has arrived.-function posterLoaded() {+// How the page loads the hero, decided by the inline script in index.html: 'live', 'deferred' (a phone) or 'poster' (light path).+const POSTER_IDLE_TIMEOUT_MS = 3000;+const PLAY_HANDOFF_MS = 800;+const playButton = document.querySelector('#play-live');+let heroMode = window.__heroMode ?? 'live';+let liveStarted = false;++// The phone path waits until the poster has painted and the page has nothing else to do, so the download and the build never compete with it.+async function posterVisibleAndPageIdle() {const poster = document.querySelector('#poster');- if (!poster || poster.complete) return Promise.resolve();- return new Promise(resolve => {- poster.addEventListener('load', resolve, { once: true });- poster.addEventListener('error', resolve, { once: true });- });+ if (poster && !poster.complete) {+ await new Promise(resolve => {+ poster.addEventListener('load', resolve, { once: true });+ poster.addEventListener('error', resolve, { once: true });+ });+ }+ await poster?.decode?.().catch(() => {});+ await new Promise(resolve => (window.requestIdleCallback ? window.requestIdleCallback(resolve, { timeout: POSTER_IDLE_TIMEOUT_MS }) : setTimeout(resolve, 1200)));+}++function showPosterOnly() {+ paintScene(0);+ stage.setAttribute('aria-label', `A still of the live 3D scene: ${SCENES[0].name}`);+ playButton.hidden = false;+ playButton.addEventListener('click', playOnDemand);+}++async function playOnDemand() {+ playButton.disabled = true;+ playButton.dataset.state = 'loading';+ playButton.querySelector('.play-label').textContent = 'Loading 3D';+ try {+ await beginLive();+ } catch (error) {+ showStageError(stage, `Live view unavailable: ${error.message}`);+ playButton.disabled = false;+ delete playButton.dataset.state;+ playButton.querySelector('.play-label').textContent = 'Play live 3D';+ return;+ }+ playButton.hidden = true;+ // The poster keeps its slow pan while it fades out, then the page switches to the live layout.+ setTimeout(() => { heroMode = 'live'; document.documentElement.dataset.heroMode = 'live'; }, PLAY_HANDOFF_MS);}async function start() {- await posterLoaded();+ if (heroMode === 'poster' && playButton) {+ showPosterOnly();+ return;+ }+ if (heroMode === 'deferred') await posterVisibleAndPageIdle();+ await beginLive();+}++async function beginLive() {+ if (liveStarted) return;+ liveStarted = true;+ try {+ await startLive();+ } catch (error) {+ liveStarted = false;+ throw error;+ }+}++async function startLive() {const first = prepare(0, { immediately: true });await first.ready;if (first.error) throw first.error;diff --git a/src/hero-lab/loop/loop.css b/src/hero-lab/loop/loop.cssindex 305bb019..6a3b959f 100644--- a/src/hero-lab/loop/loop.css+++ b/src/hero-lab/loop/loop.css@@ -48,9 +48,9 @@.scene-bar { position: absolute; z-index: 4; right: clamp(16px, 4vw, 48px); bottom: clamp(24px, 5svh, 48px); display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 4px; max-width: min(720px, 60vw); }.scene-tabs { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 2px; }-.hero-loop .scene-tab, .hero-loop .credits-toggle { display: inline-flex; text-shadow: 0 1px 12px rgb(9 7 15 / 0.9); align-items: center; gap: 8px; min-height: 36px; padding: 0 12px; border: 0; border-radius: 12px; background: transparent; color: var(--muted); font: inherit; font-size: 13px; font-weight: 500; cursor: pointer; transition: background-color var(--hover) ease, color var(--hover) ease, transform var(--press) var(--ease-out); }-.hero-loop .scene-tab svg, .hero-loop .credits-toggle svg { flex: none; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }-.hero-loop .scene-tab:active, .hero-loop .credits-toggle:active { transform: scale(0.97); }+.hero-loop .scene-tab, .hero-loop .credits-toggle, .hero-loop .play-live { display: inline-flex; text-shadow: 0 1px 12px rgb(9 7 15 / 0.9); align-items: center; gap: 8px; min-height: 36px; padding: 0 12px; border: 0; border-radius: 12px; background: transparent; color: var(--muted); font: inherit; font-size: 13px; font-weight: 500; cursor: pointer; transition: background-color var(--hover) ease, color var(--hover) ease, transform var(--press) var(--ease-out); }+.hero-loop .scene-tab svg, .hero-loop .credits-toggle svg, .hero-loop .play-live svg { flex: none; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }+.hero-loop .scene-tab:active, .hero-loop .credits-toggle:active, .hero-loop .play-live:active { transform: scale(0.97); }.hero-loop .scene-tab[aria-current='true'] { background: rgb(255 255 255 / 0.1); color: var(--text); }.ring-track { stroke: rgb(255 255 255 / 0.22); }.ring-fill { stroke: currentColor; transform: rotate(-90deg); transform-origin: 50% 50%; opacity: 0; }@@ -61,9 +61,9 @@@keyframes ring-turn { to { transform: rotate(360deg); } }@media (hover: hover) and (pointer: fine) {.attribution a:hover { color: var(--text); }- .hero-loop .scene-tab:hover, .hero-loop .credits-toggle:hover { background: rgb(255 255 255 / 0.08); color: var(--text); }+ .hero-loop .scene-tab:hover, .hero-loop .credits-toggle:hover, .hero-loop .play-live:hover:not(:disabled) { background: rgb(255 255 255 / 0.08); color: var(--text); }}-.attribution[hidden], .credits-panel[hidden] { display: none; }+.attribution[hidden], .credits-panel[hidden], .hero-loop .play-live[hidden] { display: none; }.attribution { flex-basis: 100%; display: flex; flex-direction: column; align-items: flex-end; padding: 0 12px 4px; }.attribution a { display: inline-flex; align-items: center; min-height: 28px; color: var(--muted); font-size: 12px; text-shadow: 0 1px 12px rgb(9 7 15 / 0.9); transition: color var(--hover) ease; }.credits-panel { flex-basis: 100%; display: flex; flex-direction: column; gap: 2px; padding: 8px; border-radius: 16px; background: var(--surface); }@@ -72,6 +72,19 @@.credits-panel p { margin: 0; padding: 8px 10px; color: var(--muted); font-size: 12px; }@media (hover: hover) and (pointer: fine) { .credits-panel a:hover { background: var(--surface-hover); } }+/* Light path: no 3D is fetched until Play live 3D is pressed, so the poster drifts slowly and the scene tabs wait. */+.hero-loop .play-live { grid-area: tabs; justify-self: start; }+.hero-loop .play-live .play-icon { fill: currentColor; stroke: none; }+.hero-loop .play-live .play-wait { display: none; stroke-dasharray: 3 4; transform-origin: 50% 50%; animation: ring-turn 1.4s linear infinite; }+.hero-loop .play-live[data-state='loading'] .play-icon { display: none; }+.hero-loop .play-live[data-state='loading'] .play-wait { display: block; }+html[data-hero-mode='poster'] .hero-loop .scene-tabs { display: none; }+html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: poster-pan 40s ease-in-out infinite alternate; will-change: transform; }+@keyframes poster-pan {+ from { transform: scale(1.04) translate3d(-1.5%, 0.6%, 0); }+ to { transform: scale(1.12) translate3d(1.5%, -1.2%, 0); }+}+@media (max-width: 1180px) {.hero-loop .scene-tab span { display: none; }.hero-loop .scene-tab[aria-current='true'] span { display: inline; }@@ -86,6 +99,7 @@.hero-loop .credits-toggle { grid-area: credits; }.attribution { align-items: flex-start; padding: 0 8px 8px; }.hero-loop .scene-tab, .hero-loop .credits-toggle { padding: 0 9px; }+ .hero-loop .play-live { padding: 0 12px 0 9px; }.hero-loop .scene-tab[aria-current='true'] { padding: 0 12px 0 9px; }.credits-label { display: none; }.scene-tabs { justify-content: flex-start; }@@ -93,7 +107,8 @@.hero-loop .scene-tab[aria-current='true'] span { display: inline; }}@media (prefers-reduced-motion: reduce) {- .hero-loop .scene-tab[data-state='loading'] .ring-track { animation: none; }+ .hero-loop .scene-tab[data-state='loading'] .ring-track, .hero-loop .play-live .play-wait { animation: none; }+ html[data-hero-mode='poster'] .hero-loop .stage .poster { animation: none; will-change: auto; }.hero-loop { transition: none; }.hero-loop .copy > * { animation: none; }}diff --git a/src/hero-lab/loop/world.js b/src/hero-lab/loop/world.jsindex 8fc7ae6a..158cf9eb 100644--- a/src/hero-lab/loop/world.js+++ b/src/hero-lab/loop/world.js@@ -18,7 +18,17 @@ const WATER_MIRROR_ENABLED = false;// Lets the page draw and handle input between the phases of a build, so one phase never queues behind another.const yieldToMain = yieldToPage;+// index.html starts the first world's files with the page and leaves their promises in window.__heroPrefetch; each is taken once.+async function takePrefetched(url) {+ const promise = window.__heroPrefetch?.[url];+ if (!promise) return null;+ delete window.__heroPrefetch[url];+ return promise.catch(() => null);+}+async function fetchBlob(url) {+ const prefetched = await takePrefetched(url);+ if (prefetched) return prefetched;const response = await fetch(url);if (!response.ok) throw new Error(`${url} is not available (${response.status})`);return response.blob();@@ -86,7 +96,7 @@ async function replacePartsInSlices(renderer, parts) {}export async function fetchWorld(descriptionUrl) {- const description = await (await fetch(descriptionUrl)).json();+ const description = JSON.parse(await (await fetchBlob(descriptionUrl)).text());const paths = [description.glb, ...(description.glbRest ?? [])];const [models, sky] = await Promise.all([Promise.all(paths.map(fetchBlob)), fetchBlob(description.hdri)]);const bytes = models.reduce((total, model) => total + model.size, sky.size);diff --git a/tests/hero-mode.test.js b/tests/hero-mode.test.jsnew file mode 100644index 00000000..88025c33--- /dev/null+++ b/tests/hero-mode.test.js@@ -0,0 +1,93 @@+import assert from 'node:assert/strict';+import { existsSync, readFileSync } from 'node:fs';+import { test } from 'node:test';+import vm from 'node:vm';++const indexHtml = readFileSync(new URL('../index.html', import.meta.url), 'utf8');+const heroModeScript = indexHtml.match(/<script id="hero-mode">([\s\S]*?)<\/script>/)?.[1];++// Runs the inline script of index.html against a fake browser and returns what it decided and which files it started to fetch.+function runHeroMode({ connection, deviceMemory, phone = false, search = '' } = {}) {+ const fetched = [];+ const documentElement = { dataset: {} };+ const sandbox = {+ navigator: { connection, deviceMemory },+ matchMedia: () => ({ matches: phone }),+ location: { search },+ URLSearchParams,+ fetch: href => {+ fetched.push(href);+ return Promise.resolve({ ok: true, blob: () => Promise.resolve({ href }) });+ },+ document: { documentElement },+ };+ sandbox.window = sandbox;+ vm.runInNewContext(heroModeScript, sandbox);+ return { mode: sandbox.window.__heroMode, attribute: documentElement.dataset.heroMode, fetched, prefetch: sandbox.window.__heroPrefetch };+}++test('index.html carries the hero mode script', () => {+ assert.ok(heroModeScript, 'index.html needs <script id="hero-mode">');+});++test('a desktop on a good connection goes live and starts the first world with the page', async () => {+ const { mode, attribute, fetched, prefetch } = runHeroMode({ connection: { effectiveType: '4g', saveData: false }, deviceMemory: 8 });+ assert.equal(mode, 'live');+ assert.equal(attribute, 'live');+ assert.ok(fetched.length > 0);+ assert.deepEqual(Object.keys(prefetch), fetched);+ for (const href of fetched) assert.deepEqual(await prefetch[href], { href });+});++test('a browser that reports nothing about the connection goes live', () => {+ assert.equal(runHeroMode().mode, 'live');+});++test('the prefetched files are the ones the port description names', () => {+ const description = JSON.parse(readFileSync(new URL('../public/showcase/port/scene.json', import.meta.url), 'utf8'));+ const { fetched } = runHeroMode();+ const expected = ['/showcase/port/scene.json', description.glb, ...description.glbRest, description.hdri];+ assert.deepEqual(fetched, expected);+ for (const href of expected) assert.ok(existsSync(new URL(`../public${href}`, import.meta.url)), `${href} exists`);+});++test('a failed prefetch is a rejected promise that never goes unhandled', async () => {+ const sandbox = { navigator: {}, matchMedia: () => ({ matches: false }), location: { search: '' }, URLSearchParams, document: { documentElement: { dataset: {} } }, fetch: () => Promise.resolve({ ok: false, status: 404 }) };+ sandbox.window = sandbox;+ vm.runInNewContext(heroModeScript, sandbox);+ await assert.rejects(sandbox.window.__heroPrefetch['/showcase/port/scene.glb'], /is not available \(404\)/);+});++test('the light path shows the poster and fetches nothing', () => {+ const cases = {+ 'save data': { connection: { saveData: true, effectiveType: '4g' } },+ '2g': { connection: { effectiveType: '2g' } },+ 'slow 2g': { connection: { effectiveType: 'slow-2g' } },+ '3g': { connection: { effectiveType: '3g' } },+ '4 GB of memory': { connection: { effectiveType: '4g' }, deviceMemory: 4 },+ '2 GB of memory': { deviceMemory: 2 },+ 'a phone on 3g': { connection: { effectiveType: '3g' }, phone: true },+ };+ for (const [name, options] of Object.entries(cases)) {+ const { mode, fetched } = runHeroMode(options);+ assert.equal(mode, 'poster', name);+ assert.equal(fetched.length, 0, name);+ }+});++test('a phone on a good connection waits for the poster and fetches nothing yet', () => {+ const { mode, fetched } = runHeroMode({ connection: { effectiveType: '4g' }, deviceMemory: 8, phone: true });+ assert.equal(mode, 'deferred');+ assert.equal(fetched.length, 0);+});++test('capture, measure and scout pages always go live', () => {+ for (const search of ['?capture=1', '?measure=1&samples=2', '?scout=1']) {+ assert.equal(runHeroMode({ connection: { saveData: true }, phone: true, search }).mode, 'live', search);+ }+ assert.equal(runHeroMode({ connection: { saveData: true }, search: '?captured=1' }).mode, 'poster');+});++test('index.html has the Play live 3D button, hidden until the light path shows it', () => {+ assert.match(indexHtml, /<button class="play-live" id="play-live" type="button" hidden>[\s\S]*?Play live 3D<\/span><\/button>/);+});diff --git a/tests/recode-glb-textures.test.js b/tests/recode-glb-textures.test.jsnew file mode 100644index 00000000..231117a1--- /dev/null+++ b/tests/recode-glb-textures.test.js@@ -0,0 +1,68 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import sharp from 'sharp';+import { parseArguments, readGlb, recodeGlbTextures, writeGlb } from '../scripts/recode-glb-textures.mjs';++async function noisyJpeg(size) {+ const raw = Buffer.alloc(size * size * 3);+ for (let index = 0; index < raw.length; index++) raw[index] = (index * 31 + (index >> 7) * 17) & 255;+ return sharp(raw, { raw: { width: size, height: size, channels: 3 } }).jpeg({ quality: 95 }).toBuffer();+}++// One JPEG image and one stand-in for a meshopt buffer view, whose data lives in the extension and not in the view.+async function buildGlb(size) {+ const jpeg = await noisyJpeg(size);+ const geometry = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);+ const padded = bytes => Buffer.concat([bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]);+ const binary = Buffer.concat([padded(geometry), padded(jpeg)]);+ const json = {+ asset: { version: '2.0' },+ buffers: [{ byteLength: binary.length }, { byteLength: 8, extensions: { EXT_meshopt_compression: { fallback: true } } }],+ bufferViews: [+ { buffer: 1, byteOffset: 0, byteLength: 8, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: 0, byteLength: 8, byteStride: 4, count: 2, mode: 'ATTRIBUTES' } } },+ { buffer: 0, byteOffset: padded(geometry).length, byteLength: jpeg.length },+ ],+ images: [{ bufferView: 1, mimeType: 'image/jpeg' }],+ extensionsUsed: ['EXT_meshopt_compression'],+ extensionsRequired: ['EXT_meshopt_compression'],+ };+ return { glb: writeGlb(json, binary), geometry, jpegBytes: jpeg.length };+}++test('parseArguments reads both options and rejects unknown ones', () => {+ const parsed = parseArguments(['in.glb', 'out.glb', '--webp-quality', '70', '--max-texture', '2048']);+ assert.deepEqual(parsed.options, { webpQuality: 70, maxTexture: 2048 });+ assert.throws(() => parseArguments(['in.glb', 'out.glb', '--bogus', '1']), /Unknown or invalid option/);+ assert.throws(() => parseArguments(['only-one.glb']), /Pass <input.glb> and <output.glb>/);+});++test('textures become WebP and the meshopt data stays byte for byte', async () => {+ const { glb, geometry } = await buildGlb(256);+ const result = await recodeGlbTextures(glb, { webpQuality: 60, maxTexture: 4096 });+ const { json, binary } = readGlb(result.glb);+ assert.equal(json.images[0].mimeType, 'image/webp');+ assert.ok(json.extensionsRequired.includes('EXT_texture_webp'));+ const meshopt = json.bufferViews[0].extensions.EXT_meshopt_compression;+ assert.deepEqual([...binary.subarray(meshopt.byteOffset, meshopt.byteOffset + meshopt.byteLength)], [...geometry]);+ const view = json.bufferViews[1];+ const metadata = await sharp(binary.subarray(view.byteOffset, view.byteOffset + view.byteLength)).metadata();+ assert.equal(metadata.format, 'webp');+ assert.ok(json.buffers[0].byteLength <= binary.length);+ assert.equal(json.buffers[0].byteLength % 4, 0);+});++test('a texture above the cap is scaled down, keeping its aspect ratio', async () => {+ const { glb } = await buildGlb(512);+ const { json, binary } = readGlb((await recodeGlbTextures(glb, { webpQuality: 60, maxTexture: 128 })).glb);+ const view = json.bufferViews[1];+ const metadata = await sharp(binary.subarray(view.byteOffset, view.byteOffset + view.byteLength)).metadata();+ assert.deepEqual([metadata.width, metadata.height], [128, 128]);+});++test('an image whose WebP would be larger is left as it was', async () => {+ const { glb } = await buildGlb(64);+ const unchanged = await recodeGlbTextures(glb, { webpQuality: 100, maxTexture: 4096 });+ const { json } = readGlb(unchanged.glb);+ if (json.images[0].mimeType === 'image/jpeg') assert.equal(unchanged.imageBytesAfter, unchanged.imageBytesBefore);+ else assert.ok(unchanged.imageBytesAfter < unchanged.imageBytesBefore);+});