← Commit history
package-lock.json+2−2
@@ -1,12 +1,12 @@ {   "name": "adom-3d-viewer-babylon9",-  "version": "0.12.10",+  "version": "0.13.0",   "lockfileVersion": 3,   "requires": true,   "packages": {     "": {       "name": "adom-3d-viewer-babylon9",-      "version": "0.12.10",+      "version": "0.13.0",       "license": "MIT",       "devDependencies": {         "@babylonjs/addons": "9.5.0",
package.json+55−5
@@ -3,7 +3,61 @@   "version": "0.13.0",   "description": "The Babylon 9.5 engine behind every component page's 3D tab on wiki.adom.inc. Versioned ESM bundle with GLB loading, view cube, layers toolbar, ground shadows, and Z-up CAD framing.",   "type": "app",+  "main": "./dist/index.js",+  "module": "./dist/index.js",+  "types": "./dist/index.d.ts",+  "exports": {+    ".": {+      "import": "./dist/index.js",+      "types": "./dist/index.d.ts"+    }+  },+  "files": [+    "dist",+    "dist-standalone",+    "src",+    "standalone.ts"+  ],+  "scripts": {+    "build": "vite build",+    "build:standalone": "vite build --config vite.standalone.config.mts",+    "dev": "vite build --watch",+    "prepare": "npm run build",+    "test:sandbox": "node test/wiki-sandbox.test.mjs",+    "test:orbit": "node test/orbit.test.mjs",+    "test": "node test/run-all.mjs",+    "test:viewcube": "node test/viewcube.test.mjs",+    "test:help": "node test/help.test.mjs",+    "test:lights": "node test/lights.test.mjs",+    "test:replace": "node test/replace.test.mjs",+    "test:layers": "node test/layers.test.mjs",+    "test:bundle": "node test/bundle.test.mjs",+    "test:home": "node test/home-target.test.mjs",+    "test:intro": "node test/intro.test.mjs",+    "test:visibility": "node test/visibility.test.mjs"+  },   "dependencies": {},+  "devDependencies": {+    "@babylonjs/addons": "9.5.0",+    "@babylonjs/core": "9.5.0",+    "@babylonjs/gui": "9.5.0",+    "@babylonjs/gui-editor": "9.5.0",+    "@babylonjs/inspector": "9.5.0",+    "@babylonjs/loaders": "9.5.0",+    "@babylonjs/materials": "9.5.0",+    "@babylonjs/serializers": "9.5.0",+    "@sveltejs/vite-plugin-svelte": "^3.1.2",+    "babylonjs-gltf2interface": "9.5.0",+    "puppeteer-core": "25.15.0",+    "svelte": "4.2.20",+    "svelte-check": "^3.8.6",+    "terser": "^5.46.2",+    "typescript": "^5.5.4",+    "vite": "^5.4.1"+  },+  "peerDependencies": {+    "svelte": "^4.0.0 || ^5.0.0"+  },   "slug": "adom-3d-viewer",   "license": "MIT",   "tags": [@@ -37,9 +91,5 @@       "prompt": "Download the 0.4.3 viewer bundle so my tool vendors a fixed build"     }   ],-  "title": "Adom 3D Viewer",-  "scripts": {-    "install": "./install.sh",-    "uninstall": "./uninstall.sh"-  }+  "title": "Adom 3D Viewer" }
src/ThreeDViewer.svelte+913−120
@@ -1,30 +1,33 @@ <script lang="ts">-    import { installBoardLayers } from "./lib/board-layers";-    import { installPinFinish } from "./lib/pin-finish";     import { onMount, onDestroy } from 'svelte';     import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';     import '@babylonjs/loaders/glTF';     import { Vector3 } from '@babylonjs/core/Maths/math.vector';     import { Color3 } from '@babylonjs/core/Maths/math.color';+    import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer';     import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';     import { RawTexture } from '@babylonjs/core/Materials/Textures/rawTexture';     import { Texture } from '@babylonjs/core/Materials/Textures/texture';     import type { Mesh } from '@babylonjs/core/Meshes/mesh';-    import { AdomStatics } from './lib/adom-babylon/AdomStatics';+    import { ViewerContext } from './lib/adom-babylon/ViewerContext';+    import type { AdomCamera } from './lib/adom-babylon/Camera/AdomCamera';     import { SceneBuilder } from './lib/adom-babylon/3DViewer/SceneBuilder';     import { ContentLights } from './lib/adom-babylon/3DViewer/ContentLights';     import type { ContentLightRow } from './lib/adom-babylon/3DViewer/ContentLights';     import * as AxisHelpers from './lib/adom-babylon/3DViewer/AxisHelpers';     import { ResizableLoadingScreen } from './lib/adom-babylon/ui/ResizableLoadingScreen';     import { getPref, setPref, prefsBackend, removePrefsWithPrefix } from './lib/adom-babylon/util/prefs';+    import { trackViewerRoot, ownsPageEvent } from './lib/adom-babylon/util/pageOwner';     import type { EnvironmentStatus } from './lib/adom-babylon/3DViewer/SceneBuilder';     import type { ViewerHint, ViewerReadyReport } from './lib/adom-babylon/util/readiness';-    import type { ViewCubeUICallbacks } from './lib/adom-babylon/3DViewer/ViewCubeBuilder';+    import { ViewCubeBuilder, type ViewCubeUICallbacks } from './lib/adom-babylon/3DViewer/ViewCubeBuilder';     import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';     import type { TransformNode } from '@babylonjs/core/Meshes/transformNode';-    import type { Scene, Engine, Camera, ShadowGenerator } from '@babylonjs/core';+    import type { Scene, Engine, Camera, ShadowGenerator, AnimationGroup } from '@babylonjs/core';     import { PBRMetallicRoughnessMaterial } from '@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial';     import { loadBabylon } from './lib/babylon-namespace';+    import { installBoardLayers } from './lib/board-layers';+    import { installPinFinish } from './lib/pin-finish';      export let zUp: boolean = true;     export let modelUrl: string | undefined = undefined;@@ -33,6 +36,46 @@     /** How many content lights (LEDs inside the GLB) may light surfaces at      *  once. 0 leaves every one of them off; their emissive skins still glow. */     export let lightBudget: number = 4;+    /** false holds every animation group at its first frame after each load. */+    export let animate: boolean = true;+    /** How many times an animation the model starts with plays before it+     *  rests on its last frame; 0 loops forever. */+    export let repeat: number = 0;+    /** Hover labels: 'all' (the authored extras.tooltip, else a readable+     *  mesh name), 'authored' (extras.tooltip only) or 'off'. onMeshHover+     *  still runs on every hover and can override the label. */+    export let tooltips: 'all' | 'authored' | 'off' = 'all';+    /** World axes at startup. */+    export let axes: boolean = true;+    /** Bottom fill light at startup. */+    export let bottomLight: boolean = false;+    /** false: no shadows and no shadow map; getShadowGenerator() returns null. */+    export let shadows: boolean = true;+    /** The view Home goes to, set at startup: { alpha, beta, radiusScale? }+     *  in radians, as setHomeView(). */+    export let homeView: { alpha: number; beta: number; radiusScale?: number; target?: [number, number, number] | null } | null = null;+    /** true: the first model load opens at Home (homeView, else the view+     *  cube's top-front-right corner) instead of framing from the camera's+     *  starting top-down view. */+    export let homeOnLoad: boolean = false;+    /** A model load from a URL that has not finished after this many+     *  milliseconds fails with a MODEL_LOAD_TIMEOUT hint; 0 waits forever. */+    export let loadTimeoutMs: number = 0;+    /** Click to load: the viewer shows a card instead of starting, and+     *  creates its engine, scene and WebGL context only when the reader+     *  presses Load or the host calls openGate(). Model loads asked for in+     *  the meantime wait. bytes and vertices describe the model on the card;+     *  downloadUrl adds a download link. It must be an http(s) or relative+     *  URL; any other (javascript:, data:) gets no link and a console+     *  warning. */+    export let gate: { bytes?: number; vertices?: number; downloadUrl?: string } | null = null;+    /** Called when the browser takes this viewer's WebGL context away (too+     *  many live contexts, a GPU reset); nothing paints until it is back. */+    export let onContextLost: (() => void) | undefined = undefined;+    /** Called when the context is back and the viewer has rebuilt its GPU state. */+    export let onContextRestored: (() => void) | undefined = undefined;+    /** 'studio' (the gradient), 'transparent' (the page shows through) or '#rrggbb'. */+    export let background: string = 'studio';     export let environmentUrl: string | undefined = undefined;     /** Bytes of a Babylon .env file to use as the environment map, loaded      *  from memory (no blob URL, no fetch). For frames whose CSP forbids@@ -42,7 +85,8 @@     export let environment: 'studio' | 'none' = 'studio';     /** Called once with the ready report: environment, camera, storage,      *  loading overlay, model, CSP violations, and actionable hints. Also-     *  reachable as whenReady(). */+     *  reachable as whenReady(). Not called for a viewer destroyed before+     *  its scene was ready. */     export let onReady: ((report: ViewerReadyReport) => void) | undefined = undefined;     /** Initial camera projection. Applied once when the viewer is ready. Use setProjectionMode() to change at runtime. */     export let initialViewMode: 'perspective' | 'orthographic' = 'perspective';@@ -58,6 +102,10 @@      *  place to reapply a style rather than setting it once from outside. */     export let onGroundCreated: ((ground: any) => void) | undefined = undefined; +    // This viewer's engine, scene, camera and rig. Nothing here is shared+    // with other viewers on the page.+    const ctx = new ViewerContext();+     // Readiness ledger (adom/adom-3d-viewer#5): a consumer in a sandboxed     // frame cannot tell "painted" from "stuck behind the overlay" by counting     // meshes, so the viewer reports the state explicitly, with hints that@@ -80,7 +128,9 @@     /** Resolves with the ready report once the first scene is up. Once ready,      *  every call rebuilds the report from the CURRENT state (a model loaded      *  later via loadModel/loadModelBytes shows up). Never rejects: failures-     *  are in the report. */+     *  are in the report. A viewer destroyed before its scene was ready+     *  (gated and never opened, or still starting) resolves with+     *  `destroyed: true`. */     export function whenReady(): Promise<ViewerReadyReport> {         return readyReport ? Promise.resolve(buildReadyReport()) : readyPromise;     }@@ -90,12 +140,12 @@     }      function buildReadyReport(): ViewerReadyReport {-        const engine = AdomStatics.engine;-        const scene = AdomStatics.scene;-        const cam = AdomStatics.camera;+        const engine = ctx.engine;+        const scene = ctx.scene;+        const cam = ctx.camera;         const hints: ViewerHint[] = [];         const storage = prefsBackend();-        const overlay = container && container.querySelector('#babylonjsLoadingDiv') ? 'visible' : 'hidden';+        const overlay = !destroyed && container && container.querySelector('#babylonjsLoadingDiv') ? 'visible' : 'hidden';         // Count the LOADED content only (model roots and consumer-added         // roots), never the rig (view cube, axes, ground).         let meshes = 0, vertices = 0;@@ -130,7 +180,11 @@                     : `Environment map (${envStatus.source}) was still loading when the scene became ready.`,                 action: 'Pass environmentBytes (a .env file\'s bytes) or leave environmentUrl unset so the bundled studio map loads from memory.' });         }-        if (lastModelError) {+        if (lastModelError && lastModelTimedOut) {+            hints.push({ code: 'MODEL_LOAD_TIMEOUT', level: 'error',+                message: `The model did not load in time: ${lastModelError}.`,+                action: 'Check that the URL answers from this frame, or raise loadTimeoutMs for a large model on a slow link.' });+        } else if (lastModelError) {             hints.push({ code: 'MODEL_LOAD_FAILED', level: 'error',                 message: `The model did not load: ${lastModelError}`,                 action: 'Check that the URL is reachable from this frame (CSP connect-src, authentication) or pass the bytes with loadModelBytes(bytes, { extension: ".glb" }).' });@@ -142,13 +196,17 @@         if (overlay === 'visible') {             hints.push({ code: 'LOADING_OVERLAY_STUCK', level: 'error', message: 'The loading overlay is still shown after the scene reported ready.', action: 'Report this with the console output; the viewer hides the overlay in a finally block.' });         }+        if (destroyed) {+            hints.push({ code: 'VIEWER_DESTROYED', level: 'info', message: 'The viewer was destroyed; it shows nothing and takes no more loads.', action: 'Create a new viewer to show a model again.' });+        }         if (contextLost) {             hints.push({ code: 'WEBGL_CONTEXT_LOST', level: 'error', message: 'The WebGL context is lost; nothing paints until it is restored.', action: 'Destroy and recreate the viewer, or wait for the browser to restore the context.' });         }-        const ok = overlay === 'hidden' && !contextLost && !lastModelError && (envStatus.ready || envStatus.source === 'none')+        const ok = !destroyed && overlay === 'hidden' && !contextLost && !lastModelError && (envStatus.ready || envStatus.source === 'none')             && cspViolations.length === 0 && (!modelRequested || meshes > 0);         return {             ok,+            destroyed,             engine: { webglVersion: engine ? (engine as any).webGLVersion || 0 : 0, contextLost },             environment: { ...envStatus },             camera: { ready: !!cam, mode: cam && cam.isOrthographic() ? 'orthographic' : 'perspective' },@@ -228,6 +286,7 @@     const JUNK_NAME = /^(__|mesh|node|object|primitive|instance|clone)[\w.]*$|_primitive\d+$/i;      function tooltipForMesh(mesh: AbstractMesh): string | null {+        if (tooltips === 'off') return null;         // extras.tooltip may sit on the picked mesh or an ancestor node         // (Babylon splits multi-material prims into child meshes).         let n: any = mesh;@@ -237,6 +296,7 @@             if (n.name === '__root__') break;             n = n.parent;         }+        if (tooltips === 'authored') return null;         let name = mesh.name;         if (JUNK_NAME.test(name) && mesh.parent) name = mesh.parent.name;         if (!name || JUNK_NAME.test(name)) return null;@@ -256,8 +316,12 @@         return false;     } +    // What the pointer can land on: a scene.pick predicate replaces Babylon's+    // own enabled/visible/pickable check, so it has to repeat it.+    const pickable = (m: AbstractMesh) => m.isPickable && m.isVisible && m.visibility > 0 && m.isEnabled();+     function onPointerMoveTooltip(e: PointerEvent): void {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene || !container) return;         // No tooltip while dragging/orbiting or while placing an orbit pivot.         if (e.buttons !== 0 || pivotChordHeld) {@@ -268,8 +332,14 @@         const now = performance.now();         if (now - lastMeshPick < 50) return;         lastMeshPick = now;-        const pick = scene.pick(scene.pointerX, scene.pointerY, (m) => m.isPickable && m.isVisible);+        lastPointer = [scene.pointerX, scene.pointerY];+        const pick = overViewCube(scene.pointerX, scene.pointerY) ? null :+            scene.pick(scene.pointerX, scene.pointerY, pickable);         if (pick?.hit && pick.pickedMesh && belongsToContent(pick.pickedMesh)) {+            if (pick.pickedMesh !== hoverMesh) {+                hoverMesh = pick.pickedMesh;+                emit('hover', contentEvent(pick, scene.pointerX, scene.pointerY));+            }             let tip = tooltipForMesh(pick.pickedMesh);             // Consumer hook (adom/wiki#60 item 5). Runs on the pick the viewer             // already does, so hovering costs nothing extra. Returning a string@@ -313,12 +383,351 @@     // a listener should not be called 60 times a second while hovering nothing.     let hoverWasOver = false;     function notifyHoverOut(): void {+        if (hoverMesh) {+            hoverMesh = null;+            emit('hover', { mesh: null, path: [], point: null, x: lastPointer[0], y: lastPointer[1] });+        }         if (!hoverWasOver) return;         hoverWasOver = false;         if (!onMeshHover) return;         try { onMeshHover(null, null); } catch (e) { console.warn('[viewer] onMeshHover threw', e); }     } +    // Events (on). A pick is a click on the canvas that did not drag; a+    // hover event fires when the content mesh under the pointer changes,+    // and once with mesh null when it leaves content. Only loaded models+    // and content roots are reported: the ground, axes and view cube never+    // are, and the view cube's corner fires no pick and counts as empty+    // space for hover. load and error follow model loads, camera fires at+    // most once per rendered frame while the view changes, layer when a+    // layer is shown or hidden.+    type ViewerEventType = 'pick' | 'hover' | 'load' | 'error' | 'camera' | 'layer' | 'contextlost' | 'contextrestored';+    const listeners: Record<ViewerEventType, Set<(e: any) => void>> = {+        pick: new Set(), hover: new Set(), load: new Set(), error: new Set(),+        camera: new Set(), layer: new Set(), contextlost: new Set(), contextrestored: new Set(),+    };+    let hoverMesh: AbstractMesh | null = null;+    let lastPointer: [number, number] = [0, 0];+    let pointerDownAt: { x: number; y: number; button: number } | null = null;+    const CLICK_SLOP_PX = 4;++    /**+     * Listen for a viewer event: 'pick', 'hover', 'load', 'error', 'camera',+     * 'layer', 'contextlost' or 'contextrestored'. Returns a function that+     * removes the listener.+     */+    export function on(type: ViewerEventType, listener: (e: any) => void): () => void {+        const set = Object.prototype.hasOwnProperty.call(listeners, type) ? listeners[type] : undefined;+        if (!set) throw new Error(`unknown viewer event "${type}"; expected one of ${Object.keys(listeners).join(', ')}`);+        if (typeof listener !== 'function') throw new Error('on() needs a listener function');+        set.add(listener);+        return () => { set.delete(listener); };+    }++    function emit(type: ViewerEventType, event: any): void {+        for (const fn of [...listeners[type]]) {+            try { fn(event); } catch (e) { console.warn(`[viewer] ${type} listener threw`, e); }+        }+    }++    // Node names from the model root down to `mesh`, without the glTF+    // loader's own __root__.+    function contentPath(mesh: AbstractMesh): string[] {+        const roots = new Set<any>([...loadedRootNodes, ...contentRoots]);+        const names: string[] = [];+        let cur: any = mesh;+        while (cur) {+            if (cur.name !== '__root__') names.push(cur.name);+            if (roots.has(cur)) break;+            cur = cur.parent;+        }+        return names.reverse();+    }++    function contentEvent(pick: any, x: number, y: number) {+        const mesh: AbstractMesh | null = pick?.hit && pick.pickedMesh && belongsToContent(pick.pickedMesh) ? pick.pickedMesh : null;+        const p = mesh ? pick.pickedPoint : null;+        return { mesh, path: mesh ? contentPath(mesh) : [], point: p ? [p.x, p.y, p.z] : null, x, y };+    }++    // True when (x, y), in CSS pixels from the canvas corner, is inside the+    // view cube's corner. The render size is CSS pixels times the display's+    // pixel density.+    function overViewCube(x: number, y: number): boolean {+        const cam = ctx.viewCubeScene?.activeCamera;+        const engine = ctx.engine;+        if (!cam || !engine) return false;+        const k = engine.getHardwareScalingLevel();+        const w = engine.getRenderWidth() * k, h = engine.getRenderHeight() * k, vp = cam.viewport;+        const left = vp.x * w, top = (1 - vp.y - vp.height) * h;+        return x >= left && x <= left + vp.width * w && y >= top && y <= top + vp.height * h;+    }++    function onCanvasPointerUp(e: PointerEvent): void {+        const down = pointerDownAt;+        pointerDownAt = null;+        if (!down || down.button !== e.button || !listeners.pick.size) return;+        // Moved: an orbit or pan, not a click.+        if (Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_SLOP_PX) return;+        // Shift+Alt+click places the orbit pivot.+        if (e.shiftKey && e.altKey) return;+        const scene = ctx.scene;+        if (!scene || !canvas) return;+        const rect = canvas.getBoundingClientRect();+        const x = e.clientX - rect.left, y = e.clientY - rect.top;+        if (overViewCube(x, y)) return;+        const pick = scene.pick(x, y, pickable);+        emit('pick', { ...contentEvent(pick, x, y), button: e.button, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, altKey: e.altKey, metaKey: e.metaKey });+    }++    /**+     * Content nodes (the meshes and transform nodes of loaded models and+     * content roots) whose name equals `query`, matches it as a RegExp, or+     * for which it returns true as a function, in scene order. The ground,+     * axes and view cube are never included.+     */+    export function findNodes(query: string | RegExp | ((node: any) => boolean)): any[] {+        let test: (n: any) => boolean;+        if (typeof query === 'string') {+            test = (n) => n.name === query;+        } else if (Object.prototype.toString.call(query) === '[object RegExp]') {+            const re = new RegExp((query as RegExp).source, (query as RegExp).flags.replace(/[gy]/g, ''));+            test = (n) => re.test(n.name);+        } else if (typeof query === 'function') {+            test = (n) => !!query(n);+        } else {+            throw new Error('findNodes() takes a name, a RegExp or a function');+        }+        const found: any[] = [];+        const seen = new Set<any>();+        for (const root of [...loadedRootNodes, ...contentRoots]) {+            for (const n of [root, ...root.getDescendants(false)]) {+                if (seen.has(n)) continue;+                seen.add(n);+                if (test(n)) found.push(n);+            }+        }+        return found;+    }++    // Highlights. Each highlight() call adds a set; where sets share a mesh+    // the latest shows, and clearing it brings back the one beneath or the+    // mesh's own look. 'overlay' tints the mesh with Babylon's overlay pass,+    // which stays readable on gold and metal where an emissive tint washes+    // out to white; 'outline' draws a glow around the mesh.+    type HighlightMode = 'overlay' | 'outline';+    type HighlightSet = { meshes: Set<AbstractMesh>; color: Color3; alpha: number; mode: HighlightMode };+    let highlightSets: HighlightSet[] = [];+    const overlayOwn = new Map<AbstractMesh, { on: boolean; color: Color3; alpha: number }>();+    let highlightLayer: HighlightLayer | null = null;++    function highlightColor(c: unknown): Color3 {+        if (c === undefined) return new Color3(0.2, 0.52, 1.0);+        if (Array.isArray(c) && c.length === 3 && c.every(v => typeof v === 'number' && v >= 0 && v <= 1)) return new Color3(c[0], c[1], c[2]);+        if (typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c)) return Color3.FromHexString(c);+        throw new Error(`highlight color must be "#rrggbb" or [r, g, b] with each 0..1, not ${JSON.stringify(c)}`);+    }++    function meshesOf(target: any): AbstractMesh[] {+        const isQuery = typeof target === 'string' || typeof target === 'function' || Object.prototype.toString.call(target) === '[object RegExp]';+        const nodes = isQuery ? findNodes(target) : Array.isArray(target) ? target : target ? [target] : [];+        const out = new Set<AbstractMesh>();+        for (const n of nodes) {+            if (!n || typeof n.getChildMeshes !== 'function') continue;+            if (n.getTotalVertices?.() > 0) out.add(n);+            for (const m of n.getChildMeshes(false)) if (m.getTotalVertices?.() > 0) out.add(m);+        }+        return [...out];+    }++    // A disposed mesh leaves every highlight set and the isolation as it+    // goes, so neither holds it until the next call.+    function forgetMesh(m: AbstractMesh): void {+        let emptied = false;+        for (const s of highlightSets) if (s.meshes.delete(m) && s.meshes.size === 0) emptied = true;+        if (emptied) highlightSets = highlightSets.filter(s => s.meshes.size > 0);+        overlayOwn.delete(m);+        isolation?.saved.delete(m);+    }++    // Forget meshes a model replace or clear has disposed.+    function pruneHighlights(): void {+        for (const s of highlightSets) for (const m of s.meshes) if (m.isDisposed()) s.meshes.delete(m);+        highlightSets = highlightSets.filter(s => s.meshes.size > 0);+        for (const m of overlayOwn.keys()) if (m.isDisposed()) overlayOwn.delete(m);+    }++    function restyle(meshes: Iterable<AbstractMesh>): void {+        for (const m of meshes) {+            if (m.isDisposed()) { overlayOwn.delete(m); continue; }+            let top: HighlightSet | null = null;+            for (let i = highlightSets.length - 1; i >= 0 && !top; i--) if (highlightSets[i].meshes.has(m)) top = highlightSets[i];+            if (top?.mode === 'overlay') {+                if (!overlayOwn.has(m)) overlayOwn.set(m, { on: m.renderOverlay, color: m.overlayColor.clone(), alpha: m.overlayAlpha });+                m.overlayColor = top.color.clone();+                m.overlayAlpha = top.alpha;+                m.renderOverlay = true;+            } else {+                const own = overlayOwn.get(m);+                if (own) {+                    m.renderOverlay = own.on;+                    m.overlayColor = own.color;+                    m.overlayAlpha = own.alpha;+                    overlayOwn.delete(m);+                }+            }+            if (top?.mode === 'outline' && ctx.scene) {+                if (!highlightLayer) highlightLayer = new HighlightLayer('a3d-highlight', ctx.scene);+                highlightLayer.removeMesh(m as Mesh);+                highlightLayer.addMesh(m as Mesh, top.color);+            } else {+                highlightLayer?.removeMesh(m as Mesh);+            }+        }+    }++    /**+     * Highlight content: a node, an array of nodes, or a query as findNodes+     * takes. A node lights every mesh under it. Options: color ("#rrggbb" or+     * [r, g, b] in 0..1, default blue), alpha (overlay strength, default+     * 0.75) and mode ('overlay', the default, or 'outline'). Returns the+     * meshes lit and a clear() that removes this highlight alone.+     */+    export function highlight(+        target: any,+        options: { color?: string | [number, number, number]; alpha?: number; mode?: HighlightMode } = {},+    ): { meshes: AbstractMesh[]; clear: () => void } {+        const mode = options.mode ?? 'overlay';+        if (mode !== 'overlay' && mode !== 'outline') throw new Error(`highlight mode must be "overlay" or "outline", not "${mode}"`);+        const color = highlightColor(options.color);+        const alpha = options.alpha ?? 0.75;+        if (!(typeof alpha === 'number' && alpha >= 0 && alpha <= 1)) throw new Error('highlight alpha must be a number from 0 to 1');+        pruneHighlights();+        const meshes = meshesOf(target);+        const set: HighlightSet = { meshes: new Set(meshes), color, alpha, mode };+        if (meshes.length) {+            highlightSets.push(set);+            restyle(meshes);+        }+        return {+            meshes,+            clear: () => {+                const i = highlightSets.indexOf(set);+                if (i < 0) return;+                highlightSets.splice(i, 1);+                restyle(set.meshes);+            },+        };+    }++    /** Remove every highlight; each mesh gets its own look back. */+    export function clearHighlight(): void {+        const all = new Set<AbstractMesh>();+        for (const s of highlightSets) for (const m of s.meshes) all.add(m);+        highlightSets = [];+        restyle(all);+    }++    // Isolation. One at a time: a new isolate() replaces the last. It works+    // through mesh visibility and isPickable, which layers (isVisible) and+    // state groups (setEnabled) do not touch, so both keep working+    // underneath, and each mesh gets back exactly what isolate changed.+    // Hidden meshes also leave the shadow casters, because the shadow pass+    // ignores visibility.+    type Isolation = { mode: 'hide' | 'ghost'; saved: Map<AbstractMesh, { visibility: number; pickable: boolean; caster: boolean }> };+    let isolation: Isolation | null = null;++    /**+     * Show only `target` (a node, an array of nodes, or a findNodes query):+     * every other content mesh is hidden (mode 'hide', the default) or drawn+     * at `alpha` (mode 'ghost', default 0.15) and stops taking picks. When+     * the target matches no mesh nothing changes and `meshes` is empty.+     * Models loaded afterwards are not affected. Returns the meshes kept and+     * a clear() that ends this isolation.+     */+    export function isolate(+        target: any,+        options: { mode?: 'hide' | 'ghost'; alpha?: number } = {},+    ): { meshes: AbstractMesh[]; clear: () => void } {+        const mode = options.mode ?? 'hide';+        if (mode !== 'hide' && mode !== 'ghost') throw new Error(`isolate mode must be "hide" or "ghost", not "${mode}"`);+        const alpha = options.alpha ?? 0.15;+        if (!(typeof alpha === 'number' && alpha >= 0 && alpha <= 1)) throw new Error('isolate alpha must be a number from 0 to 1');+        const keep = meshesOf(target);+        if (!keep.length) return { meshes: [], clear: () => {} };+        clearIsolate();+        stopIntros();+        const kept = new Set(keep);+        const sg = ctx.shadowGenerator;+        const casters = sg?.getShadowMap()?.renderList ?? [];+        const iso: Isolation = { mode, saved: new Map() };+        for (const m of meshesOf([...loadedRootNodes, ...contentRoots])) {+            if (kept.has(m)) continue;+            const caster = casters.includes(m);+            iso.saved.set(m, { visibility: m.visibility, pickable: m.isPickable, caster });+            m.isPickable = false;+            if (mode === 'ghost') {+                m.visibility = m.visibility * alpha;+            } else {+                m.visibility = 0;+                if (caster) sg!.removeShadowCaster(m, false);+            }+        }+        isolation = iso;+        ctx.refreshShadows();+        return { meshes: keep, clear: () => { if (isolation === iso) clearIsolate(); } };+    }++    /** End the current isolation; every mesh it changed gets its own state back. */+    export function clearIsolate(): void {+        const iso = isolation;+        if (!iso) return;+        isolation = null;+        const sg = ctx.shadowGenerator;+        for (const [m, s] of iso.saved) {+            if (m.isDisposed()) continue;+            m.visibility = s.visibility;+            m.isPickable = s.pickable;+            if (iso.mode === 'hide' && s.caster) sg?.addShadowCaster(m, false);+        }+        ctx.refreshShadows();+    }++    // Where the camera's target and radius go so these meshes fill about+    // 80% of the view, keeping the current angles.+    function fitView(meshes: AbstractMesh[]): { center: Vector3; radius: number } | null {+        const camera = ctx.camera;+        if (!camera || !meshes.length) return null;+        let worldMin = new Vector3(Infinity, Infinity, Infinity);+        let worldMax = new Vector3(-Infinity, -Infinity, -Infinity);+        for (const m of meshes) {+            m.computeWorldMatrix(true);+            const bb = m.getBoundingInfo().boundingBox;+            worldMin = Vector3.Minimize(worldMin, bb.minimumWorld);+            worldMax = Vector3.Maximize(worldMax, bb.maximumWorld);+        }+        if (!isFinite(worldMin.x)) return null;+        const diag = worldMax.subtract(worldMin).length();+        if (diag === 0) return null;+        const fov = camera.fov || 0.8;+        const aspect = (ctx.engine?.getAspectRatio(camera) ?? 1);+        const hFov = 2 * Math.atan(Math.tan(fov / 2) * aspect);+        const effectiveFov = Math.min(fov, hFov);+        return { center: Vector3.Center(worldMin, worldMax), radius: (diag / 2) / Math.tan(effectiveFov / 2) / 0.8 };+    }++    /**+     * Turn the camera to `target` (a node, an array of nodes, or a findNodes+     * query) so it fills about 80% of the view, keeping the current angles;+     * the move double-click makes. Eases over `ms` like moveCamera. Resolves+     * with the final camera state, or null when the target matches no mesh.+     */+    export function focus(target: any, opts?: { ms?: number }): Promise<CameraState | null> {+        const fit = fitView(meshesOf(target));+        if (!fit) return Promise.resolve(null);+        return moveCamera({ target: [fit.center.x, fit.center.y, fit.center.z], radius: fit.radius }, opts);+    }+     // Layers: a GLB whose nodes declare layers gets a slide-out panel with     // per-layer visibility toggles.     //@@ -537,10 +946,12 @@         const layer = layers.find(l => l.name === name);         if (!layer) return false;         if (introRuns.has(name) || layer.introActive) cancelIntro(layer);+        const changed = layer.visible !== visible;         layer.visible = visible;         layer.meshes.forEach(m => { m.isVisible = visible; });         layers = layers; // trigger svelte reactivity-        AdomStatics.refreshShadows();+        ctx.refreshShadows();+        if (changed) emit('layer', { name, visible });         return true;     } @@ -563,7 +974,7 @@         layer.meshes.forEach(m => { m.visibility = alpha; });     }     function rampLayer(run: IntroRun, from: number, to: number, ms: number, done: () => void): void {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene) { setLayerAlpha(run.layer, to); done(); return; }         const t0 = performance.now();         if (run.observer) { scene.onBeforeRenderObservable.remove(run.observer); run.observer = null; }@@ -578,7 +989,7 @@         const run = introRuns.get(layer.name);         if (run) {             run.timers.forEach(t => clearTimeout(t));-            if (run.observer && AdomStatics.scene) AdomStatics.scene.onBeforeRenderObservable.remove(run.observer);+            if (run.observer && ctx.scene) ctx.scene.onBeforeRenderObservable.remove(run.observer);             introRuns.delete(layer.name);         }         setLayerAlpha(layer, 1);@@ -597,7 +1008,7 @@                 layer.introActive = true; layers = layers;                 setLayerAlpha(layer, 0);                 layer.meshes.forEach(m => { m.isVisible = true; });-                AdomStatics.refreshShadows();+                ctx.refreshShadows();                 rampLayer(run, 0, 1, it.fadeMs, () => {});             }, it.fadeInAt * 1000));             run.timers.push(window.setTimeout(() => {@@ -606,7 +1017,7 @@                     layer.meshes.forEach(m => { m.isVisible = false; m.visibility = 1; });                     layer.introActive = false; layers = layers;                     introRuns.delete(layer.name);-                    AdomStatics.refreshShadows();+                    ctx.refreshShadows();                 });             }, it.fadeOutAt * 1000));         }@@ -755,7 +1166,7 @@         writeState(key, enabled ? '1' : '0');         stateGroups = stateGroups;         contentLights?.invalidate();-        AdomStatics.refreshShadows();+        ctx.refreshShadows();         return true;     } @@ -768,7 +1179,7 @@         g.enabled = g.roots.some(r => r.isEnabled(false));         stateGroups = stateGroups;         contentLights?.invalidate();-        AdomStatics.refreshShadows();+        ctx.refreshShadows();         return true;     } @@ -821,6 +1232,7 @@         if (e.shiftKey && e.altKey) {             pivotHintVisible = false;         }+        pointerDownAt = { x: e.clientX, y: e.clientY, button: e.button };     }      const viewCubeCallbacks: ViewCubeUICallbacks = {@@ -854,7 +1266,9 @@             dropdownOpen = false;         }         if (e.key === 'Escape' && layersPanelOpen) layersPanelOpen = false;-        updatePivotChord(e);+        // Only the viewer the key belongs to shows the pivot chip; a+        // release always clears it (onKeyup).+        if (container && ownsPageEvent(container, e.target)) updatePivotChord(e);     }      function onKeyup(e: KeyboardEvent) {@@ -882,17 +1296,34 @@     let destroyed = false;     let boardLayers: ReturnType<typeof installBoardLayers> | undefined;     let pinFinish: ReturnType<typeof installPinFinish> | undefined;-    // Hosts may call loadModel immediately after init. The scene exists before-    // this async setup installs glTF material observers, so imports must wait-    // for setup (not whenReady, which can itself wait for an initial model).-    let viewerSetup: Promise<void> | undefined;     async function initViewer() {         if (!canvas || !container) return;-        await AdomStatics.init(canvas, zUp);-        const engine = AdomStatics.engine!;-        const scene = AdomStatics.scene!;+        await ctx.init(canvas, zUp);+        if (destroyed) return;+        const engine = ctx.engine!;+        const scene = ctx.scene!;+        // Both hook the glTF loader's material events, so they go in before+        // any import: the imports wait on `sceneUp`, which settles only when+        // this function returns, so a loadModel() called right after init+        // still gets the board shader and the pin finish.         boardLayers = installBoardLayers(scene);         pinFinish = installPinFinish(scene, { reflections: environment !== 'none' });+        engine.onContextLostObservable.add(() => {+            try { onContextLost?.(); } catch (e) { console.warn('[viewer] onContextLost threw', e); }+            emit('contextlost', {});+        });+        engine.onContextRestoredObservable.add(() => {+            try { onContextRestored?.(); } catch (e) { console.warn('[viewer] onContextRestored threw', e); }+            emit('contextrestored', {});+        });+        // One camera event per rendered frame in which the view changed.+        let cameraDirty = false;+        ctx.camera?.onViewMatrixChangedObservable.add(() => { cameraDirty = true; });+        scene.onAfterRenderObservable.add(() => {+            if (!cameraDirty) return;+            cameraDirty = false;+            if (listeners.camera.size) emit('camera', getCameraState());+        });          // The engine sizes the backing store from the canvas's CSS box at the         // display's pixel density; setting canvas.width by hand would pin it@@ -905,13 +1336,16 @@         document.addEventListener('securitypolicyviolation', onCspViolation);          try {-            await SceneBuilder.init(engine, {-                zUp, showViewCube, environmentUrl, environmentBytes, environment, viewCubeCallbacks,+            await SceneBuilder.init(ctx, {+                zUp, showViewCube, environmentUrl, environmentBytes, environment, viewCubeCallbacks, axes, background, shadows,                 onEnvironment: (s) => { envStatus = s; envResolve?.(s); },             });+            if (destroyed) return;+            if (bottomLight) setBottomLight(true);             // Built after the rig, so the viewer's own key/fill lights are             // counted as the viewer's and never culled as content.             contentLights = new ContentLights(scene, lightBudget);+            scene.onMeshRemovedObservable.add((m) => forgetMesh(m));         } catch (e) {             // The rig failed: report instead of leaving the overlay up forever.             lastModelError = null;@@ -948,7 +1382,7 @@             };             syncRendering(); -            const cam = AdomStatics.camera;+            const cam = ctx.camera;             if (cam && initialViewMode === 'orthographic' && !cam.isOrthographic()) {                 cam.toggleCameraMode();                 isOrtho = true;@@ -982,11 +1416,12 @@             canvas.addEventListener('pointermove', onPointerMoveTooltip);             canvas.addEventListener('pointerleave', onPointerLeaveCanvas);             canvas.addEventListener('pointerdown', onCanvasPointerDown);+            canvas.addEventListener('pointerup', onCanvasPointerUp);         });          resizeObserver = new ResizeObserver(() => {-            const eng = AdomStatics.engine;-            const sc = AdomStatics.scene;+            const eng = ctx.engine;+            const sc = ctx.scene;             if (canvas && eng) {                 eng.resize();                 sc?.render();@@ -1000,8 +1435,8 @@     // (the window dragged to a Retina screen, browser zoom), so watch it.     let deviceRatioQuery: MediaQueryList | null = null;     function onDeviceRatioChange() {-        AdomStatics.syncDeviceRatio();-        AdomStatics.scene?.render();+        ctx.syncDeviceRatio();+        ctx.scene?.render();         watchDeviceRatio();     }     function watchDeviceRatio() {@@ -1024,7 +1459,13 @@     /** Load a model from a URL alongside what is already shown (explicitly additive). */     export async function addModel(url: string): Promise<void> {         const result = await importModelFromUrl(url);-        if (result) { stateScope = modelScope(url); attachLoadedModel(result); }+        if (result) attachAndAnnounce(result, url);+    }++    function attachAndAnnounce(result: { meshes: AbstractMesh[] }, url: string | null): void {+        stateScope = modelScope(url);+        attachLoadedModel(result);+        emit('load', { url, root: result.meshes[0] ?? null, meshes: result.meshes.length });     }      /**@@ -1041,8 +1482,7 @@         if (!result) return;         if (gen !== modelGen) { disposeImport(result); return; }         disposeLoadedModels();-        stateScope = modelScope(url);-        attachLoadedModel(result);+        attachAndAnnounce(result, url);     }      /** replaceModel() for bytes already in hand (see loadModelBytes). */@@ -1052,14 +1492,12 @@         if (!result) return;         if (gen !== modelGen) { disposeImport(result); return; }         disposeLoadedModels();-        stateScope = null;-        attachLoadedModel(result);+        attachAndAnnounce(result, null);     }      async function importModelFromUrl(url: string): Promise<any> {-        await viewerSetup;-        if (destroyed) return null;-        const scene = AdomStatics.scene;+        await sceneUp;+        const scene = ctx.scene;         if (!scene) return null;          const lastSlash = url.lastIndexOf('/');@@ -1078,22 +1516,47 @@          modelRequested = true;         let result;+        const importing = SceneLoader.ImportMeshAsync('', rootUrl, sceneFilename, scene, undefined, pluginExt);+        let timer: ReturnType<typeof setTimeout> | undefined;         try {-            result = await SceneLoader.ImportMeshAsync('', rootUrl, sceneFilename, scene, undefined, pluginExt);+            result = loadTimeoutMs > 0+                ? await Promise.race([importing, new Promise<never>((_, reject) => {+                    timer = setTimeout(() => reject(new ModelLoadTimeout(url, loadTimeoutMs)), loadTimeoutMs);+                })])+                : await importing;         } catch (e) {             lastModelError = e instanceof Error ? e.message : String(e);+            lastModelTimedOut = e instanceof ModelLoadTimeout;+            // A load that finishes after its timeout already failed for the+            // caller: take it back out of the scene.+            if (lastModelTimedOut) importing.then(disposeImport, () => {});+            emit('error', { url, message: lastModelError, code: lastModelTimedOut ? 'MODEL_LOAD_TIMEOUT' : 'MODEL_LOAD_FAILED' });             throw e;+        } finally {+            clearTimeout(timer);         }+        // Outside loadTimeoutMs: a timeout discards the model, and these only+        // upgrade textures it already has. Each of their loads gives up on+        // its own after 10 s and leaves the model's own textures.         await boardLayers?.waitReady();         await pinFinish?.waitReady();+        if (destroyed) return null;         lastModelError = null;+        lastModelTimedOut = false;         return result;     } +    class ModelLoadTimeout extends Error {+        constructor(url: string, ms: number) {+            super(`${url} did not finish loading within ${Math.round(ms / 100) / 10} s`);+            this.name = 'ModelLoadTimeout';+        }+    }+    let lastModelTimedOut = false;+     async function importModelFromBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<any> {-        await viewerSetup;-        if (destroyed) return null;-        const scene = AdomStatics.scene;+        await sceneUp;+        const scene = ctx.scene;         if (!scene) return null;         modelRequested = true;         const ext = (options && options.extension) || '.glb';@@ -1102,11 +1565,14 @@             result = await SceneLoader.ImportMeshAsync('', '', bytes, scene, undefined, ext);         } catch (e) {             lastModelError = e instanceof Error ? e.message : String(e);+            emit('error', { url: null, message: lastModelError, code: 'MODEL_LOAD_FAILED' });             throw e;         }         await boardLayers?.waitReady();         await pinFinish?.waitReady();+        if (destroyed) return null;         lastModelError = null;+        lastModelTimedOut = false;         return result;     } @@ -1123,7 +1589,7 @@     /** loadModelBytes(), explicitly additive. */     export async function addModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {         const result = await importModelFromBytes(bytes, options);-        if (result) { stateScope = null; attachLoadedModel(result); }+        if (result) attachAndAnnounce(result, null);     }      // Release one import completely: animations stop and go, skeletons go,@@ -1139,7 +1605,7 @@     }      function attachLoadedModel(result: { meshes: AbstractMesh[] }): void {-        const shadowGenerator = AdomStatics.shadowGenerator;+        const shadowGenerator = ctx.shadowGenerator;         maybeShowPivotHint();          // EXT_mesh_gpu_instancing (gltf-transform optimize's default) loads as@@ -1167,16 +1633,68 @@                     shadowGenerator.addShadowCaster(m);                 }             });-            AdomStatics.refreshShadows();+            ctx.refreshShadows();             detectLayers();             adoptContentLights(result);             detectStateGroups();             mitigateCoplanarFighting(result.meshes);-            frameModel();+            if (homeOnLoad && !openedAtHome) { openedAtHome = true; goHome(); }+            else frameModel();+            applyAnimationPolicy((result as any).animationGroups || []);             scheduleIntros();         }     } +    // Animation policy (animate, repeat). The glTF loader starts a model's+    // first animation group looping; these are the groups it started, which+    // replayAnimations() plays again.+    let openedAtHome = false;+    let motionGroups: AnimationGroup[] = [];+    const animPlays = new WeakMap<AnimationGroup, { target: number; done: number }>();++    /** Play a group `times` times and rest on its last frame; 0 loops. */+    function playGroup(g: AnimationGroup, times: number): void {+        let st = animPlays.get(g);+        if (!st) {+            const state = { target: -1, done: 0 };+            st = state;+            animPlays.set(g, state);+            g.onAnimationGroupEndObservable.add(() => {+                if (state.target <= 0) return;+                state.done++;+                if (state.done < state.target) g.play(false);+            });+        }+        st.target = -1; // a stop() below must not count as a play+        g.stop();+        g.goToFrame(g.from);+        st.target = times;+        st.done = 0;+        g.play(times === 0);+    }++    function applyAnimationPolicy(groups: AnimationGroup[]): void {+        const started = groups.filter(g => g.isPlaying);+        motionGroups = [...motionGroups.filter(g => ctx.scene?.animationGroups.includes(g)), ...started];+        if (!animate) {+            for (const g of groups) { g.goToFrame(g.from); g.pause(); }+            return;+        }+        if (repeat > 0) for (const g of started) playGroup(g, repeat);+    }++    /** Play the model's animations again from their first frame: `repeat`+     *  times (looping when repeat is 0 and animate is on, else at least+     *  once), then rest on the last frame. Layer intros have their own+     *  replayIntros(). Returns false when the model has no animation. */+    export function replayAnimations(): boolean {+        const groups = motionGroups.filter(g => ctx.scene?.animationGroups.includes(g));+        if (!groups.length) return false;+        const times = repeat > 0 ? repeat : animate ? 0 : 1;+        for (const g of groups) playGroup(g, times);+        return true;+    }+     /**      * Take the GLB's own lights under the viewer's budget, and say something      * when the content puts one under a scaled node: glTF range is meters and@@ -1299,28 +1817,28 @@         loadedRootNodes = [];         layers = [];         layersPanelOpen = false;-        AdomStatics.refreshShadows();-        AdomStatics.camera?.disableBounds();+        ctx.refreshShadows();+        ctx.camera?.disableBounds();     }      /** Babylon scene — use to create/modify meshes (e.g. MeshBuilder.CreateSphere). */     export function getScene(): Scene | null {-        return AdomStatics.scene;+        return ctx.scene;     }      /** Babylon engine (resize, etc.). */     export function getEngine(): Engine | null {-        return AdomStatics.engine;+        return ctx.engine;     }      /** Active camera (orbit/pan/zoom). */     export function getCamera(): Camera | null {-        return AdomStatics.camera ?? null;+        return ctx.camera ?? null;     } -    /** Shadow generator — call addShadowCaster(mesh) for custom meshes that should cast shadows. */+    /** The shadow generator; call addShadowCaster(mesh) for custom meshes that should cast shadows. Null when the `shadows` option is false. */     export function getShadowGenerator(): ShadowGenerator | null {-        return AdomStatics.shadowGenerator;+        return ctx.shadowGenerator;     }      /**@@ -1334,8 +1852,8 @@      *   v.setShadowRefreshRate(v.BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME)      */     export function setShadowRefreshRate(rate: number | null): void {-        AdomStatics.shadowRefreshRateOverride = rate;-        AdomStatics.refreshShadows();+        ctx.shadowRefreshRateOverride = rate;+        ctx.refreshShadows();     }      /**@@ -1347,8 +1865,8 @@      * own resolution.      */     export async function captureScreenshot(options?: { width?: number; height?: number }): Promise<string> {-        const engine = AdomStatics.engine;-        const camera = AdomStatics.camera;+        const engine = ctx.engine;+        const camera = ctx.camera;         if (!engine || !camera) throw new Error('viewer is not initialized');         const w = options?.width || engine.getRenderWidth();         const h = options?.height || engine.getRenderHeight();@@ -1371,7 +1889,7 @@     export function addContentRoot(node: TransformNode, options?: { castShadows?: boolean; receiveShadows?: boolean }): void {         if (contentRoots.includes(node)) return;         contentRoots.push(node);-        const sg = AdomStatics.shadowGenerator;+        const sg = ctx.shadowGenerator;         const cast = options?.castShadows !== false;         const receive = options?.receiveShadows !== false;         const visit = (m: AbstractMesh) => {@@ -1384,14 +1902,14 @@         if ('getChildMeshes' in node) {             (node as AbstractMesh).getChildMeshes(false).forEach(visit);         }-        AdomStatics.refreshShadows();+        ctx.refreshShadows();     }      /** Unregister a content root from framing (does not dispose the node). */     export function removeContentRoot(node: TransformNode): void {         const i = contentRoots.indexOf(node);         if (i >= 0) contentRoots.splice(i, 1);-        AdomStatics.refreshShadows();+        ctx.refreshShadows();     }      /** Show or hide the ground plane at runtime. Re-runs frameModel to create/remove it. */@@ -1409,13 +1927,13 @@      *  Intensity 0.6 when on (matches the top hemisphere's perceived      *  brightness once spotlight contribution is added). */     export function setBottomLight(on: boolean): void {-        const bl = AdomStatics.bottomLight;+        const bl = ctx.bottomLight;         if (bl) bl.intensity = on ? 0.6 : 0;     }      /** Returns the current bottom-light state (true == on). */     export function getBottomLightState(): boolean {-        const bl = AdomStatics.bottomLight;+        const bl = ctx.bottomLight;         return !!(bl && bl.intensity > 0);     } @@ -1427,7 +1945,7 @@     // frame: a GLB's own coordinates, Z up, as the viewer shows them. Without     // it Home aims at the model's bounding-box center, which for a scene (a     // workcell pulled up by an arm, sideways by a rail) can float in the air.-    let homeView: { alpha: number; beta: number; radiusScale: number; target: Vector3 | null } | null = null;+    let homeViewState: { alpha: number; beta: number; radiusScale: number; target: Vector3 | null } | null = null;      /** Set (or clear with null) the view Home returns to: { alpha, beta, radiusScale?, target? } (radians; target [x, y, z] in the model's frame), the ?camera= contract. */     export function setHomeView(view: { alpha: number; beta: number; radiusScale?: number; target?: [number, number, number] | null } | null): void {@@ -1435,23 +1953,183 @@             const r = view.radiusScale == null ? 1 : Number(view.radiusScale);             const t = Array.isArray(view.target) && view.target.length === 3 && view.target.every((v) => Number.isFinite(Number(v)))                 ? new Vector3(Number(view.target[0]), Number(view.target[1]), Number(view.target[2])) : null;-            homeView = { alpha: Number(view.alpha), beta: Number(view.beta), radiusScale: Number.isFinite(r) && r > 0 ? r : 1, target: t };+            homeViewState = { alpha: Number(view.alpha), beta: Number(view.beta), radiusScale: Number.isFinite(r) && r > 0 ? r : 1, target: t };         } else {-            homeView = null;+            homeViewState = null;+        }+    }+    // Set at construction, so a model loaded right after init() already sees it.+    if (homeView) setHomeView(homeView);++    // Camera state and moves, for hosts that drive the camera (a guided+    // view, a test, an assistant). A move runs on its own timer as well as+    // on animation frames, so it ends where it was asked to even when the+    // browser throttles frames; a new move cancels the one in flight.+    type CameraState = { alpha: number; beta: number; radius: number; target: [number, number, number] };+    type CameraView = 'home' | 'fit' | 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom';+    // Directions in view cube space, so each view lands where clicking that+    // cube face does.+    const VIEW_FACES: Record<string, [number, number, number]> = {+        front: [0, -1, 0], back: [0, 1, 0], right: [1, 0, 0], left: [-1, 0, 0], top: [0, 0, 1], bottom: [0, 0, -1],+    };+    let cameraMove = 0;++    /** Where the camera is: alpha and beta in radians, radius, target [x, y, z]. */+    export function getCameraState(): CameraState | null {+        const c = ctx.camera;+        if (!c) return null;+        return { alpha: c.alpha, beta: c.beta, radius: c.radius, target: [c.target.x, c.target.y, c.target.z] };+    }++    function applyCameraState(s: CameraState): void {+        const c = ctx.camera;+        if (!c) return;+        c.alpha = s.alpha;+        c.beta = s.beta;+        c.radius = s.radius;+        c.target.set(s.target[0], s.target[1], s.target[2]);+    }++    // The limits a fit or Home sets: radius range, clip planes, panning+    // speed and target bounds.+    type CameraLimits = {+        lower: number | null; upper: number | null; minZ: number; maxZ: number; panning: number;+        bounds: ReturnType<AdomCamera['getTargetBounds']>;+    };+    function readLimits(c: AdomCamera): CameraLimits {+        return { lower: c.lowerRadiusLimit, upper: c.upperRadiusLimit, minZ: c.minZ, maxZ: c.maxZ, panning: c.panningSensibility, bounds: c.getTargetBounds() };+    }+    function writeLimits(c: AdomCamera, l: CameraLimits): void {+        c.lowerRadiusLimit = l.lower; c.upperRadiusLimit = l.upper; c.minZ = l.minZ; c.maxZ = l.maxZ; c.panningSensibility = l.panning;+        c.restoreTargetBounds(l.bounds);+    }+    // Limits the move in flight sets when it lands (see runCameraMove).+    let landingLimits: CameraLimits | null = null;++    // Where fn would leave the camera and the limits it would set, without+    // leaving either.+    function probeCamera(fn: () => void): { state: CameraState; limits: CameraLimits } | null {+        const c = ctx.camera;+        const saved = getCameraState();+        if (!c || !saved) return null;+        const before = readLimits(c);+        fn();+        const out = { state: getCameraState()!, limits: readLimits(c) };+        writeLimits(c, before);+        applyCameraState(saved);+        return out;+    }++    // Runs at(k) for k from 0 to 1 over ms; resolves with the final state.+    // With limits (a fit or Home), the move eases with the radius range and+    // target bounds relaxed and the clip planes covering both ends, and the+    // limits apply when it lands: one tighter than the starting view would+    // otherwise clamp the first frame. A move that replaces it lands them.+    function runCameraMove(ms: number, at: (k: number) => CameraState, limits: CameraLimits | null = null): Promise<CameraState | null> {+        const id = ++cameraMove;+        const c = ctx.camera;+        if (limits) landingLimits = limits;+        const land = () => {+            applyCameraState(at(1));+            if (landingLimits && ctx.camera) { writeLimits(ctx.camera, landingLimits); landingLimits = null; }+        };+        if (!(ms > 0)) {+            land();+            return Promise.resolve(getCameraState());+        }+        if (limits && c) {+            c.minZ = Math.min(c.minZ, limits.minZ);+            c.maxZ = Math.max(c.maxZ, limits.maxZ);+            c.lowerRadiusLimit = null;+            c.upperRadiusLimit = null;+            c.disableBounds();+        }+        const t0 = performance.now();+        return new Promise((done) => {+            let finished = false;+            const finish = () => {+                if (finished) return;+                finished = true;+                if (id === cameraMove) land();+                done(getCameraState());+            };+            const step = () => {+                if (finished) return;+                if (id !== cameraMove) { finished = true; done(getCameraState()); return; }+                const k = Math.min(1, (performance.now() - t0) / ms);+                if (k < 1) { applyCameraState(at(k)); requestAnimationFrame(step); }+                else finish();+            };+            requestAnimationFrame(step);+            setTimeout(finish, ms + 250);+        });+    }++    /**+     * Move the camera to a named view ('home', 'fit', or a view cube face:+     * 'front', 'back', 'left', 'right', 'top', 'bottom') or to a state+     * (any of alpha, beta, radius, target; the rest stay). With ms > 0 it+     * eases there, turning the short way round. Resolves with the final+     * state.+     */+    export function moveCamera(to: CameraView | Partial<CameraState>, opts?: { ms?: number }): Promise<CameraState | null> {+        const from = getCameraState();+        if (!from) return Promise.resolve(null);+        let goal: CameraState | null = { ...from, target: [...from.target] as [number, number, number] };+        let limits: CameraLimits | null = null;+        if (typeof to === 'string') {+            if (to === 'home' || to === 'fit') {+                const probe = probeCamera(to === 'home' ? goHome : () => frameModel());+                goal = probe?.state ?? null;+                limits = probe?.limits ?? null;+            } else if (VIEW_FACES[to]) {+                const [x, y, z] = VIEW_FACES[to];+                Object.assign(goal, ViewCubeBuilder.anglesFacing(x, y, z, !!ctx.scene?.useRightHandedSystem));+            } else {+                return Promise.reject(new Error(`unknown view "${to}": use home, fit, front, back, left, right, top or bottom`));+            }+        } else if (to && typeof to === 'object') {+            for (const k of ['alpha', 'beta', 'radius'] as const) if (Number.isFinite(to[k])) goal[k] = Number(to[k]);+            if (Array.isArray(to.target) && to.target.length === 3 && to.target.every(Number.isFinite)) goal.target = [to.target[0], to.target[1], to.target[2]];         }+        if (!goal) return Promise.resolve(null);+        const end = goal;+        let da = end.alpha - from.alpha;+        while (da > Math.PI) da -= 2 * Math.PI;+        while (da < -Math.PI) da += 2 * Math.PI;+        const ease = (k: number) => (k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2);+        const lerp = (a: number, b: number, e: number) => a + (b - a) * e;+        return runCameraMove(Number(opts?.ms) || 0, (k) => {+            const e = ease(k);+            return {+                alpha: from.alpha + da * e,+                beta: lerp(from.beta, end.beta, e),+                radius: lerp(from.radius, end.radius, e),+                target: [lerp(from.target[0], end.target[0], e), lerp(from.target[1], end.target[1], e), lerp(from.target[2], end.target[2], e)],+            };+        }, limits);+    }++    /** Turn the camera around its target: degrees (default 360) over ms (default 4000), at a steady rate. */+    export function orbit(opts?: { degrees?: number; ms?: number }): Promise<CameraState | null> {+        const from = getCameraState();+        if (!from) return Promise.resolve(null);+        const turn = (Number.isFinite(opts?.degrees) ? Number(opts!.degrees) : 360) * Math.PI / 180;+        const ms = Number.isFinite(opts?.ms) ? Math.max(0, Number(opts!.ms)) : 4000;+        return runCameraMove(ms, (k) => ({ ...from, alpha: from.alpha + turn * k }));     }      /** Jump camera to the home view (the host's, else front-top-right like the view cube corner) and re-frame the model. No animation. */     export function goHome(): void {-        const cam = AdomStatics.camera;+        const cam = ctx.camera;         if (!cam) return;-        if (homeView) {+        if (homeViewState) {             frameModel();             // The framing's distance and bounds stay; only the orbit point moves.-            if (homeView.target) cam.setTarget(homeView.target.clone(), false, false, true);-            cam.alpha = homeView.alpha;-            cam.beta = homeView.beta;-            cam.radius = cam.radius * homeView.radiusScale;+            if (homeViewState.target) cam.setTarget(homeViewState.target.clone(), false, false, true);+            cam.alpha = homeViewState.alpha;+            cam.beta = homeViewState.beta;+            cam.radius = cam.radius * homeViewState.radiusScale;             return;         }         cam.rotateToCubeTopFrontRight(0);@@ -1465,7 +2143,7 @@      * Returns the new state.      */     export function toggleAxes(target: 'world' | 'mesh-local', enabled?: boolean): boolean {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene) return false;         if (target === 'world') {             const next = enabled !== undefined ? enabled : !AxisHelpers.isWorldAxesVisible(scene);@@ -1485,7 +2163,7 @@         return false;     }     export function getAxesState(): { world: boolean; meshLocal: boolean } {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene) return { world: false, meshLocal: false };         return {             world: AxisHelpers.isWorldAxesVisible(scene),@@ -1495,7 +2173,7 @@      /** Set camera projection to perspective or orthographic. */     export function setProjectionMode(ortho: boolean): void {-        const cam = AdomStatics.camera;+        const cam = ctx.camera;         if (!cam) return;         const currentlyOrtho = cam.isOrthographic();         if (currentlyOrtho !== ortho) {@@ -1506,7 +2184,7 @@      /** Current projection: `'orthographic'` or `'perspective'`. */     export function getProjectionMode(): 'perspective' | 'orthographic' {-        return AdomStatics.camera?.isOrthographic() ? 'orthographic' : 'perspective';+        return ctx.camera?.isOrthographic() ? 'orthographic' : 'perspective';     }  @@ -1515,8 +2193,8 @@      * calculate optimal camera distance, and animate to it via moveCamTo.      */     function onDoubleClick(): void {-        const scene = AdomStatics.scene;-        const camera = AdomStatics.camera;+        const scene = ctx.scene;+        const camera = ctx.camera;         if (!scene || !camera) return;          const pickInfo = scene.pick(scene.pointerX, scene.pointerY);@@ -1557,28 +2235,9 @@         }         if (meshes.length === 0) return; -        // Compute world bounds-        let worldMin = new Vector3(Infinity, Infinity, Infinity);-        let worldMax = new Vector3(-Infinity, -Infinity, -Infinity);-        for (const m of meshes) {-            m.computeWorldMatrix(true);-            const bb = m.getBoundingInfo().boundingBox;-            worldMin = Vector3.Minimize(worldMin, bb.minimumWorld);-            worldMax = Vector3.Maximize(worldMax, bb.maximumWorld);-        }-        if (!isFinite(worldMin.x)) return;--        const center = Vector3.Center(worldMin, worldMax);-        const sizeVec = worldMax.subtract(worldMin);-        const diag = sizeVec.length();-        if (diag === 0) return;--        // Calculate optimal camera distance to fill ~80% of the viewport-        const fov = camera.fov || 0.8;-        const aspect = (AdomStatics.engine?.getAspectRatio(camera) ?? 1);-        const hFov = 2 * Math.atan(Math.tan(fov / 2) * aspect);-        const effectiveFov = Math.min(fov, hFov);-        const radius = (diag / 2) / Math.tan(effectiveFov / 2) / 0.8;+        const fit = fitView(meshes);+        if (!fit) return;+        const { center, radius } = fit;          // Animate to the target using moveCamTo (keeps current alpha/beta)         const pos = camera.position.clone();@@ -1599,8 +2258,8 @@      * @param rootsToFrame When provided, frame only these roots. Otherwise frame all.      */     export function frameModel(fillFraction: number = 1, rootsToFrame?: TransformNode[]): void {-        const scene = AdomStatics.scene;-        const camera = AdomStatics.camera;+        const scene = ctx.scene;+        const camera = ctx.camera;         const roots = rootsToFrame ?? [...loadedRootNodes, ...contentRoots];         if (!scene || !camera || roots.length === 0) return; @@ -1617,6 +2276,13 @@             m.isVisible && m.getTotalVertices && m.getTotalVertices() > 0         );         if (visible.length === 0) return;+        // What the camera frames: the meshes on show, without any an+        // isolation set aside or that sit at visibility 0. The rig below+        // (light, ground, shadow bias, clip planes, zoom limits) keeps the+        // whole model's bounds, so it is still right when the isolation ends.+        const setAside = isolation ? isolation.saved : null;+        const shown = visible.filter(m => m.visibility > 0 && !setAside?.has(m));+        const framed = shown.length ? shown : visible;          let worldMin = new Vector3(Infinity, Infinity, Infinity);         let worldMax = new Vector3(-Infinity, -Infinity, -Infinity);@@ -1636,9 +2302,14 @@         camera.upperRadiusLimit = Infinity;          camera.zoomOn(visible, true);+        const wholeRadius = camera.radius * fillFraction;+        if (framed !== visible) camera.zoomOn(framed, true);         camera.radius *= fillFraction;          const radius = camera.radius;+        // Far plane and zoom-out limit cover the whole model even when the+        // camera frames part of it.+        const reach = Math.max(radius, wholeRadius);         const halfSize = modelSize / 2;         const center = Vector3.Center(worldMin, worldMax); @@ -1647,7 +2318,7 @@         // layer with no depth, so the far plane only has to cover the model         // and max zoom-out. Keeping it model-scaled preserves depth precision         // (the old 7500 floor with a meter-scale near plane was #45).-        camera.maxZ = radius * 20;+        camera.maxZ = reach * 20;         camera.panningSensibility = 5000 / halfSize;          const pad = 0.2;@@ -1656,7 +2327,7 @@             worldMin.y - extent.y * pad, worldMax.y + extent.y * pad,             worldMin.z - extent.z * pad, worldMax.z + extent.z * pad         );-        camera.upperRadiusLimit = radius / 0.3;+        camera.upperRadiusLimit = reach / 0.3;         camera.lowerRadiusLimit = halfSize * 0.01;          // 3d-viewer-design §8a — world-origin axis helper sized to 15% of@@ -1665,7 +2336,7 @@         AxisHelpers.refreshAxisScale(scene, halfSize);          // Reposition SpotLight proportional to model size, angled from front-left.-        const spotLight = AdomStatics.spotLight;+        const spotLight = ctx.spotLight;         if (spotLight) {             const spotHeight = modelSize * 3;             const lateralOffset = modelSize * 1.2;@@ -1692,7 +2363,7 @@             // already model-scaled below, so a modest constant works at every             // size; normalBias is in WORLD units so it must scale with the             // model diagonal.-            const shadowGenerator = AdomStatics.shadowGenerator;+            const shadowGenerator = ctx.shadowGenerator;             if (shadowGenerator) {                 shadowGenerator.bias = 0.0008;                 shadowGenerator.normalBias = modelSize * 0.004;@@ -1776,17 +2447,21 @@         // model casts nothing. frameModel always runs after init is complete         // and on every fit/home, so it's the reliable place. The renderList         // index guard keeps it idempotent across re-frames.-        const sg = AdomStatics.shadowGenerator;+        // A mesh at visibility 0 (hidden by an isolation, or by the host)+        // is left out: Babylon's shadow pass ignores visibility, so it would+        // still cast.+        const sg = ctx.shadowGenerator;         if (sg) {             const sm = sg.getShadowMap();             for (const m of visible) {                 m.receiveShadows = true;+                if (m.visibility <= 0) continue;                 if (sm && sm.renderList && sm.renderList.indexOf(m) === -1) {                     sm.renderList.push(m);                 }             }         }-        AdomStatics.refreshShadows();+        ctx.refreshShadows();     }      /** Show the Babylon Inspector. Lazy-imported so it lands in its own@@ -1815,7 +2490,7 @@     }      export async function showDebugLayer(): Promise<void> {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene) return;         // The inspector expects the whole engine on window.BABYLON.         await loadBabylon();@@ -1826,12 +2501,12 @@      /** Hide the Inspector. */     export function hideDebugLayer(): void {-        AdomStatics.scene?.debugLayer.hide();+        ctx.scene?.debugLayer.hide();     }      /** Toggle the Inspector visibility. */     export async function toggleDebugLayer(): Promise<void> {-        const scene = AdomStatics.scene;+        const scene = ctx.scene;         if (!scene) return;         if (scene.debugLayer.isVisible()) {             hideDebugLayer();@@ -1840,25 +2515,83 @@         }     } +    // Model loads asked for before the scene exists (right after init, or+    // behind a closed gate) wait on `sceneUp`. It also settles when setup+    // fails or the viewer is destroyed; the load then finds no scene.+    let sceneUpResolve: () => void = () => {};+    const sceneUp = new Promise<void>((r) => { sceneUpResolve = r; });+    function start() {+        initViewer().finally(sceneUpResolve);+    }++    // Click to load: nothing starts until the gate opens.+    let gated = !!gate;++    /** Start a viewer created with `gate`, as its Load button does. Resolves with the ready report. */+    export function openGate(): Promise<ViewerReadyReport> {+        if (gated && !destroyed) {+            gated = false;+            start();+        }+        return whenReady();+    }++    /** True while a viewer created with `gate` waits to be opened. */+    export function isGated(): boolean {+        return gated;+    }++    function gateText(g: { bytes?: number; vertices?: number }): string {+        const facts: string[] = [];+        if (Number.isFinite(g.bytes) && g.bytes! > 0) facts.push(`${(g.bytes! / 1048576).toFixed(1)} MB`);+        if (Number.isFinite(g.vertices) && g.vertices! > 0) facts.push(`${(g.vertices! / 1e6).toFixed(1)} M vertices`);+        const size = facts.length ? `This model is ${facts.join(', ')}. ` : '';+        return `${size}Decoding a model this large can use up the tab's memory, so it does not load until you ask.`;+    }++    // The root holds this viewer's canvas and the host's controls for it+    // (the standalone help card): its parent element, when it has one.+    let untrackRoot: (() => void) | null = null;++    // An http(s) URL, or a relative one: parsed the way the browser parses+    // an href, so tabs, newlines or case cannot slip a javascript: past it.+    function safeDownloadUrl(url: unknown): boolean {+        let ok = false;+        try { ok = typeof url === 'string' && ['http:', 'https:'].includes(new URL(url, 'https://base.invalid/').protocol); } catch { ok = false; }+        if (!ok) console.warn('[adom-3d-viewer] gate.downloadUrl must be an http(s) or relative URL; no download link is shown for', url);+        return ok;+    }     onMount(() => {-        viewerSetup = initViewer();+        untrackRoot = trackViewerRoot(container.parentElement ?? container);+        if (!gated) start();     });      onDestroy(() => {         destroyed = true;+        sceneUpResolve();+        untrackRoot?.();+        // Hosts awaiting whenReady() get a report instead of a promise that+        // never settles; onReady is for a scene that came up, so it stays quiet.+        if (!readyReport) {+            readyReport = buildReadyReport();+            readyResolve?.(readyReport);+        }         renderVisibilityCleanup?.();         document.removeEventListener('securitypolicyviolation', onCspViolation);         canvas?.removeEventListener('dblclick', onDoubleClick);         canvas?.removeEventListener('pointermove', onPointerMoveTooltip);         canvas?.removeEventListener('pointerleave', onPointerLeaveCanvas);         canvas?.removeEventListener('pointerdown', onCanvasPointerDown);+        canvas?.removeEventListener('pointerup', onCanvasPointerUp);         if (pivotHintTimer) clearTimeout(pivotHintTimer);         resizeObserver?.disconnect();+        for (const run of introRuns.values()) run.timers.forEach(t => clearTimeout(t));+        introRuns.clear();         deviceRatioQuery?.removeEventListener('change', onDeviceRatioChange);-        AdomStatics.engine?.stopRenderLoop();+        ctx.engine?.stopRenderLoop();         boardLayers?.dispose();         pinFinish?.dispose();-        AdomStatics.dispose();+        ctx.dispose();     }); </script> @@ -1867,6 +2600,19 @@ <div class="viewer-container" class:pivot-mode={pivotChordHeld} bind:this={container}>     <canvas bind:this={canvas}></canvas> +    {#if gated && gate}+        <div class="a3d-gate" role="dialog" aria-label="Large 3D model">+            <h2>Large 3D model</h2>+            <p>{gateText(gate)}</p>+            <div class="a3d-gate-actions">+                <button type="button" class="a3d-gate-load" on:click={() => openGate()}>Load 3D model</button>+                {#if gate.downloadUrl && safeDownloadUrl(gate.downloadUrl)}+                    <a href={gate.downloadUrl} download>Download</a>+                {/if}+            </div>+        </div>+    {/if}+     {#if meshTipText && !tooltipText && !dropdownOpen}         <div             class="mesh-tooltip"@@ -2000,6 +2746,53 @@ </div>  <style>+    .a3d-gate {+        position: absolute;+        inset: 0;+        z-index: 5;+        display: flex;+        flex-direction: column;+        align-items: center;+        justify-content: center;+        padding: 24px;+        text-align: center;+        background: linear-gradient(#5a6b7e, #2a3340);+        color: #e0e0e0;+        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+    }+    .a3d-gate h2 {+        margin: 0 0 8px;+        font-size: 17px;+        font-weight: 600;+    }+    .a3d-gate p {+        margin: 0;+        max-width: 420px;+        font-size: 13px;+        line-height: 1.5;+        color: #c8ced6;+    }+    .a3d-gate-actions {+        display: flex;+        gap: 10px;+        margin-top: 16px;+    }+    .a3d-gate-actions button,+    .a3d-gate-actions a {+        font: inherit;+        font-size: 13px;+        padding: 7px 16px;+        border-radius: 8px;+        border: 1px solid rgba(255, 255, 255, 0.25);+        background: rgba(30, 34, 38, 0.6);+        color: #e0e0e0;+        text-decoration: none;+        cursor: pointer;+    }+    .a3d-gate-actions .a3d-gate-load {+        background: rgba(30, 34, 38, 0.92);+        border-color: rgba(255, 255, 255, 0.45);+    }     .viewer-container {         position: relative;         width: 100%;
src/VIEWER_CONTEXT.md+2−2
@@ -17,7 +17,7 @@ If you load a Z-up GLB into a default Babylon scene without adjusting anything,  ### What this viewer does when `zUp={true}` (default) -- **Scene:** `scene.useRightHandedSystem = true` is set in `AdomStatics.init`. In this codebase, handedness is tied to the `zUp` flag.+- **Scene:** `scene.useRightHandedSystem = true` is set in `ViewerContext.init`. In this codebase, handedness is tied to the `zUp` flag. - **Camera:** In `AdomCamera`'s constructor, `camera.upVector = (0, 0, 1)` when `zUp` is true, so the orbit camera treats Z as up. Orbit, pan, zoom, and Q/E "up/down" all respect Z as vertical. - **Lights:** In `SceneBuilder.init`, the hemispheric light direction and the SpotLight's initial position are chosen based on `zUp`. In `ThreeDViewer.svelte`'s `frameModel()`, the SpotLight is repositioned: when `zUp` is true, height is applied along Z and lateral offset in X/Y; when false, height is along Y and offset in X/Z. So "above the model" and "to the side" stay correct for both conventions. - **Ground plane (optional):** Babylon's `MeshBuilder.CreateGround` creates a quad in the **XZ** plane (normal Y). When `zUp` is true, the viewer rotates that ground by `Math.PI/2` around X so the plane lies in the **XY** plane (normal Z) and positions it at `worldMin.z`. When `zUp` is false, the ground stays in the XZ plane and is positioned at `worldMin.y`. So in both modes the ground sits "under" the content along the chosen up axis.@@ -73,7 +73,7 @@ These are the main ways this component diverges from a vanilla Babylon.js setup.  ## Where `zUp` is used in the codebase -- **`AdomStatics.init(canvas, zUp)`** — Sets `scene.useRightHandedSystem = zUp` and passes `zUp` into `AdomCamera`.+- **`ViewerContext.init(canvas, zUp)`** — Sets `scene.useRightHandedSystem = zUp` and passes `zUp` into `AdomCamera`. - **`AdomCamera` constructor** — Sets `this.upVector = zUp ? new Vector3(0, 0, 1) : new Vector3(0, 1, 0)`. - **`SceneBuilder.init(engine, { zUp, ... })`** — Hemispheric light direction and SpotLight initial position/direction use `zUp`. - **`ThreeDViewer.svelte`** — `frameModel()` uses `zUp` for SpotLight position (which axis is "height" vs "lateral") and for ground plane rotation and position (`worldMin.z` vs `worldMin.y`).
src/lib/adom-babylon/3DViewer/SceneBuilder.ts+61−66
@@ -8,28 +8,8 @@ import { Layer } from '@babylonjs/core/Layers/layer'; import { Vector3 } from '@babylonjs/core/Maths/math.vector'; import { Color3, Color4 } from '@babylonjs/core/Maths/math.color'; import { ImageProcessingConfiguration } from '@babylonjs/core/Materials/imageProcessingConfiguration';-import type { Engine, Scene } from '@babylonjs/core';--/**- * The shadow map's size in pixels: 8192 on a desktop, 2048 on a phone or- * tablet (a coarse pointer on a screen up to 1400 px) or a device reporting- * 4 GB of memory or less. At 8192 with percentage-closer filtering the map is- * a half-float color target plus a depth texture, several hundred MB; on iOS,- * where a page and its frames share one content process, that killed the tab- * and reloaded it, over and over (wiki component pages, 2026-10-23). 2048 is a- * sixteenth of that and still sharp at a phone's size.- */-export function shadowMapSize(): number {-    try {-        const coarse = typeof window.matchMedia === 'function' && window.matchMedia('(pointer: coarse)').matches;-        const small = Math.max(window.screen.width, window.screen.height) <= 1400;-        const memory = (navigator as unknown as { deviceMemory?: number }).deviceMemory;-        if ((coarse && small) || (typeof memory === 'number' && memory <= 4)) return 2048;-    } catch { /* no window: a desktop size */ }-    return 8192;-} import { ViewCubeBuilder, type ViewCubeUICallbacks } from './ViewCubeBuilder';-import { AdomStatics } from '../AdomStatics';+import type { ViewerContext } from '../ViewerContext'; import { STUDIO_ENV_BASE64 } from '../assets/studioEnv'; import { initAxisHelpers } from './AxisHelpers'; @@ -55,6 +35,13 @@ export interface SceneBuilderOptions {     /** Fires when the environment map is ready or failed. */     onEnvironment?: (status: EnvironmentStatus) => void;     viewCubeCallbacks?: ViewCubeUICallbacks;+    /** World axes at startup (default true). */+    axes?: boolean;+    /** false: no shadow generator and no shadow map (default true). */+    shadows?: boolean;+    /** 'studio' (default) is the steel-blue gradient; 'transparent' clears+     *  to alpha 0 so the page shows through; '#rrggbb' is a flat color. */+    background?: string; }  /** Decode the bundled studio .env into bytes (a base64 data URL). */@@ -66,13 +53,16 @@ export function studioEnvironmentBytes(): Uint8Array { }  export class SceneBuilder {-    static init(engine: Engine, options: SceneBuilderOptions = { zUp: true, showViewCube: true }): Promise<void> {-        if (!AdomStatics.scene) {-            console.error("SceneBuilder Error: AdomStatics.scene is null.");-            return Promise.reject(new Error("Scene is undefined in AdomStatics."));+    /** Builds the lights, shadows, environment, background, view cube and+     *  axes into the context's scene, and stores the rig on the context. */+    static init(ctx: ViewerContext, options: SceneBuilderOptions = { zUp: true, showViewCube: true }): Promise<void> {+        const { engine, scene, camera } = ctx;+        if (!engine || !scene || !camera) {+            return Promise.reject(new Error("SceneBuilder: the viewer context has no engine, scene or camera."));         }-        const scene = AdomStatics.scene;-        const { zUp, showViewCube, environmentUrl, environmentBytes, environment, onEnvironment, viewCubeCallbacks } = options;+        const { zUp, showViewCube, environmentUrl, environmentBytes, environment, onEnvironment, viewCubeCallbacks, axes } = options;+        const background = options.background ?? 'studio';+        const shadows = options.shadows !== false;          return new Promise<void>((resolve, reject) => {             try {@@ -100,7 +90,7 @@ export class SceneBuilder {                 bottomLight.parent = rootNode;                 bottomLight.diffuse = new Color3(1, 1, 1);                 bottomLight.groundColor = new Color3(0.5, 0.5, 0.5);-                AdomStatics.bottomLight = bottomLight;+                ctx.bottomLight = bottomLight;                  // SpotLight — sole direct light, matching Hydrogen.                 // Cone naturally darkens ground edges. Repositioned by@@ -112,24 +102,24 @@ export class SceneBuilder {                 const spotLight = new SpotLight('spotLight', spotPos, spotDir, Math.PI * 0.7, 50, scene);                 spotLight.intensity = 2_000_000;                 spotLight.parent = rootNode;-                AdomStatics.spotLight = spotLight;--                const shadowGenerator = new ShadowGenerator(shadowMapSize(), spotLight);-                scene.shadowsEnabled = true;-                shadowGenerator.usePercentageCloserFiltering = true;-                shadowGenerator.filteringQuality = ShadowGenerator.QUALITY_HIGH;-                shadowGenerator.bias = 0.0002 / 1000;-                shadowGenerator.normalBias = 0.08 / 1000;-                shadowGenerator.darkness = -1;-                shadowGenerator.forceBackFacesOnly = true;-                shadowGenerator.frustumEdgeFalloff = 0;--                AdomStatics.shadowGenerator = shadowGenerator;+                ctx.spotLight = spotLight;++                scene.shadowsEnabled = shadows;+                if (shadows) {+                    const shadowGenerator = ctx.createShadowGenerator(spotLight);+                    shadowGenerator.usePercentageCloserFiltering = true;+                    shadowGenerator.filteringQuality = ShadowGenerator.QUALITY_HIGH;+                    shadowGenerator.bias = 0.0002 / 1000;+                    shadowGenerator.normalBias = 0.08 / 1000;+                    shadowGenerator.darkness = -1;+                    shadowGenerator.forceBackFacesOnly = true;+                    shadowGenerator.frustumEdgeFalloff = 0;+                }                  // Catch incompatible shadow-filter combos no matter when a                 // consumer sets them (pages flip flags long after load).                 scene.onBeforeRenderObservable.add(() => {-                    AdomStatics.enforceShadowFilterCompat();+                    ctx.enforceShadowFilterCompat();                 });                  // Studio environment map for PBR reflections. Bundled as@@ -172,6 +162,12 @@ export class SceneBuilder {                     fromBytes(studioEnvironmentBytes(), 'bundled-studio');                 } +                // Approved Board Look 0.6 lighting/tone defaults. The gold+                // pins' dedicated reflection map is installed separately.+                scene.environmentIntensity = 0.5;+                scene.imageProcessingConfiguration.toneMappingEnabled = true;+                scene.imageProcessingConfiguration.toneMappingType = ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL;+                 // 3d-viewer-design skill §3b — neutral steel-blue gradient.                 // Top  ≈ #5a6b7e  (0.353, 0.420, 0.494)  ~37% luma                 // Bot  ≈ #2a3340  (0.165, 0.200, 0.251)  ~20% luma@@ -188,36 +184,35 @@ export class SceneBuilder {                 // clip, seam, or z-fight, and the gradient is identical at                 // every camera angle. PBR reflections on the model still come                 // from scene.environmentTexture, which is untouched.-                const SKILL_BG_TOP = '#5a6b7e';-                const SKILL_BG_BOTTOM = new Color3(0.165, 0.200, 0.251);-                const bgTex = new DynamicTexture('bgGradientTex', { width: 4, height: 512 }, scene, false);-                const bgCtx = bgTex.getContext();-                const grad = bgCtx.createLinearGradient(0, 0, 0, 512);-                grad.addColorStop(0, SKILL_BG_TOP);-                grad.addColorStop(1, SKILL_BG_BOTTOM.toHexString());-                bgCtx.fillStyle = grad;-                bgCtx.fillRect(0, 0, 4, 512);-                bgTex.update();-                const bgLayer = new Layer('bgGradient', null, scene, true);-                bgLayer.texture = bgTex;--                // Approved Board Look 0.6 lighting/tone defaults. The gold-                // pins' dedicated reflection map is installed separately.-                scene.environmentIntensity = 0.5;-                scene.imageProcessingConfiguration.toneMappingEnabled = true;-                scene.imageProcessingConfiguration.toneMappingType = ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL;-                scene.clearColor = new Color4(SKILL_BG_BOTTOM.r, SKILL_BG_BOTTOM.g, SKILL_BG_BOTTOM.b, 1);+                if (background === 'studio') {+                    const SKILL_BG_TOP = '#5a6b7e';+                    const SKILL_BG_BOTTOM = new Color3(0.165, 0.200, 0.251);+                    const bgTex = new DynamicTexture('bgGradientTex', { width: 4, height: 512 }, scene, false);+                    const bgCtx = bgTex.getContext();+                    const grad = bgCtx.createLinearGradient(0, 0, 0, 512);+                    grad.addColorStop(0, SKILL_BG_TOP);+                    grad.addColorStop(1, SKILL_BG_BOTTOM.toHexString());+                    bgCtx.fillStyle = grad;+                    bgCtx.fillRect(0, 0, 4, 512);+                    bgTex.update();+                    const bgLayer = new Layer('bgGradient', null, scene, true);+                    bgLayer.texture = bgTex;+                    scene.clearColor = new Color4(SKILL_BG_BOTTOM.r, SKILL_BG_BOTTOM.g, SKILL_BG_BOTTOM.b, 1);+                } else if (background === 'transparent') {+                    scene.clearColor = new Color4(0, 0, 0, 0);+                } else {+                    const c = Color3.FromHexString(background);+                    scene.clearColor = new Color4(c.r, c.g, c.b, 1);+                } -                if (showViewCube && AdomStatics.camera) {-                    ViewCubeBuilder.createViewCube(scene, AdomStatics.camera, engine, viewCubeCallbacks);+                if (showViewCube) {+                    ctx.viewCubeScene = ViewCubeBuilder.createViewCube(scene, camera, engine, viewCubeCallbacks);                 }                  // 3d-viewer-design §8 axis helpers — non-negotiable.                 // §8a world-origin axes (default ON, toggleable via API)                 // §8c screen-space corner triad (always on)-                if (AdomStatics.camera) {-                    initAxisHelpers(scene, AdomStatics.camera, { worldDefaultOn: true });-                }+                initAxisHelpers(scene, camera, { worldDefaultOn: axes !== false });                  scene.onPointerObservable.add(() => { /* Ensure pointer events */ }); 
src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+82−85
@@ -17,7 +17,6 @@ import { Ray } from '@babylonjs/core/Culling/ray'; import { SolidParticle } from '@babylonjs/core/Particles/solidParticle'; import { VertexBuffer } from '@babylonjs/core/Buffers/buffer'; import { SolidParticleSystem } from "@babylonjs/core/Particles/solidParticleSystem";-import { AdomStatics } from "../AdomStatics"; import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight'; import { ShaderMaterial } from '@babylonjs/core/Materials/shaderMaterial' import { BoundingInfo } from '@babylonjs/core/Culling/boundingInfo'@@ -31,10 +30,6 @@ export interface ViewCubeUICallbacks {  export class ViewCubeBuilder {     // One-shot log guard: a per-frame error must not spam the console (#79).-    private static _frameErrorLogged = false-    private static prevPick: number = -1-    private static prevDarkened: number = -1-    private static particleColorMap: Map<number, Color4> = new Map()      /**      * Creates a combined texture atlas for all six faces of the cube@@ -97,6 +92,26 @@ export class ViewCubeBuilder {         return angle - Math.PI * 2 * Math.floor((angle + Math.PI) / (2 * Math.PI))     } +    /**+     * The main camera's alpha and beta that look at the scene from direction+     * (x, y, z) in view cube space (Z up, front is -Y), as clicking the cube+     * there would. The main scene's handedness decides the alpha reflection.+     */+    static anglesFacing(x: number, y: number, z: number, rightHanded: boolean): { alpha: number; beta: number } {+        // atan2 gives the cube-scene (right-handed) azimuth that faces the+        // direction. The MAIN camera alpha that lands on it must use the SAME+        // reflection as the display sync: identity when the main scene is+        // right-handed (zUp=true), PI-x when it's left-handed (zUp=false).+        // Without matching the display, clicking a face navigated to its+        // mirror (front-left jumped to front-right).+        const adjust = x === 0 && y === 0 ? Math.PI / 2 : -Math.PI / 2+        const cubeAlpha = Math.atan2(x, y) + adjust+        return {+            alpha: rightHanded ? cubeAlpha : Math.PI - cubeAlpha,+            beta: Math.acos(z / Math.sqrt(x * x + y * y + z * z)),+        }+    }+     /**      * Calculates the shortest angle distance between two angles      * @internal@@ -183,7 +198,12 @@ export class ViewCubeBuilder {         engine: WebGPUEngine | Engine,         uiCallbacks?: ViewCubeUICallbacks     ) {+        // Babylon gives objects created without a scene to the last scene+        // created (EngineStore.LastCreatedScene). The cube's scene is+        // internal, so creating it leaves that as it was.+        const lastCreated = EngineStore._LastCreatedScene         const scene2 = new Scene(engine)+        EngineStore._LastCreatedScene = lastCreated         scene2.autoClear = false         scene2.useRightHandedSystem = true @@ -216,6 +236,12 @@ export class ViewCubeBuilder {         let fitHovered = false         let viewModeHovered = false         let buttonsAlpha = 0+        // Cube particle ids: the hovered one, the one facing the main camera,+        // and each particle's own colour to return to.+        let prevPick = -1+        let prevDarkened = -1+        const particleColorMap = new Map<number, Color4>()+        let frameErrorLogged = false          mainScene.afterRender = () => {             // adom/wiki#79: the cube used to vanish permanently, with no way back@@ -228,8 +254,8 @@ export class ViewCubeBuilder {             try {                 cubeFrameBody()             } catch (e) {-                if (!ViewCubeBuilder._frameErrorLogged) {-                    ViewCubeBuilder._frameErrorLogged = true+                if (!frameErrorLogged) {+                    frameErrorLogged = true                     console.warn("[view-cube] frame handler error (cube still renders):", e)                 }             }@@ -380,7 +406,7 @@ export class ViewCubeBuilder {         const sps = this.generateSPS(scene2, cr, es)          sps.initParticles = () => {-            this.initParticlePositions(sps, cr, es)+            this.initParticlePositions(sps, cr, es, particleColorMap)         }          // Update the label planes to always face the camera@@ -480,6 +506,12 @@ export class ViewCubeBuilder {         // under the pointer and a release within CLICK_SLOP_PX of it, still         // over that face, is the click that animates the camera there.         const CLICK_SLOP_PX = 4++        // A cube particle shows one of four colours, chosen from its state:+        // its own, darkened (the face nearest the camera), hovered, or both.+        const darkColor = new Color4(0.4, 0.4, 0.4, 1)+        const hoverColor = new Color4(0.7, 0.7, 1, 0.9)+        const darkHoverColor = new Color4(0.47, 0.47, 0.9, 1)         let pendingFace: { id: number; x: number; y: number } | null = null          scene2.onPointerDown = function (evt, pickResult) {@@ -569,15 +601,7 @@ export class ViewCubeBuilder {                 }             }             if (isOverButton) {-                if (ViewCubeBuilder.prevPick !== -1) {-                    const clearColor = new Color4(0.8, 0.8, 1, 0.3)-                    const prevDiff = ViewCubeBuilder.particleColorMap-                        .get(ViewCubeBuilder.prevPick)-                        ?.subtract(clearColor)-                    if (prevDiff) sps.particles[ViewCubeBuilder.prevPick].color!.addInPlace(prevDiff)-                    ViewCubeBuilder.prevPick = -1-                    sps.setParticles()-                }+                setHovered(-1)                 return             }             highlightFromPointer(evt.offsetX, evt.offsetY, pickResult)@@ -585,8 +609,6 @@ export class ViewCubeBuilder {         const endMousePos = camera2.viewport.x + camera2.viewport.width         viewCubeMesh.enablePointerMoveEvents = true -        EngineStore._LastCreatedScene = AdomStatics.scene-         return scene2          function cubeRayCollision(pickResult: PickingInfo) {@@ -606,7 +628,7 @@ export class ViewCubeBuilder {             // outside the canvas) must not spin, and a null pick must not throw             // through the caller and leave highlight state inconsistent (#79).             let guard = 0-            while ((id < 3 || 29 < id) && guard++ < 16) {+            while ((id < 3 || 29 <= id) && guard++ < 16) {                 if (!result.pickedPoint || !result.ray) return                 const ray = new Ray(                     result.pickedPoint.add(@@ -622,29 +644,15 @@ export class ViewCubeBuilder {                 result = next                 id = nextParticle.idx             }-            if (id < 3 || 29 < id) return+            if (id < 3 || 29 <= id) return              return id         }          function rotateToParticle(id: number) {             const position = sps.particles[id].position-            const adjust = position.x === 0 && position.y === 0 ? Math.PI/2 : -Math.PI/2-            // atan2 gives the cube-scene (right-handed) azimuth that faces the-            // clicked particle. The MAIN camera alpha that lands on this face-            // must use the SAME reflection as the display sync above: identity-            // when the main scene is right-handed (zUp=true), PI-x when it's-            // left-handed (zUp=false). Without matching the display, clicking a-            // face navigated to its mirror (front-left jumped to front-right).-            const cubeAlpha = Math.atan2(position.x, position.y) + adjust-            const targetAlpha = mainScene.useRightHandedSystem-                ? cubeAlpha-                : Math.PI - cubeAlpha-            const targetBeta = Math.acos(-                position.z /-                    Math.sqrt(-                        position.x * position.x + position.y * position.y + position.z * position.z-                    )+            const { alpha: targetAlpha, beta: targetBeta } = ViewCubeBuilder.anglesFacing(+                position.x, position.y, position.z, mainScene.useRightHandedSystem             )              if (targetAlpha !== undefined && targetBeta !== undefined) {@@ -658,8 +666,6 @@ export class ViewCubeBuilder {                 darkenFromCameraPosition(id)                 sps.setParticles() -                sps.particles[id].color!.addInPlace(new Color4(0, 0, 0, 0))-                 const animate_dur = 0.5                  ViewCubeBuilder._animateCameraToPosition(@@ -676,7 +682,6 @@ export class ViewCubeBuilder {                         darkenFromCameraPosition(getClosestParticleId())                         sps.setParticles()                     })-                    sps.particles[id].color!.subtractInPlace(new Color4(0, 0, 0, 0))                 }, animate_dur * 1000)             }         }@@ -691,55 +696,47 @@ export class ViewCubeBuilder {             return distances.indexOf(Math.min(...distances)) + 3         } -        function darkenFromCameraPosition(id: number) {-            const targetColor = new Color4(0.4, 0.4, 0.4, 1)-            if (id && id !== ViewCubeBuilder.prevDarkened) {-                const prevDiff = ViewCubeBuilder.particleColorMap-                    .get(ViewCubeBuilder.prevDarkened)-                    ?.subtract(targetColor)-                if (prevDiff) sps.particles[ViewCubeBuilder.prevDarkened].color!.addInPlace(prevDiff)-                ViewCubeBuilder.prevDarkened = id-                const diffFromOriginal = ViewCubeBuilder.particleColorMap-                    .get(id)!-                    .subtract(targetColor)-                sps.particles[id].color!.subtractInPlace(diffFromOriginal)-            }+        function updateParticleColor(id: number) {+            const originalColor = particleColorMap.get(id)+            const particleColor = sps.particles[id]?.color+            if (!originalColor || !particleColor) return+            const isDarkened = id === prevDarkened+            const isHovered = id === prevPick+            particleColor.copyFrom(+                isDarkened && isHovered ? darkHoverColor+                    : isHovered ? hoverColor+                    : isDarkened ? darkColor+                    : originalColor+            )+        }++        function darkenFromCameraPosition(id: number | undefined) {+            if (id === undefined || id < 0 || id === prevDarkened) return+            const previous = prevDarkened+            prevDarkened = id+            if (previous !== -1) updateParticleColor(previous)+            updateParticleColor(id)+        }++        function setHovered(id: number) {+            if (id === prevPick) return+            const previous = prevPick+            prevPick = id+            if (previous !== -1) updateParticleColor(previous)+            if (id !== -1) updateParticleColor(id)+            sps.setParticles()         }          function highlightFromPointer(xOffset: number, yOffset: number, pickResult: PickingInfo) {-            if (!pickResult) return             //Only ray-cast if pointer is in the viewcube viewport.             //Uncomment other conditions if the viewcube is moved from the top right corner.-            const targetColor = new Color4(0.8, 0.8, 1, 0.3)--            if (pickResult.faceId === -1) {-                const prevDiff = ViewCubeBuilder.particleColorMap-                    .get(ViewCubeBuilder.prevPick)-                    ?.subtract(targetColor)-                if (prevDiff) sps.particles[ViewCubeBuilder.prevPick].color!.addInPlace(prevDiff)-                ViewCubeBuilder.prevPick = -1-            }-            if (+            const inViewport =                 // camera2.viewport.x < evt.offsetX / engine.getRenderWidth() &&                 // 1 - endMousePosY < evt.offsetY / engine.getRenderHeight() &&                 xOffset / (engine.getRenderWidth() * engine.getHardwareScalingLevel()) < endMousePos &&                 yOffset / (engine.getRenderHeight() * engine.getHardwareScalingLevel()) < 1 - camera2.viewport.y-            ) {-                const id = cubeRayCollision(pickResult)-                if (id && id !== ViewCubeBuilder.prevPick) {-                    const prevDiff = ViewCubeBuilder.particleColorMap-                        .get(ViewCubeBuilder.prevPick)-                        ?.subtract(targetColor)-                    if (prevDiff)-                        sps.particles[ViewCubeBuilder.prevPick].color!.addInPlace(prevDiff)-                    ViewCubeBuilder.prevPick = id-                    const diffFromOriginal = ViewCubeBuilder.particleColorMap-                        .get(id)!-                        .subtract(targetColor)-                    sps.particles[id].color!.subtractInPlace(diffFromOriginal)-                    sps.setParticles()-                }-            }+            const id = pickResult && inViewport ? cubeRayCollision(pickResult) : undefined+            setHovered(id ?? -1)         }     } @@ -775,7 +772,7 @@ export class ViewCubeBuilder {     /***      Initialize particles with proper positions, rotations and UVs     ***/-    private static initParticlePositions(sps: SolidParticleSystem, cr: number, es: number) {+    private static initParticlePositions(sps: SolidParticleSystem, cr: number, es: number, colors: Map<number, Color4>) {         // Define UV mappings for the 6 sides of the box in the texture atlas         // Format: [u1, v1, u2, v2] represents the rectangle in the texture         const uvMapping: [number, number, number, number][] = [@@ -934,7 +931,7 @@ export class ViewCubeBuilder {             particle.position.set(...(facePositions[i] as [number, number, number]))             particle.rotation.set(...(faceRotations[i] as [number, number, number]))             particle.uvs.set(...uvMapping[i])-            this.particleColorMap.set(i + 3, particle.color!.clone())+            colors.set(i + 3, particle.color!.clone())         }          // Set corner particles@@ -943,7 +940,7 @@ export class ViewCubeBuilder {             particle.position.set(...(cornerPositions[i] as [number, number, number]))             const color = new Color4(0.7, 0.7, 0.7, 1)             particle.color = color-            this.particleColorMap.set(i + 9, color.clone())+            colors.set(i + 9, color.clone())         }          // Set edge box particles@@ -953,7 +950,7 @@ export class ViewCubeBuilder {             particle.rotation.set(...(edgeBoxRotations[i] as [number, number, number]))             const color = new Color4(0.8, 0.8, 0.8, 1)             particle.color = color-            this.particleColorMap.set(i + 17, color.clone())+            colors.set(i + 17, color.clone())         }          // Set edge cylinder particles@@ -963,7 +960,7 @@ export class ViewCubeBuilder {             particle.rotation.set(...(edgeCylinderRotations[i] as [number, number, number]))             const color = new Color4(0, 0, 0, 1)             particle.color = color-            this.particleColorMap.set(i + 29, color.clone())+            colors.set(i + 29, color.clone())         }          // Set axis cylinder particles
src/lib/adom-babylon/Camera/AdomCamera.ts+22−7
@@ -1,5 +1,6 @@ import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera'; import { getPref } from '../util/prefs';+import { ownsPageEvent } from '../util/pageOwner'; import { Vector3 } from '@babylonjs/core/Maths/math.vector'; import { Scene } from '@babylonjs/core/scene'; import { KeyboardEventTypes, PointerEventTypes, type IKeyboardEvent } from '@babylonjs/core/Events';@@ -8,7 +9,6 @@ import { HighlightLayer } from '@babylonjs/core/Layers/highlightLayer'; import { Color3 } from '@babylonjs/core/Maths/math.color' import { Animation } from '@babylonjs/core/Animations/animation'; import { QuadraticEase, EasingFunction } from '@babylonjs/core/Animations/easing';-import { AdomStatics } from '../AdomStatics'; import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; import { writable, get } from 'svelte/store'; @@ -435,10 +435,14 @@ export class AdomCamera extends ArcRotateCamera{     /**      * Set up event listeners for external control (e.g. automated tests or external UI).      * Trigger via window.dispatchEvent(new CustomEvent('camera:change_view', { detail: { orientation: 'top' } })).+     * With several viewers on a page, an event dispatched on window moves the+     * viewer the pointer or focus was in last; one dispatched with+     * `bubbles: true` on an element inside a viewer moves that viewer.      */     private setupExternalEventListeners(): void {         // Create a single event listener that handles all orientations         const changeViewListener = (event: Event) => {+            if (this.canvas && !ownsPageEvent(this.canvas, event.target)) return;             const customEvent = event as CustomEvent;             const orientation = customEvent.detail?.orientation;             @@ -1079,12 +1083,10 @@ export class AdomCamera extends ArcRotateCamera{         ]);         this.animations.push(animBeta); -        if (AdomStatics.scene) {-            // console.log("Started moveCamTo anim");-            const anim = AdomStatics.scene.beginAnimation(this, 0, totalFrames, false);-            await anim.waitAsync();-            // console.log("Finished moveCamTo anim");-        }+        // console.log("Started moveCamTo anim");+        const anim = this._scene.beginAnimation(this, 0, totalFrames, false);+        await anim.waitAsync();+        // console.log("Finished moveCamTo anim");     }      /**@@ -1164,6 +1166,19 @@ export class AdomCamera extends ArcRotateCamera{         this.checkAndEnforceBounds();     } +    /** The target bounds and whether they are enforced, for restoreTargetBounds(). */+    public getTargetBounds(): { minX: number | null; maxX: number | null; minY: number | null; maxY: number | null; minZ: number | null; maxZ: number | null; enforce: boolean } {+        return { ...this.targetBounds, enforce: this.enforceBounds };+    }++    /** Put back bounds read with getTargetBounds(). */+    public restoreTargetBounds(b: ReturnType<AdomCamera['getTargetBounds']>): void {+        const { enforce, ...bounds } = b;+        this.targetBounds = bounds;+        this.enforceBounds = enforce;+        if (enforce) this.checkAndEnforceBounds();+    }+     /**      * Disable bounds checking for the camera target      */
src/lib/adom-babylon/ViewerContext.tsadded+272
@@ -0,0 +1,272 @@+import { Engine } from '@babylonjs/core/Engines/engine';+import { Scene } from '@babylonjs/core/scene';+import { AdomCamera } from './Camera/AdomCamera';+import type { Nullable } from '@babylonjs/core/types';+import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';+import type { SpotLight } from '@babylonjs/core/Lights/spotLight';+import type { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight';+import { RenderTargetTexture } from '@babylonjs/core/Materials/Textures/renderTargetTexture';++// The highest display density the scene renders at (see init).+const MAX_DEVICE_RATIO = 2;++// Contexts that hold a shadow generator. Each viewer has its own engine, so+// each shadow map is a separate GPU allocation, and an 8192 x 8192 map is+// about 256 MB: the edge length shrinks as more of them are live.+const shadowed = new Set<ViewerContext>();++/**+ * The largest shadow map this device gets: 2048 on a phone or tablet (a coarse+ * pointer on a screen up to 1400 px) or a device reporting 4 GB of memory or+ * less, else 8192. At 8192 with percentage-closer filtering the map is a+ * half-float color target plus a depth texture, several hundred MB; on iOS,+ * where a page and its frames share one content process, that killed the tab+ * and reloaded it, over and over (wiki component pages, 2026-10-23; 0.12.4).+ */+export function deviceShadowCap(): number {+    try {+        const coarse = typeof window.matchMedia === 'function' && window.matchMedia('(pointer: coarse)').matches;+        const small = Math.max(window.screen.width, window.screen.height) <= 1400;+        const memory = (navigator as unknown as { deviceMemory?: number }).deviceMemory;+        if ((coarse && small) || (typeof memory === 'number' && memory <= 4)) return 2048;+    } catch { /* no window: a desktop size */ }+    return 8192;+}++/** The shadow map edge length while `count` viewers have shadows, within the device's cap. */+export function shadowMapSize(count: number): number {+    return Math.min(count <= 1 ? 8192 : count <= 4 ? 4096 : 2048, deviceShadowCap());+}++function resizeShadowMaps(): void {+    const size = shadowMapSize(shadowed.size);+    for (const ctx of shadowed) {+        const sg = ctx.shadowGenerator;+        if (!sg || sg.mapSize === size) continue;+        // Babylon rebuilds the map (keeping its casters); refreshShadows+        // puts this viewer's refresh rate back on the new one.+        sg.mapSize = size;+        ctx.refreshShadows();+    }+}++/**+ * One viewer's engine, scene, camera and lighting rig. Each viewer owns one,+ * so several viewers on a page each render into their own canvas and+ * disposing one leaves the others running.+ */+export class ViewerContext {+    public engine: Nullable<Engine> = null;+    public scene: Nullable<Scene> = null;+    public camera: Nullable<AdomCamera> = null;+    public shadowGenerator: Nullable<ShadowGenerator> = null;+    public spotLight: Nullable<SpotLight> = null;+    /** Bottom-fill hemispheric light — illuminates the underside of parts.+     *  Default OFF (intensity 0). Toggleable via ThreeDViewer.setBottomLight(). */+    public bottomLight: Nullable<HemisphericLight> = null;+    /** The view cube's own scene, drawn over a corner of the canvas; null without a view cube. */+    public viewCubeScene: Nullable<Scene> = null;++    /**+     * Initialize the engine and scene. A second call on the same context+     * does nothing.+     * @param canvas - The canvas element to render to+     * @param zUp - If true, use Z-up coordinate system (default). If false, use Y-up (Babylon default).+     */+    public async init(canvas: HTMLCanvasElement, zUp: boolean = true): Promise<void> {+        if (this.engine && this.scene && this.camera) {+            return;+        }++        // preserveDrawingBuffer + stencil: without them the backbuffer is+        // undefined after the frame is presented, so canvas.toDataURL() and+        // any consumer-side capture return a blank image (adom/wiki#60 item+        // 9). Babylon's own CreateScreenshotUsingRenderTarget re-renders into+        // an RTT and does not need this, but consumers reaching for the canvas+        // directly do, and the cost is one retained buffer.+        // adaptToDeviceRatio: render at the display's pixel density, not at+        // CSS pixels, or a 2x (Retina) screen shows the scene upscaled and+        // blurry next to the page's text. Capped at 2x: a 3x phone would pay+        // 9x the fill of 1x for detail nobody can see at that size.+        this.engine = new Engine(canvas, true, {+            useHighPrecisionFloats: true,+            preserveDrawingBuffer: true,+            stencil: true,+            limitDeviceRatio: MAX_DEVICE_RATIO,+        }, true);+        // Decode images (environment mip levels, GLB-embedded textures) as+        // ImageBitmaps instead of <img src="blob:...">. Babylon's default on+        // WebGL builds a blob URL per image, and a sandboxed frame whose CSP+        // has no blob: in img-src (the wiki's widget and readme frames)+        // blocks every one of them: the environment never uploads and the+        // materials wait forever (adom/adom-3d-viewer#5). createImageBitmap+        // takes the Blob directly; no URL, no fetch, nothing for a CSP to see.+        if (typeof createImageBitmap === 'function') {+            (this.engine as any)._features.forceBitmapOverHTMLImageElement = true;+        }+        this.scene = new Scene(this.engine);+        this.scene.useRightHandedSystem = zUp;++        this.camera = new AdomCamera(this.scene, canvas, zUp);+        this.camera.disableBounds();+        this.camera.setClickToSetRotationPoint(false);+        this.scene.activeCamera = this.camera;+    }++    /**+     * Re-read the display's pixel density (the window moved to a screen with+     * a different one, or the page zoom changed) and resize to it.+     */+    public syncDeviceRatio(): void {+        if (!this.engine) return;+        const ratio = Math.min(window.devicePixelRatio || 1, MAX_DEVICE_RATIO);+        if (Math.abs(this.engine.getHardwareScalingLevel() - 1 / ratio) > 1e-6) {+            this.engine.setHardwareScalingLevel(1 / ratio);+        }+        this.engine.resize();+    }++    /**+     * Create the shadow generator for `light` and store it on this context.+     * Every live viewer's shadow map is then sized for the new count (see+     * shadowMapSize).+     */+    public createShadowGenerator(light: SpotLight): ShadowGenerator {+        shadowed.add(this);+        const sg = new ShadowGenerator(shadowMapSize(shadowed.size), light);+        this.shadowGenerator = sg;+        resizeShadowMaps();+        return sg;+    }++    /**+     * Releases everything this context created. The context is empty, the+     * camera's listeners and the shadow map are gone at once; the scene and+     * engine may follow a moment later (see below).+     */+    public dispose(): void {+        const { scene, engine, camera, shadowGenerator, spotLight, bottomLight } = this;+        this.scene = null;+        this.engine = null;+        this.camera = null;+        this.shadowGenerator = null;+        this.spotLight = null;+        this.bottomLight = null;+        this.viewCubeScene = null;+        shadowed.delete(this);+        engine?.stopRenderLoop();+        camera?.dispose();+        // The shadow map is the largest allocation and no texture decode+        // reads it, so it goes now rather than with the scene; the other+        // viewers' maps then grow back.+        if (shadowGenerator) {+            shadowGenerator.dispose();+            resizeShadowMaps();+        }+        const release = () => {+            spotLight?.dispose();+            bottomLight?.dispose();+            scene?.dispose();+            engine?.dispose();+        };+        // Babylon finishes an RGBD texture (the environment map, and the+        // lighting lookup texture the first PBR material creates) after its+        // load event: it decodes the data through an async shader import and+        // compile, then reads the texture's scene. A scene disposed inside+        // that window makes the callback throw. The texture stays not ready+        // from its creation to the end of that decode, and Babylon has no+        // event for the end, so the scene is kept until no texture is still+        // loading or decoding: each one is ready or has a load error. Two+        // quiet checks in a row catch a decode that hands off to another in+        // a later task. The 30 s backstop is only for a decode that never+        // ends (a shader that fails to compile); it is not a guess at how+        // long a decode takes.+        const pending = () => !!scene && scene.textures.some(t => {+            const internal = t.getInternalTexture();+            return !!internal && !internal.isReady && !t.loadingError;+        });+        const until = performance.now() + 30_000;+        let quiet = 0;+        const poll = () => {+            quiet = pending() ? 0 : quiet + 1;+            if (quiet >= 2 || performance.now() > until) release();+            else setTimeout(poll, 50);+        };+        poll();+    }++    private _pcssTransparencyWarned = false;++    /**+     * PCSS combined with soft transparent shadows renders NO shadows at all,+     * silently (pixel-diff proven: PCSS 0.0% change, PCF 26.7%). Auto-correct+     * to PCF so consumers flipping useContactHardeningShadow on a scene with+     * enableSoftTransparentShadow don't lose shadows. Called from+     * refreshShadows and once per frame (two boolean reads, negligible).+     */+    public enforceShadowFilterCompat(): void {+        const sg = this.shadowGenerator;+        if (!sg) return;+        if (sg.useContactHardeningShadow && sg.enableSoftTransparentShadow) {+            if (!this._pcssTransparencyWarned) {+                this._pcssTransparencyWarned = true;+                console.warn(+                    '[adom-3d-viewer] PCSS (useContactHardeningShadow) + enableSoftTransparentShadow ' ++                    'silently renders no shadows. Falling back to PCF (usePercentageCloserFiltering). ' ++                    'Use PCF whenever soft transparent shadows are enabled.'+                );+            }+            sg.useContactHardeningShadow = false;+            sg.usePercentageCloserFiltering = true;+        }+    }++    /**+     * Consumer override for the shadow map refresh rate (adom/wiki#60 item 7).+     *+     * null means "auto": every frame for animated content, once for static.+     * Set a RenderTargetTexture.REFRESHRATE_* value to pin it. Without this an+     * external caller who set refreshRate through getShadowGenerator() had it+     * silently reverted by the next refreshShadows(), which fires on every+     * load, frame and layer toggle. Content driven from OUTSIDE the viewer+     * (a consumer animating an added content root) has no animationGroups on+     * the scene, so auto-detection cannot see it and guesses wrong.+     */+    public shadowRefreshRateOverride: number | null = null;++    /**+     * Re-renders the shadow map once. Defers by one frame so that any light+     * frustum or caster-list changes from the current frame are applied first.+     */+    public refreshShadows(): void {+        if (!this.shadowGenerator || !this.scene) return;+        const sg = this.shadowGenerator;+        const shadowMap = sg.getShadowMap();+        if (!shadowMap) return;++        this.enforceShadowFilterCompat();++        if (this.shadowRefreshRateOverride !== null) {+            shadowMap.refreshRate = this.shadowRefreshRateOverride;+            return;+        }++        // Animated models (glTF animationGroups, e.g. a press-fit insertion or a+        // spin) need the shadow map re-rendered EVERY frame so the cast shadows+        // track the moving meshes. A one-shot render freezes the shadow at frame 0,+        // which reads as broken (the pin moves, its shadow does not). Keep the+        // cheap render-once only for fully static models.+        const hasAnimation = (this.scene.animationGroups || []).length > 0;+        if (hasAnimation) {+            shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME;+            return;+        }++        this.scene.onAfterRenderObservable.addOnce(() => {+            // An override set after this was queued wins.+            if (this.shadowRefreshRateOverride !== null) return;+            shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;+            shadowMap.resetRefreshCounter();+        });+    }+}
src/lib/adom-babylon/util/pageOwner.tsadded+43
@@ -0,0 +1,43 @@+/**+ * Which viewer a page-level input belongs to, when a page holds several: a+ * key pressed outside any viewer, or an event dispatched on window. An event+ * whose target is inside a viewer belongs to that viewer. Any other goes to+ * the viewer the pointer or focus was in last, else to the first one still+ * on the page. With one viewer, every event is its own.+ */++const roots: HTMLElement[] = [];+let last: HTMLElement | null = null;++/**+ * Track a viewer by its root: the element that holds its canvas and its+ * controls. Returns the function that stops tracking it.+ */+export function trackViewerRoot(root: HTMLElement): () => void {+    roots.push(root);+    const mark = () => { last = root; };+    root.addEventListener('pointerdown', mark, true);+    root.addEventListener('pointerenter', mark);+    root.addEventListener('focusin', mark);+    return () => {+        const i = roots.indexOf(root);+        if (i >= 0) roots.splice(i, 1);+        if (last === root && !roots.includes(root)) last = null;+        root.removeEventListener('pointerdown', mark, true);+        root.removeEventListener('pointerenter', mark);+        root.removeEventListener('focusin', mark);+    };+}++/**+ * True when an event with this target belongs to the viewer that `member`+ * (any element inside it) is part of. A member outside every tracked+ * viewer owns every event.+ */+export function ownsPageEvent(member: Element, target: EventTarget | null): boolean {+    if (!roots.some(r => r.contains(member))) return true;+    let owner: HTMLElement | undefined;+    if (target instanceof Node) owner = roots.find(r => r.contains(target));+    if (!owner) owner = last && roots.includes(last) ? last : roots[0];+    return owner.contains(member);+}
src/lib/adom-babylon/util/readiness.ts+3
@@ -20,6 +20,9 @@ export interface ViewerReadyReport {      *  ready (or deliberately absent), no CSP violation was recorded and any      *  requested model loaded with geometry. */     ok: boolean;+    /** True once the viewer is destroyed. A viewer destroyed before its+     *  scene was ready settles whenReady() with this set. */+    destroyed: boolean;     engine: { webglVersion: number; contextLost: boolean };     environment: EnvironmentStatus;     camera: { ready: boolean; mode: 'perspective' | 'orthographic' };
src/lib/babylon-side-effects.ts+3
@@ -10,6 +10,9 @@ import '@babylonjs/core/Layers/layerSceneComponent'; import '@babylonjs/core/Layers/effectLayerSceneComponent'; import '@babylonjs/core/Rendering/utilityLayerRenderer'; import '@babylonjs/core/Rendering/boundingBoxRenderer';+// Makes mesh.renderOverlay and renderOutline draw; without it they are plain+// fields that change nothing on screen.+import '@babylonjs/core/Rendering/outlineRenderer'; import '@babylonjs/core/Materials/Textures/Loaders/envTextureLoader'; import '@babylonjs/core/Culling/ray'; import '@babylonjs/core/Collisions/pickingInfo';
standalone.ts+121−1
@@ -30,6 +30,7 @@ import './src/lib/babylon-side-effects'; // The BABYLON namespace for host pages: the common classes up front, the // whole engine on demand (loadBabylon). See src/lib/babylon-namespace.ts. import { BABYLON_NAMESPACE as BABYLON_CORE, loadBabylon } from './src/lib/babylon-namespace';+import { ownsPageEvent } from './src/lib/adom-babylon/util/pageOwner';  // Babylon.js classes (used directly inside this bundle for laser etch etc.) import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';@@ -40,6 +41,19 @@ import { Color3 } from '@babylonjs/core/Maths/math.color'; import type { Scene } from '@babylonjs/core/scene'; import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; +/** Camera state: alpha and beta in radians, radius, and the target point. */+type CameraState = { alpha: number; beta: number; radius: number; target: [number, number, number] };+/** Named views: Home, fit to the model, or a view cube face. */+type CameraView = 'home' | 'fit' | 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom';+/** A content mesh under the pointer: names from the model root down to it, and the world point hit. x and y are CSS pixels from the canvas's top left. */+type HoverEvent = { mesh: any | null; path: string[]; point: [number, number, number] | null; x: number; y: number };+type PickEvent = HoverEvent & { button: number; shiftKey: boolean; ctrlKey: boolean; altKey: boolean; metaKey: boolean };+type NodeQuery = string | RegExp | ((node: any) => boolean);+type HighlightOptions = { color?: string | [number, number, number]; alpha?: number; mode?: 'overlay' | 'outline' };+type LoadEvent = { url: string | null; root: any; meshes: number };+type LoadErrorEvent = { url: string | null; message: string; code: 'MODEL_LOAD_FAILED' | 'MODEL_LOAD_TIMEOUT' };+type LayerEvent = { name: string; visible: boolean };+ interface ViewerInstance {   /** Load a model and ADD it to the scene (a second call shows both). Same as addModel. */   loadModel: (url: string) => Promise<void>;@@ -99,6 +113,18 @@ interface ViewerInstance {   replayIntros: () => boolean;   /** Cancel every running or pending intro. */   stopIntros: () => void;+  /** Play the model's own animations again from their first frame. */+  replayAnimations: () => boolean;+  /** Where the camera is: alpha and beta in radians, radius, target [x, y, z]. */+  getCameraState: () => CameraState | null;+  /** Move to a named view ('home', 'fit', or a view cube face) or to a state; eases over ms. */+  moveCamera: (to: CameraView | Partial<CameraState>, options?: { ms?: number }) => Promise<CameraState | null>;+  /** Turn around the target: degrees (default 360) over ms (default 4000). */+  orbit: (options?: { degrees?: number; ms?: number }) => Promise<CameraState | null>;+  /** Start a viewer created with `gate`, as its Load button does. */+  openGate: () => Promise<ViewerReadyReport & { version: string }>;+  /** True while a viewer created with `gate` waits to be opened. */+  isGated: () => boolean;   /** Switchable groups the GLB declares (extras.adomRole, or an Adom.<Name>    *  node): Adom.LED.State carries the lens skin AND its light, so switching    *  the group off turns both off. One entry per role, every placement behind@@ -116,6 +142,29 @@ interface ViewerInstance {   setContentLightsEnabled: (on: boolean) => void;   /** Pin the shadow map refresh rate; null restores auto (adom/wiki#60 #7). */   setShadowRefreshRate: (rate: number | null) => void;+  /** 'pick': a click that did not drag (mesh null on empty space). 'hover':+   *  the content mesh under the pointer changed. Returns the remover. */+  on: {+    (type: 'pick', listener: (e: PickEvent) => void): () => void;+    (type: 'hover', listener: (e: HoverEvent) => void): () => void;+    (type: 'load', listener: (e: LoadEvent) => void): () => void;+    (type: 'error', listener: (e: LoadErrorEvent) => void): () => void;+    (type: 'camera', listener: (e: CameraState) => void): () => void;+    (type: 'layer', listener: (e: LayerEvent) => void): () => void;+    (type: 'contextlost' | 'contextrestored', listener: (e: {}) => void): () => void;+  };+  /** Content nodes whose name equals a string, matches a RegExp, or passes a function. */+  findNodes: (query: NodeQuery) => any[];+  /** Light nodes or a findNodes query; latest highlight wins where they overlap. */+  highlight: (target: NodeQuery | any | any[], options?: HighlightOptions) => { meshes: any[]; clear: () => void };+  /** Remove every highlight. */+  clearHighlight: () => void;+  /** Show only these nodes: the rest hidden ('hide') or see-through ('ghost'). One isolation at a time. */+  isolate: (target: NodeQuery | any | any[], options?: { mode?: 'hide' | 'ghost'; alpha?: number }) => { meshes: any[]; clear: () => void };+  /** End the current isolation. */+  clearIsolate: () => void;+  /** Turn the camera to these nodes so they fill the view; null when nothing matches. */+  focus: (target: NodeQuery | any | any[], options?: { ms?: number }) => Promise<CameraState | null>;   /** PNG data URL of the current view (adom/wiki#60 #9). */   captureScreenshot: (options?: { width?: number; height?: number }) => Promise<string>;   destroy: () => void;@@ -154,8 +203,49 @@ function init(container: HTMLElement, options?: {   lightBudget?: number;   /** Play layer intros declared in the GLB (extras.adomLayer.intro); default true. */   intros?: boolean;+  /** false holds every animation group at its first frame after each load (default true). */+  animate?: boolean;+  /** Plays an animation the model starts with this many times, then rests+   *  on its last frame; 0 (default) loops forever. */+  repeat?: number;+  /** Hover labels: 'all' (default), 'authored' (extras.tooltip only) or 'off'. */+  tooltips?: 'all' | 'authored' | 'off';+  /** World axes at startup (default true). */+  axes?: boolean;+  /** Bottom fill light at startup (default false). */+  bottomLight?: boolean;+  /** false turns shadows off and skips the shadow map; getShadowGenerator() then returns null (default true). */+  shadows?: boolean;+  /** The view Home goes to, as setHomeView(). */+  homeView?: { alpha: number; beta: number; radiusScale?: number; target?: [number, number, number] | null } | null;+  /** The first model load opens at Home instead of the starting top-down view (default false). */+  homeOnLoad?: boolean;+  /** A URL model load that has not finished after this many ms fails with a MODEL_LOAD_TIMEOUT hint; 0 (default) waits forever. */+  loadTimeoutMs?: number;+  /** Click to load: show a card and start nothing until the reader presses+   *  Load or the host calls openGate(). bytes and vertices describe the+   *  model on the card; downloadUrl adds a download link and must be an+   *  http(s) or relative URL (init() throws otherwise). */+  gate?: { bytes?: number; vertices?: number; downloadUrl?: string } | null;+  /** The browser took this viewer's WebGL context away; nothing paints until it is back. */+  onContextLost?: () => void;+  /** The context is back and the viewer has rebuilt its GPU state. */+  onContextRestored?: () => void;+  /** 'studio' (default, the gradient), 'transparent' (the page shows+   *  through, and screenshots keep the alpha) or a '#rrggbb' color. */+  background?: string; }): ViewerInstance {   const opts = options || {};+  const background = opts.background ?? 'studio';+  if (background !== 'studio' && background !== 'transparent' && !/^#[0-9a-f]{6}$/i.test(String(background))) {+    throw new Error(`background must be "studio", "transparent" or "#rrggbb", not ${JSON.stringify(background)}`);+  }+  const download = opts.gate?.downloadUrl;+  if (download != null) {+    let ok = false;+    try { ok = typeof download === 'string' && ['http:', 'https:'].includes(new URL(download, 'https://base.invalid/').protocol); } catch { ok = false; }+    if (!ok) throw new Error(`gate.downloadUrl must be an http(s) or relative URL, not ${JSON.stringify(download)}`);+  }    const component = new ThreeDViewer({     target: container,@@ -173,11 +263,24 @@ function init(container: HTMLElement, options?: {       onGroundCreated: opts.onGroundCreated,       lightBudget: opts.lightBudget !== undefined ? opts.lightBudget : 4,       intros: opts.intros !== false,+      animate: opts.animate !== false,+      repeat: Number.isFinite(opts.repeat) && (opts.repeat as number) > 0 ? Math.floor(opts.repeat as number) : 0,+      tooltips: opts.tooltips === 'authored' || opts.tooltips === 'off' ? opts.tooltips : 'all',+      axes: opts.axes !== false,+      bottomLight: opts.bottomLight === true,+      shadows: opts.shadows !== false,+      homeView: opts.homeView || null,+      homeOnLoad: opts.homeOnLoad === true,+      loadTimeoutMs: Number.isFinite(opts.loadTimeoutMs) && (opts.loadTimeoutMs as number) > 0 ? Number(opts.loadTimeoutMs) : 0,+      gate: opts.gate || null,+      background,+      onContextLost: opts.onContextLost,+      onContextRestored: opts.onContextRestored,     },   });    const help = opts.showHelp === false ? null : mountHelp(container);-  if (help) component.whenReady().then(() => help.tipOnce()).catch(() => {});+  if (help) component.whenReady().then((r) => { if (!r.destroyed) help.tipOnce(); }).catch(() => {});    return {     showHelp: () => { help && help.show(); },@@ -212,11 +315,24 @@ function init(container: HTMLElement, options?: {     toggleAxes: (target: 'world' | 'mesh-local', enabled?: boolean) => component.toggleAxes(target, enabled),     getAxesState: () => component.getAxesState(),     setShadowRefreshRate: (rate: number | null) => component.setShadowRefreshRate(rate),+    on: ((type: any, listener: any) => component.on(type, listener)) as ViewerInstance['on'],+    findNodes: (query: NodeQuery) => component.findNodes(query),+    highlight: (target: any, o?: HighlightOptions) => component.highlight(target, o),+    clearHighlight: () => component.clearHighlight(),+    isolate: (target: any, o?: { mode?: 'hide' | 'ghost'; alpha?: number }) => component.isolate(target, o),+    clearIsolate: () => component.clearIsolate(),+    focus: (target: any, o?: { ms?: number }) => component.focus(target, o),     captureScreenshot: (o?: { width?: number; height?: number }) => component.captureScreenshot(o),     getLayers: () => component.getLayers(),     setLayerVisible: (name: string, visible: boolean) => component.setLayerVisible(name, visible),     getIntros: () => component.getIntros(),     replayIntros: () => component.replayIntros(),+    replayAnimations: () => component.replayAnimations(),+    getCameraState: () => component.getCameraState(),+    moveCamera: (to, o) => component.moveCamera(to, o),+    orbit: (o) => component.orbit(o),+    openGate: () => component.openGate().then(withVersion),+    isGated: () => component.isGated(),     stopIntros: () => component.stopIntros(),     getStateGroups: () => component.getStateGroups(),     setStateGroupEnabled: (key: string, enabled: boolean) => component.setStateGroupEnabled(key, enabled),@@ -315,6 +431,8 @@ function mountHelp(container: HTMLElement) {   const onKey = (e: KeyboardEvent) => {     const t = e.target as HTMLElement | null;     if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+    // With several viewers on the page, only the one the key belongs to answers.+    if (!ownsPageEvent(container, e.target)) return;     if (e.key === '?') { toggle(); e.preventDefault(); }     else if (e.key === 'Escape' && !card.hidden) { hide(); e.preventDefault(); }   };@@ -466,4 +584,6 @@ if (!(window as any).BABYLON) {   version: __VIEWER_VERSION__,   BABYLON: BABYLON_CORE,   loadBabylon,+  // The Babylon.js release the viewer is built on; BABYLON and loadBabylon() are this release.+  babylonVersion: (BABYLON_CORE as any).Engine.Version as string, };
test/board-layers.test.mjs+196−12
@@ -3,11 +3,13 @@ import assert from 'node:assert/strict'; import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url';+import { deflateSync } from 'node:zlib'; import puppeteer from 'puppeteer-core'; const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); const DIST=join(ROOT,process.env.VIEWER_DIST || 'dist-standalone'); const fixture=process.env.BOARD_LAYERS_FIXTURE; const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");+let passed=0;const ok=m=>{passed++;console.log('    ok '+m);};  /** A GLB of named cubes; `textured` gives them a textured material, `animated` a translation animation. */ function makeGlb(prefix, names, { textured = false, animated = false } = {}) {@@ -56,6 +58,8 @@ function layerFixture() {  const ext={layout:'dense',texture:{index:0},size:[1,1],baseColorTexels:[1,1],band:2,  colors:{mask:[0.1,0.2,0.1],copperUnderMask:[0.2,0.3,0.1],laminate:[0.1,0.1,0.1],finish:[0.9,0.7,0.2],silk:[1,1,1]},  roughness:{mask:0.5,laminate:0.8,finish:0.3,silk:0.6},metallic:{mask:0,laminate:0,finish:1,silk:0}};+ // A metallic-roughness map as normalized boards have, so both sample replacements compile.+ j.materials[0].pbrMetallicRoughness.metallicRoughnessTexture={index:0};  j.materials[0].name='Adom.Board.Top';j.materials[0].extensions={ADOM_board_layers:ext};  j.materials.push({...j.materials[0],name:'Adom.Board.Bottom'});  j.meshes.push({...j.meshes[0],primitives:[{...j.meshes[0].primitives[0],material:1}]});j.nodes[1].mesh=1;@@ -64,7 +68,61 @@ function layerFixture() {  return Buffer.concat([h,buf,base.subarray(20+n)]); } +// An RGBA8 PNG (no filtering), for the synthetic layer textures.+const CRC=new Uint32Array(256).map((_,n)=>{let c=n;for(let k=0;k<8;k++)c=c&1?0xedb88320^(c>>>1):c>>>1;return c>>>0;});+const crc32=b=>{let c=~0;for(const x of b)c=CRC[(c^x)&255]^(c>>>8);return ~c>>>0;};+function png(w,h,rgba){+ const chunk=(type,data)=>{const len=Buffer.alloc(4),crc=Buffer.alloc(4),td=Buffer.concat([Buffer.from(type),data]);len.writeUInt32BE(data.length);crc.writeUInt32BE(crc32(td));return Buffer.concat([len,td,crc]);};+ const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(w,0);ihdr.writeUInt32BE(h,4);ihdr[8]=8;ihdr[9]=6;+ const raw=Buffer.alloc(h*(1+4*w));for(let y=0;y<h;y++)Buffer.from(rgba.subarray(y*4*w,(y+1)*4*w)).copy(raw,y*(1+4*w)+1);+ return Buffer.concat([Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]),chunk('IHDR',ihdr),chunk('IDAT',deflateSync(raw)),chunk('IEND',Buffer.alloc(0))]);+}++// The sparse layout production boards use on both faces: a 16x16 field in 8x8 tiles, read through a 2x2+// tile map. Three tiles are flat (no edge near them; the map's alpha holds the inside bits): exposed copper+// (finish), bare mask, silk. The fourth points at atlas tile (1, 0), whose copper edge runs down its+// middle: finish on the left, laminate in the mask opening on the right. Atlas tile (0, 0) holds copper+// under mask, a colour no correct read shows. Seen face-on, a quarter of each face is mask and silk, 3/8+// finish, 1/8 laminate. The base colour map is magenta, so a face drawn without the field is obvious.+const SPARSE_COLORS={mask:[0.05,0.1,0.85],copperUnderMask:[0.85,0.8,0.05],laminate:[0.05,0.75,0.1],finish:[0.85,0.08,0.05],silk:[0.95,0.95,0.95]};+function sparseFixture() {+ const T=8,band=4,enc=d=>Math.round((Math.max(-band,Math.min(band,d))/(2*band)+0.5)*255);+ const tiles=new Uint8Array([0,0,0,3, 0,0,0,0, 0,0,0,4, 1,0,0,255]);+ const AW=2*(T+2),AH=T+2,atlas=new Uint8Array(AW*AH*4);+ for(let y=0;y<AH;y++) for(let x=0;x<AW;x++){+  const i=4*(y*AW+x),tile=Math.floor(x/(T+2)),lx=x-tile*(T+2)-1; // lx: the tile-local texel, -1 and T are its ring+  const rgb=tile===0?[enc(band),enc(-band),enc(-band)]:[enc(T/2-(lx+0.5)),enc(band),enc(-band)];+  atlas.set([...rgb,255],i);+ }+ const images=[png(1,1,new Uint8Array([255,0,255,255])),png(AW,AH,atlas),png(2,2,tiles)];+ const s=0.01,h=0.0008;+ const pos=new Float32Array([-s,-s,h, s,-s,h, s,s,h, -s,s,h, -s,-s,-h, s,-s,-h, s,s,-h, -s,s,-h]);+ const nrm=new Float32Array([0,0,1, 0,0,1, 0,0,1, 0,0,1, 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1]);+ const uv=new Float32Array([0,0, 1,0, 1,1, 0,1, 0,0, 1,0, 1,1, 0,1]);+ const top=new Uint16Array([0,1,2, 0,2,3]),bottom=new Uint16Array([4,6,5, 4,7,6]);+ const pad=b=>Buffer.concat([b,Buffer.alloc((4-b.length%4)%4)]);+ const parts=[pos,nrm,uv,top,bottom].map(a=>Buffer.from(a.buffer)).concat(images);+ const views=[];let off=0,bin=Buffer.alloc(0);+ for(const p of parts){views.push({buffer:0,byteOffset:off,byteLength:p.length});const q=pad(p);bin=Buffer.concat([bin,q]);off+=q.length;}+ const ext={layout:'sparse',texture:{index:1},indirection:{index:2},tileSize:T,size:[16,16],baseColorTexels:[1,1],band,colors:SPARSE_COLORS,+  roughness:{mask:0.9,laminate:0.9,finish:0.9,silk:0.9},metallic:{mask:0,laminate:0,finish:0,silk:0}};+ const mat=name=>({name,doubleSided:true,pbrMetallicRoughness:{baseColorTexture:{index:0},metallicRoughnessTexture:{index:0}},extensions:{ADOM_board_layers:ext}});+ const json={asset:{version:'2.0'},scene:0,scenes:[{nodes:[0,1]}],extensionsUsed:['ADOM_board_layers'],+  nodes:[{name:'Board_top',mesh:0},{name:'Board_bottom',mesh:1}],+  meshes:[3,4].map((indices,material)=>({primitives:[{attributes:{POSITION:0,NORMAL:1,TEXCOORD_0:2},indices,material}]})),+  materials:[mat('Adom.Board.Top'),mat('Adom.Board.Bottom')],+  textures:[0,1,2].map(source=>({source})),images:[5,6,7].map(bufferView=>({bufferView,mimeType:'image/png'})),+  buffers:[{byteLength:bin.length}],bufferViews:views,+  accessors:[{bufferView:0,componentType:5126,count:8,type:'VEC3',min:[-s,-s,-h],max:[s,s,h]},{bufferView:1,componentType:5126,count:8,type:'VEC3'},+   {bufferView:2,componentType:5126,count:8,type:'VEC2'},{bufferView:3,componentType:5123,count:6,type:'SCALAR'},{bufferView:4,componentType:5123,count:6,type:'SCALAR'}]};+ let text=Buffer.from(JSON.stringify(json));text=Buffer.concat([text,Buffer.alloc((4-text.length%4)%4,32)]);+ const head=Buffer.alloc(20);head.write('glTF');head.writeUInt32LE(2,4);head.writeUInt32LE(28+text.length+bin.length,8);head.writeUInt32LE(text.length,12);head.write('JSON',16);+ const chunk=Buffer.alloc(8);chunk.writeUInt32LE(bin.length);chunk.write('BIN\0',4);+ return {glb:Buffer.concat([head,text,chunk,bin]),baseBytes:images[0].length};+}+ const glb=fixture?readFileSync(fixture):layerFixture();+const sparse=sparseFixture(); const bytesVariant=(kind)=>{  const n=glb.readUInt32LE(12), d=JSON.parse(glb.subarray(20,20+n));  for(const m of d.materials||[]) if(m.extensions?.ADOM_board_layers) {@@ -75,7 +133,14 @@ const bytesVariant=(kind)=>{  const head=Buffer.from(glb.subarray(0,20));head.writeUInt32LE(20+json.length+glb.length-(20+n),8);head.writeUInt32LE(json.length,12);  return Buffer.concat([head,json,glb.subarray(20+n)]); };-const html=`<html><body style="margin:0"><div id="wrap" style="width:800px;height:600px"></div><script type="module">+// window.__slowDecode (ms) holds back the decode of every image except the sparse fixture's base colour+// map, so a test can catch the layer textures mid-load.+const html=`<html><body style="margin:0"><div id="wrap" style="width:800px;height:600px"></div><div id="wrap2" style="position:absolute;left:0;top:0;width:400px;height:300px"></div><div id="wrap3" style="position:absolute;left:400px;top:0;width:400px;height:300px"></div><script type="module">+const decode=window.createImageBitmap.bind(window);window.__slowDecode=0;+window.createImageBitmap=async(src,...rest)=>{if(window.__slowDecode&&src instanceof Blob&&src.size!==${sparse.baseBytes})await new Promise(r=>setTimeout(r,window.__slowDecode));return decode(src,...rest);};+// Ready, rendered, and still ready after that frame (a frame can start a shader compile, which a loaded+// CI runner makes slow). A scene that never gets there gives up after 60 s and fails the check that follows.+window.__settle=async s=>{const end=performance.now()+60000;do{await Promise.race([s.whenReadyAsync(true),new Promise(r=>setTimeout(r,1000))]);s.render();}while(!s.isReady()&&performance.now()<end);}; await import('/adom-3d-viewer-babylon9.esm.js'); window.v=window.Adom3DViewerBabylon9.init(document.getElementById('wrap'),{zUp:true,showViewCube:false,showGround:false,showHelp:false}); await v.loadModel('/round3.glb');@@ -84,7 +149,7 @@ await v.whenReady();window.ready=true; const server=http.createServer((req,res)=>{  const p=new URL(req.url,'http://x').pathname;  if(p==='/') { res.setHeader('Content-Type','text/html');return res.end(html); }- if(p.endsWith('.glb')) {res.setHeader('Content-Type','model/gltf-binary');return res.end(p==='/round3.glb'?glb:bytesVariant(p.includes('invalid')?'invalid':'legacy'));}+ if(p.endsWith('.glb')) {res.setHeader('Content-Type','model/gltf-binary');return res.end(p==='/round3.glb'?glb:p==='/sparse.glb'?sparse.glb:bytesVariant(p.includes('invalid')?'invalid':'legacy'));}  const f=resolve(DIST,'.'+p);  if(f.startsWith(DIST+'/')&&existsSync(f)) {res.setHeader('Content-Type',f.endsWith('.js')?'text/javascript':'application/octet-stream');return res.end(readFileSync(f));}  res.writeHead(404);res.end();@@ -103,26 +168,145 @@ try {  const errors=[];page.on('pageerror',e=>errors.push(String(e)));  await page.goto('http://127.0.0.1:'+server.address().port+'/');await page.waitForFunction('window.ready===true',{timeout:90000});  const immediate=await page.evaluate(()=>v.getScene().materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length);- assert.equal(immediate,2,'loading immediately after init keeps both board shaders');+ assert.equal(immediate,2,'loading immediately after init keeps both board shaders');ok('a load right after init gets both board shaders');  const load=async url=>{-  await page.evaluate(async u=>{await v.replaceModel(u);await Promise.race([v.getScene().whenReadyAsync(),new Promise((_,reject)=>setTimeout(()=>reject(new Error('scene readiness timed out')),60000))]);v.getScene().render();},url);+  await page.evaluate(async u=>{await v.replaceModel(u);await __settle(v.getScene());},url);   return page.evaluate(()=>{    const s=v.getScene(); const ps=s.materials.map(m=>m.pluginManager?.getPlugin('AdomBoardLayers')).filter(Boolean);    return {plugins:ps.length,active:ps.filter(p=>p.on).length,ready:s.isReady(),textures:s.textures.length,layerTextures:s.textures.filter(t=>t.name?.includes('.layers')).length,compiled:s.meshes.filter(m=>m.material?.pluginManager?.getPlugin('AdomBoardLayers')).every(m=>m.subMeshes?.every(sm=>sm.effect?.isReady()))};   });  };- const first=await load('/round3.glb');assert.equal(first.plugins,2);assert.equal(first.active,2);assert.equal(first.compiled,true);assert.equal(first.ready,true);- for(let i=0;i<3;i++){const next=await load('/round3.glb');assert.equal(next.textures,first.textures);assert.equal(next.layerTextures,first.layerTextures);}- const legacy=await load('/legacy.glb');assert.equal(legacy.plugins,0);assert.equal(legacy.layerTextures,0);assert.equal(legacy.ready,true);- const invalid=await load('/invalid.glb');assert.equal(invalid.active,0);assert.equal(invalid.layerTextures,0);assert.equal(invalid.ready,true);+ // The compiled board effects: whether the sparse path is in, and whether the PBR shader's base colour and+ // metallic-roughness samples were replaced. The replacements match Babylon's shader text by regular+ // expression, so a Babylon update that rewrites those lines drops them without an error.+ const effects=()=>page.evaluate(()=>v.getScene().meshes.filter(m=>m.material?.pluginManager?.getPlugin('AdomBoardLayers')?.on).flatMap(m=>m.subMeshes.map(sm=>{+  const fs=sm.effect?.fragmentSourceCode||'';+  return {sparse:/#define ADOMSPARSE\b/.test(sm.effect?.defines||''),albedo:fs.includes('if (adomW < 1.0) albedoTexture='),mr:fs.includes('if (adomW < 1.0) surfaceMetallicOrReflectivityColorMap='),eval:fs.includes('adomLayersEval(vAlbedoUV)')};+ })));+ const first=await load('/round3.glb');assert.equal(first.plugins,2);assert.equal(first.active,2);assert.equal(first.compiled,true);assert.equal(first.ready,true);ok('dense: both shaders compile and the scene is ready');+ const dense=await effects();assert.ok(dense.length>=2);+ for(const e of dense) assert.deepEqual(e,{sparse:false,albedo:true,mr:true,eval:true},'dense effect carries the field and both sample replacements');+ ok('dense: the compiled fragment source has the field and both sample replacements');+ for(let i=0;i<3;i++){const next=await load('/round3.glb');assert.equal(next.textures,first.textures);assert.equal(next.layerTextures,first.layerTextures);}ok('replacing the model three times releases its layer textures');+ const legacy=await load('/legacy.glb');assert.equal(legacy.plugins,0);assert.equal(legacy.layerTextures,0);assert.equal(legacy.ready,true);ok('a GLB without the extension keeps its textures');+ const invalid=await load('/invalid.glb');assert.equal(invalid.active,0);assert.equal(invalid.layerTextures,0);assert.equal(invalid.ready,true);ok('invalid extension data falls back');++ const sparseLoad=await load('/sparse.glb');assert.equal(sparseLoad.plugins,2);assert.equal(sparseLoad.active,2);assert.equal(sparseLoad.layerTextures,4);assert.equal(sparseLoad.compiled,true);assert.equal(sparseLoad.ready,true);+ ok('sparse: both faces get the shader with their atlas and tile map, and it compiles');+ const sparseFx=await effects();assert.ok(sparseFx.length>=2);+ for(const e of sparseFx) assert.deepEqual(e,{sparse:true,albedo:true,mr:true,eval:true},'sparse effect is the ADOMSPARSE variant with both sample replacements');+ ok('sparse: the compiled fragment source is the ADOMSPARSE variant with both sample replacements');+ // Face-on from above, black background, no axes: count pixels by colour.+ const colours=await page.evaluate(async()=>{+  v.toggleAxes('world',false);v.getScene().clearColor.set(0,0,0,1);+  await v.moveCamera('top',{ms:0});v.frameModel(0.8);+  const s=v.getScene();await __settle(s);s.render();+  const src=v.getEngine().getRenderingCanvas(),c=document.createElement('canvas');c.width=src.width;c.height=src.height;+  const g=c.getContext('2d');g.drawImage(src,0,0);const d=g.getImageData(0,0,c.width,c.height).data;+  const n={finish:0,mask:0,silk:0,laminate:0,copperUnderMask:0,base:0};+  for(let i=0;i<d.length;i+=4){+   const r=d[i],gr=d[i+1],b=d[i+2],hi=Math.max(r,gr,b),lo=Math.min(r,gr,b);+   if(hi<40) continue;+   if(hi-lo<40&&lo>90) n.silk++;+   else if(r>gr+60&&b>gr+60) n.base++;+   else if(r>gr+60&&r>b+60) n.finish++;+   else if(gr>r+60&&gr>b+60) n.laminate++;+   else if(b>r+60&&b>gr+60) n.mask++;+   else if(r>b+60&&gr>b+60) n.copperUnderMask++;+  }+  return n;+ });+ console.log('    sparse face pixels: '+JSON.stringify(colours));+ const near=(x,want,tol)=>Math.abs(x-want)<=tol*want;+ const q=colours.mask;+ assert.ok(q>2000,'the mask quarter is on screen');+ assert.ok(near(colours.silk/q,1,0.25),'silk covers a quarter, as the mask does');+ assert.ok(near(colours.finish/q,1.5,0.25),'finish covers 3/8: one flat tile and half the atlas tile');+ assert.ok(near(colours.laminate/q,0.5,0.3),'laminate covers 1/8: the other half of the atlas tile');+ assert.ok(colours.copperUnderMask<q*0.02,'nothing reads atlas tile (0, 0)');+ assert.ok(colours.base<q*0.02,'no pixel shows the base colour map');+ ok('sparse: face-on, the tile map and atlas paint mask, silk, finish and laminate in the right shares');++ // Two viewers at once, each with its own scene: the loader hook is global, the materials are not.+ const two=await page.evaluate(async()=>{+  const V=window.Adom3DViewerBabylon9,opts={zUp:true,showViewCube:false,showGround:false,showHelp:false};+  const a=V.init(document.getElementById('wrap2'),opts),b=V.init(document.getElementById('wrap3'),opts);+  await Promise.all([a.loadModel('/sparse.glb'),b.loadModel('/round3.glb')]);+  await Promise.all([a.whenReady(),b.whenReady()]);+  const look=x=>{const s=x.getScene(),ps=s.materials.map(m=>m.pluginManager?.getPlugin('AdomBoardLayers')).filter(p=>p?.on);+   return {on:ps.length,own:ps.every(p=>p._tex.getScene()===s&&(!p._tiles||p._tiles.getScene()===s)),layerTextures:s.textures.filter(t=>t.name?.includes('.layers')).length};};+  const before={a:look(a),b:look(b)};+  const bTextures=b.getScene().textures.filter(t=>t.name?.includes('.layers'));+  a.destroy();+  await new Promise(r=>setTimeout(r,1000));+  const s=b.getScene();await __settle(s);+  const after={b:look(b),kept:bTextures.every(t=>s.textures.includes(t)&&t.getInternalTexture()&&t.isReady()),ready:s.isReady()};+  b.destroy();+  return {before,after};+ });+ assert.deepEqual(two.before,{a:{on:2,own:true,layerTextures:4},b:{on:2,own:true,layerTextures:2}},'two viewers each get their own board shaders and textures');+ assert.deepEqual(two.after,{b:{on:2,own:true,layerTextures:2},kept:true,ready:true},'destroying one leaves the other its shaders and textures');+ ok('two viewers: each has its own board materials; destroying one leaves the other drawing');++ // Click to load: a load asked for behind a closed gate waits for the viewer, then gets the shader.+ const gated=await page.evaluate(async()=>{+  const g=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false,gate:{bytes:1}});+  let loaded=false;const loading=g.loadModel('/round3.glb').then(()=>{loaded=true;});+  await new Promise(r=>setTimeout(r,300));+  const waiting={gated:g.isGated(),scene:!!g.getScene(),loaded};+  await g.openGate();await loading;+  const on=g.getScene().materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length;+  g.destroy();+  return {waiting,on};+ });+ assert.deepEqual(gated,{waiting:{gated:true,scene:false,loaded:false},on:2},'a load behind the gate waits, then gets both board shaders');+ ok('gate: a load asked for before openGate() gets both board shaders');++ // destroy() with layer textures still loading: the load settles, the scene is released, and nothing+ // throws, whether the destroy comes while the field images decode or 0 to 400 ms after a board load,+ // while its shaders may still compile.+ const beforeDestroy=errors.length;+ const midDecode=await page.evaluate(async()=>{+  const d=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false});+  await d.whenReady();+  window.__slowDecode=1500;+  let settled=null;d.loadModel('/sparse.glb').then(()=>{settled='resolved';},e=>{settled='rejected: '+e.message;});+  const s=d.getScene(),t0=performance.now();+  let caught=false;+  while(performance.now()-t0<5000){+   if(s.textures.some(t=>t.name?.includes('.layers')&&!t.isReady())){caught=true;break;}+   await new Promise(r=>setTimeout(r,5));+  }+  d.destroy();+  const t1=performance.now();+  while(!s.isDisposed&&performance.now()-t1<20000) await new Promise(r=>setTimeout(r,50));+  await new Promise(r=>setTimeout(r,2000));+  window.__slowDecode=0;+  return {caught,settled,disposed:s.isDisposed};+ });+ assert.deepEqual(midDecode,{caught:true,settled:'resolved',disposed:true},'a destroy while the field images decode settles the load and releases the scene');+ await page.evaluate(async()=>{+  for(const ms of [0,20,50,100,200,400]){+   const d=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false});+   await d.whenReady();+   await d.loadModel('/sparse.glb');+   await new Promise(r=>setTimeout(r,ms));+   d.destroy();+  }+  await new Promise(r=>setTimeout(r,2500));+ });+ assert.deepEqual(errors.slice(beforeDestroy),[],'no page errors from destroys during layer texture loads');+ ok('destroy: while the field images decode and 0 to 400 ms after a board load, the load settles, the scene is released and nothing throws');+  await load('/round3.glb');  const fallback=await page.evaluate(async()=>{   const s=v.getScene(),m=s.materials.find(m=>m.pluginManager?.getPlugin('AdomBoardLayers'));   let removed=false;m.onError({isReady:()=>false,dispose:()=>{removed=true;}},'deliberate regression-test compile failure');-  await new Promise(r=>setTimeout(r,25));await s.whenReadyAsync();s.render();+  await new Promise(r=>setTimeout(r,25));await __settle(s);   return {removed,ready:s.isReady(),active:s.materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length};  });- assert.deepEqual(fallback,{removed:true,ready:true,active:0});assert.deepEqual(errors,[]);- console.log('Round 3: both shaders compiled; replacement releases textures; legacy, invalid-data and shader-error fallbacks pass.');- console.log(JSON.stringify({first,legacy,invalid,fallback}));+ assert.deepEqual(fallback,{removed:true,ready:true,active:0});assert.deepEqual(errors,[]);ok('a shader that does not compile drops every board material back to its textures');+ console.log('Round 3: dense and sparse shaders compiled with both sample replacements; replacement releases textures; two viewers, the gate, destroy during loads, and the legacy, invalid-data and shader-error fallbacks pass.');+ console.log(JSON.stringify({first,legacy,invalid,sparse:sparseLoad,colours,fallback}));+ console.log(`${passed} passed, 0 failed`); } finally {await browser.close();server.close();}
test/camera.test.mjsadded+229
@@ -0,0 +1,229 @@+// Camera control a host drives: getCameraState(), moveCamera() to a named view+// or a state, orbit(), and the loadTimeoutMs option. Named face views put the+// camera on that side of the model in both Z-up and Y-up scenes; moves ease+// the short way round, end where asked even without animation frames, and a+// new move cancels the one in flight. A URL load past its timeout fails with+// MODEL_LOAD_TIMEOUT and does not show up later.+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }+const near = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;++/** A GLB of one 2 cm cube named `<prefix>_cube`. */+function makeGlb(prefix) {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));+  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+  const bin = Buffer.concat([posBuf, idxBuf]);+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0] }],+    nodes: [{ name: `${prefix}_cube`, mesh: 0 }],+    meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],+    materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],+    buffers: [{ byteLength: bin.length }],+    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const CUBE = makeGlb("Part");+const LATE = makeGlb("Late");+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  // A fresh viewer in #wrap with these options; the previous one is destroyed.+  window.__make = async (opts) => {+    if (window.__v) window.__v.destroy();+    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showHelp: false, ...opts });+    await window.__v.whenReady();+  };+  // Camera position relative to its target, in units of the radius.+  window.__side = () => { const c = window.__v.getCamera(); c.getViewMatrix(true); const p = c.position, t = c.target; return [(p.x - t.x) / c.radius, (p.y - t.y) / c.radius, (p.z - t.z) / c.radius]; };+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (url.pathname === "/cube.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(CUBE); }+  // Answers after 1.5 s: slower than the 500 ms timeout the test sets.+  if (url.pathname === "/late.glb") { setTimeout(() => { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); res.end(LATE); }, 1500); return; }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);++  // Which way each named view looks from, in a Z-up and a Y-up scene.+  const SIDES = {+    true: { front: [1, -1], back: [1, 1], right: [0, 1], left: [0, -1], top: [2, 1], bottom: [2, -1] },+    false: { top: [1, 1], bottom: [1, -1] },+  };+  for (const zUp of [true, false]) {+    section(`named views put the camera on that side (zUp ${zUp})`);+    await run((z) => window.__make({ zUp: z }), zUp);+    await run(async () => { await window.__v.loadModel("/cube.glb"); });+    for (const [view, [axis, sign]] of Object.entries(SIDES[zUp])) {+      const st = await run(async (v) => { const s = await window.__v.moveCamera(v); return { s, side: window.__side() }; }, view);+      assert(st.side[axis] * sign > 0.99, `${view}: the camera sits on the ${sign > 0 ? "+" : "-"}${"XYZ"[axis]} side of its target (${st.side.map(v => v.toFixed(3)).join(", ")})`);+    }+  }++  section("state, easing, the short way round");+  await run(() => window.__make({}));+  await run(async () => { await window.__v.loadModel("/cube.glb"); });+  const st0 = await run(() => window.__v.getCameraState());+  assert(st0 && ["alpha", "beta", "radius"].every(k => Number.isFinite(st0[k])) && st0.target.length === 3, `getCameraState() reports alpha, beta, radius and target (${JSON.stringify(st0)})`);+  // Halfway is read by driving one animation frame by hand with the clock+  // set to the middle of the move: under software GL a frame takes so long+  // that a real timer would only fire after the move is over.+  const eased = await run(async () => {+    const v = window.__v;+    await v.moveCamera({ alpha: 0.1, beta: 1 });+    const realNow = performance.now, realRaf = window.requestAnimationFrame;+    let now = realNow.call(performance), mid;+    const frames = [];+    performance.now = () => now;+    window.requestAnimationFrame = (cb) => { frames.push(cb); return frames.length; };+    let p;+    try {+      p = v.moveCamera({ alpha: 2 * Math.PI - 0.1, radius: v.getCameraState().radius * 2 }, { ms: 600 });+      now += 300;+      frames.shift()(now);+      mid = v.getCameraState();+    } finally {+      performance.now = realNow;+      window.requestAnimationFrame = realRaf;+    }+    const end = await p;+    return { mid, end };+  });+  assert(near(eased.mid.alpha, 0), `a move from alpha 0.1 to 2pi - 0.1 is at 0 halfway, not round the long way (mid ${eased.mid.alpha.toFixed(4)})`);+  assert(near(Math.cos(eased.end.alpha), Math.cos(-0.1)) && near(Math.sin(eased.end.alpha), Math.sin(-0.1)), `it ends at the asked angle (${eased.end.alpha.toFixed(4)})`);+  assert(eased.mid.radius > st0.radius && eased.mid.radius < eased.end.radius, "the radius is in between halfway through");+  const target = await run(async () => (await window.__v.moveCamera({ target: [0.01, 0.02, 0.03] })).target);+  assert(target.every((v, i) => near(v, [0.01, 0.02, 0.03][i])), "moveCamera() sets the target");++  section("home, fit and orbit");+  const homes = await run(async () => {+    const v = window.__v;+    await v.moveCamera({ alpha: 0.3, beta: 1.2 });+    const viaMove = await v.moveCamera("home", { ms: 200 });+    await v.moveCamera({ alpha: 0.3, beta: 1.2 });+    v.goHome();+    return { viaMove, viaGoHome: v.getCameraState() };+  });+  assert(["alpha", "beta", "radius"].every(k => near(homes.viaMove[k], homes.viaGoHome[k], 1e-6)), "moveCamera('home') ends where goHome() does");+  const fit = await run(async () => {+    const v = window.__v;+    await v.moveCamera({ radius: 5 });+    const before = v.getCameraState();+    const p = v.moveCamera("fit", { ms: 200 });+    const during = v.getCameraState();+    const end = await p;+    return { before, during, end };+  });+  assert(near(fit.during.radius, fit.before.radius, 1e-6), "a 'fit' move does not jump the camera before it starts");+  assert(fit.end.radius < 1, `'fit' brings a far camera back to the model (radius ${fit.end.radius.toFixed(4)})`);+  const unclamped = await run(async () => {+    const v = window.__v, c = v.getCamera();+    const frames = (n) => new Promise(r => { const f = () => (--n > 0 ? requestAnimationFrame(f) : r()); requestAnimationFrame(f); });+    c.upperRadiusLimit = null;+    await v.moveCamera({ radius: 5 });+    await frames(2);+    const start = c.radius;+    const p = v.moveCamera("fit", { ms: 3000 });+    await frames(2);+    const early = c.radius;+    await p;+    return { start, early, end: c.radius, upper: c.upperRadiusLimit };+  });+  assert(unclamped.start > 4.9 && unclamped.early > unclamped.start * 0.8, `a 'fit' move eases from a view its own limits would clamp, without a jump (radius ${unclamped.start.toFixed(3)} -> ${unclamped.early.toFixed(3)})`);+  assert(Number.isFinite(unclamped.upper) && unclamped.end <= unclamped.upper, `and sets fit's limits when it lands (radius ${unclamped.end.toFixed(4)}, limit ${unclamped.upper})`);+  const orb = await run(async () => { const v = window.__v; const a = v.getCameraState().alpha; const s = await v.orbit({ degrees: 90, ms: 300 }); return s.alpha - a; });+  assert(near(orb, Math.PI / 2), `orbit({ degrees: 90 }) turns a quarter round (${orb.toFixed(4)})`);++  section("moves end where asked without animation frames, and the latest move wins");+  const noFrames = await run(async () => {+    const v = window.__v, raf = window.requestAnimationFrame;+    window.requestAnimationFrame = () => 0;+    try { return await v.moveCamera({ alpha: 1.234 }, { ms: 200 }); } finally { window.requestAnimationFrame = raf; }+  });+  assert(near(noFrames.alpha, 1.234), "with no animation frames, the move still ends at its goal on its timer");+  const latest = await run(async () => {+    const v = window.__v;+    const slow = v.moveCamera({ alpha: 2 }, { ms: 1000 });+    await new Promise(r => setTimeout(r, 100));+    const fast = await v.moveCamera({ alpha: -1 });+    await slow;+    await new Promise(r => setTimeout(r, 1300));+    return { fast: fast.alpha, after: v.getCameraState().alpha };+  });+  assert(near(latest.fast, -1) && near(latest.after, -1), `a new move cancels the one in flight (camera stays at ${latest.after.toFixed(4)})`);+  const bad = await run(async () => { try { await window.__v.moveCamera("sideways"); return "resolved"; } catch (e) { return String(e.message); } });+  assert(/unknown view/.test(bad), `an unknown view name rejects (${bad})`);++  section("loadTimeoutMs");+  await run(() => window.__make({ loadTimeoutMs: 500 }));+  const timedOut = await run(async () => {+    const t0 = performance.now();+    try { await window.__v.loadModel("/late.glb"); return { ok: true }; }+    catch (e) { return { ok: false, ms: performance.now() - t0, msg: String(e.message) }; }+  });+  assert(!timedOut.ok && timedOut.ms < 1200, `a load slower than loadTimeoutMs rejects at the timeout (${Math.round(timedOut.ms || 0)} ms: ${timedOut.msg})`);+  const hint = await run(() => window.__v.getReadyReport().hints.map(h => h.code));+  assert(hint.includes("MODEL_LOAD_TIMEOUT") && !hint.includes("MODEL_LOAD_FAILED"), `the ready report says MODEL_LOAD_TIMEOUT (${hint.join(", ")})`);+  await new Promise(r => setTimeout(r, 2500));+  const lateMeshes = await run(() => window.__v.getScene().meshes.filter(m => /^Late_/.test(m.name)).length);+  assert(lateMeshes === 0, "the model that arrives after its timeout is not left in the scene");+  const recovered = await run(async () => { await window.__v.loadModel("/cube.glb"); return window.__v.getReadyReport().hints.map(h => h.code); });+  assert(!recovered.includes("MODEL_LOAD_TIMEOUT"), "a later successful load clears the hint");+  await run(() => window.__make({}));+  const noLimit = await run(async () => { await window.__v.loadModel("/late.glb"); return window.__v.getScene().meshes.filter(m => /^Late_/.test(m.name)).length; });+  assert(noLimit > 0, "without loadTimeoutMs the slow load still finishes");++  assert(pageErrors.length === 0, `no page errors (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/extend.test.mjsadded+369
@@ -0,0 +1,369 @@+// The host-facing extension surface: lifecycle events through on() (load,+// error, camera, layer, contextlost, contextrestored), isolate() and+// focus(), the background option, picks that skip disabled meshes, and the+// loadBabylon() contract (the viewer's own Babylon module, babylonVersion).+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }+const near = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;++/**+ * A GLB of 1 cm grey boxes along X, sharing one material: U1 (holding mesh+ * U1_body) at 0, pad_7 at +2.5 cm, pad_17 at -2.5 cm, and two board layers+ * by the built-in vocabulary, fr4_board at +5 cm and silk_top at -5 cm.+ */+function makeGlb() {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.005, v[1] * 0.005, v[2] * 0.005); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));+  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+  const bin = Buffer.concat([posBuf, idxBuf]);+  const prim = { attributes: { POSITION: 0 }, indices: 1, material: 0 };+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0, 2, 3, 4, 5] }],+    nodes: [+      { name: "U1", children: [1] },+      { name: "U1_body", mesh: 0 },+      { name: "pad_7", mesh: 1, translation: [0.025, 0, 0] },+      { name: "pad_17", mesh: 2, translation: [-0.025, 0, 0] },+      { name: "fr4_board", mesh: 3, translation: [0.05, 0, 0] },+      { name: "silk_top", mesh: 4, translation: [-0.05, 0, 0] },+    ],+    meshes: [0, 1, 2, 3, 4].map(i => ({ name: "m" + i, primitives: [prim] })),+    materials: [{ name: "grey", pbrMetallicRoughness: { baseColorFactor: [0.5, 0.5, 0.5, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: [0.5, 0.5, 0.5] }],+    buffers: [{ byteLength: bin.length }],+    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.005, -0.005, -0.005], max: [0.005, 0.005, 0.005] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const PARTS = makeGlb();+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  // A fresh viewer in #wrap with these options and the parts model; the previous one is destroyed.+  window.__make = async (opts, model = true) => {+    if (window.__v) window.__v.destroy();+    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showHelp: false, ...opts });+    await window.__v.whenReady();+    if (model) { await window.__v.loadModel('/parts.glb'); window.__v.frameModel(); }+  };+  window.__mesh = (name) => window.__v.getScene().getMeshByName(name);+  // A page point over the middle of the named mesh, found by picking a grid+  // in CSS pixels (scene.pick's unit at any pixel density).+  window.__at = (name) => {+    const s = window.__v.getScene(), c = window.__v.getEngine().getRenderingCanvas();+    const hits = [];+    for (let y = 4; y < c.clientHeight; y += 4) for (let x = 4; x < c.clientWidth; x += 4) {+      const p = s.pick(x, y, m => m.isPickable && m.isVisible);+      if (p.hit && p.pickedMesh && p.pickedMesh.name === name) hits.push([x, y]);+    }+    if (!hits.length) return null;+    const cx = hits.reduce((a, h) => a + h[0], 0) / hits.length, cy = hits.reduce((a, h) => a + h[1], 0) / hits.length;+    hits.sort((a, b) => Math.hypot(a[0] - cx, a[1] - cy) - Math.hypot(b[0] - cx, b[1] - cy));+    const r = c.getBoundingClientRect();+    return { x: r.left + hits[0][0], y: r.top + hits[0][1] };+  };+  // RGBA of one canvas pixel, or of one pixel of a PNG data URL.+  window.__pixel = (x, y) => {+    const src = window.__v.getEngine().getRenderingCanvas();+    const c = document.createElement('canvas'); c.width = src.width; c.height = src.height;+    const g = c.getContext('2d'); g.drawImage(src, 0, 0);+    return [...g.getImageData(x, y, 1, 1).data];+  };+  window.__pngPixel = (url, x, y) => new Promise((res) => {+    const img = new Image();+    img.onload = () => { const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; const g = c.getContext('2d'); g.drawImage(img, 0, 0); res([...g.getImageData(x, y, 1, 1).data]); };+    img.src = url;+  });+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (url.pathname === "/parts.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(PARTS); }+  // Answers after 1 s: slower than the 300 ms timeout the test sets.+  if (url.pathname === "/late.glb") { setTimeout(() => { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); res.end(PARTS); }, 1000); return; }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  if (url.pathname === "/favicon.ico") { res.writeHead(204); return res.end(); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);+  const waitFor = (cond, timeout = 30000) => page.waitForFunction(cond, { timeout, polling: 100 }).then(() => true, () => false);+  const pause = (ms) => new Promise(r => setTimeout(r, ms));++  section("load and error events");+  const loads = await run(async () => {+    await window.__make({}, false);+    const v = window.__v, seen = [];+    const off = v.on("load", (e) => seen.push({ url: e.url, root: e.root && e.root.name, meshes: e.meshes }));+    const errs = [];+    v.on("error", (e) => errs.push(e));+    await v.loadModel("/parts.glb");+    const bytes = new Uint8Array(await (await fetch("/parts.glb")).arrayBuffer());+    await v.loadModelBytes(bytes);+    await v.replaceModel("/parts.glb");+    let rejected = false;+    try { await v.loadModel("/missing.glb"); } catch { rejected = true; }+    off();+    await v.loadModel("/parts.glb");+    return { seen, errs, rejected };+  });+  assert(loads.seen.length === 3, `a load event per load, replace and bytes load, none after removal (${loads.seen.length})`);+  assert(loads.seen[0] && loads.seen[0].url === "/parts.glb" && loads.seen[0].root === "__root__" && loads.seen[0].meshes >= 6, `the event names the URL and the root (${JSON.stringify(loads.seen[0])})`);+  assert(loads.seen[1] && loads.seen[1].url === null, "a bytes load reports url null");+  assert(loads.rejected && loads.errs.length === 1 && loads.errs[0].url === "/missing.glb" && loads.errs[0].code === "MODEL_LOAD_FAILED" && typeof loads.errs[0].message === "string",+    `a failed load rejects and fires error (${JSON.stringify(loads.errs[0])})`);+  const late = await run(async () => {+    await window.__make({ loadTimeoutMs: 300 }, false);+    const errs = [];+    window.__v.on("error", (e) => errs.push(e.code));+    try { await window.__v.loadModel("/late.glb"); } catch { /* expected */ }+    return errs;+  });+  assert(JSON.stringify(late) === '["MODEL_LOAD_TIMEOUT"]', `a timed-out load fires error with MODEL_LOAD_TIMEOUT (${late})`);++  section("camera and layer events");+  const cam = await run(async () => {+    await window.__make({});+    const v = window.__v, s = v.getScene();+    const states = [];+    let frames = 0;+    const ob = s.onAfterRenderObservable.add(() => frames++);+    v.on("camera", (st) => states.push(st));+    const end = await v.moveCamera("front", { ms: 400 });+    await new Promise(r => setTimeout(r, 300));+    s.onAfterRenderObservable.remove(ob);+    const n = states.length;+    await new Promise(r => setTimeout(r, 400));+    return { n, quiet: states.length === n, frames, last: states[states.length - 1], end };+  });+  assert(cam.n >= 2 && cam.n <= cam.frames + 1, `a camera move fires camera events, no more than one per frame (${cam.n} events, ${cam.frames} frames)`);+  assert(cam.last && near(cam.last.alpha, cam.end.alpha) && near(cam.last.beta, cam.end.beta) && near(cam.last.radius, cam.end.radius), "the last camera event is where the move ended");+  assert(cam.quiet, "a still camera fires nothing");+  const lay = await run(() => {+    const v = window.__v, names = v.getLayers().map(l => l.name);+    const seen = [];+    v.on("layer", (e) => seen.push(e));+    v.setLayerVisible(names[0], false);+    v.setLayerVisible(names[0], false);+    v.setLayerVisible(names[0], true);+    return { names, seen };+  });+  assert(lay.names.length >= 2, `the model has layers (${lay.names})`);+  assert(lay.seen.length === 2 && lay.seen[0].name === lay.names[0] && lay.seen[0].visible === false && lay.seen[1].visible === true, `layer fires on each change and not when nothing changes (${JSON.stringify(lay.seen)})`);+  const bad = await run(() => { try { window.__v.on("click", () => {}); return null; } catch (e) { return e.message; } });+  assert(!!bad && /pick/.test(bad) && /camera/.test(bad), `an unknown event throws and lists the known ones (${bad})`);++  section("contextlost and contextrestored events");+  const ctxEvents = await run(async () => {+    const v = window.__v, seen = [];+    v.on("contextlost", () => seen.push("lost"));+    v.on("contextrestored", () => seen.push("restored"));+    const c = v.getEngine().getRenderingCanvas();+    const ext = (c.getContext("webgl2") || c.getContext("webgl")).getExtension("WEBGL_lose_context");+    if (!ext) return null;+    ext.loseContext();+    for (let i = 0; i < 100 && !seen.includes("lost"); i++) await new Promise(r => setTimeout(r, 100));+    ext.restoreContext();+    for (let i = 0; i < 300 && !seen.includes("restored"); i++) await new Promise(r => setTimeout(r, 100));+    return seen;+  });+  assert(JSON.stringify(ctxEvents) === '["lost","restored"]', `on() hears the context go and come back (${ctxEvents})`);++  section("isolate");+  await run(() => window.__make({}));+  // The whole model's framing, for comparison once part of it is isolated.+  await run(() => {+    const v = window.__v, c = v.getCamera();+    v.frameModel();+    const s = v.getScene().getLightByName("spotLight").position;+    window.__whole = { r: c.radius, upper: c.upperRadiusLimit, spot: [s.x, s.y, s.z] };+  });+  const BODY = await run(() => window.__at("U1_body"));+  const P17 = await run(() => window.__at("pad_17"));+  assert(!!BODY && !!P17, "U1_body and pad_17 are on screen");+  const iso = await run(() => {+    const v = window.__v, m = window.__mesh;+    const casters = () => v.getShadowGenerator().getShadowMap().renderList;+    const wasCaster = casters().includes(m("U1_body"));+    window.__iso = v.isolate("pad_7");+    return {+      kept: window.__iso.meshes.map(x => x.name),+      body: [m("U1_body").visibility, m("U1_body").isPickable, casters().includes(m("U1_body"))],+      pad7: [m("pad_7").visibility, m("pad_7").isPickable],+      wasCaster,+    };+  });+  assert(JSON.stringify(iso.kept) === '["pad_7"]', `isolate returns the meshes kept (${iso.kept})`);+  assert(JSON.stringify(iso.body) === "[0,false,false]" && iso.wasCaster, `the rest is hidden, takes no picks and casts no shadow (${iso.body})`);+  assert(JSON.stringify(iso.pad7) === "[1,true]", "the target is untouched");+  await run(() => { window.__picks = []; window.__v.on("pick", (e) => window.__picks.push(e.mesh ? e.mesh.name : null)); });+  await page.mouse.click(BODY.x, BODY.y);+  await waitFor("window.__picks.length >= 1", 5000);+  assert(await run(() => window.__picks[0]) !== "U1_body", `a click where a hidden mesh sits does not pick it (${await run(() => window.__picks[0])})`);+  const framed = await run(() => {+    const v = window.__v, m = window.__mesh, c = v.getCamera();+    const caster = () => v.getShadowGenerator().getShadowMap().renderList.includes(m("U1_body"));+    const spot = () => { const p = v.getScene().getLightByName("spotLight").position; return [p.x, p.y, p.z]; };+    const box = m("pad_7").getBoundingInfo().boundingBox;+    const onPad = () => ["x", "y", "z"].every(k => c.target[k] >= box.minimumWorld[k] - 1e-6 && c.target[k] <= box.maximumWorld[k] + 1e-6);+    v.goHome();+    const home = { caster: caster(), onPad: onPad(), r: c.radius, upper: c.upperRadiusLimit, spot: spot() };+    v.frameModel();+    const fit = { caster: caster(), onPad: onPad(), r: c.radius, spot: spot() };+    return { home, fit, whole: window.__whole };+  });+  const sameSpot = (a, b) => a.every((x, i) => Math.abs(x - b[i]) < 1e-6 * Math.max(1, Math.abs(b[i])));+  assert(!framed.home.caster && !framed.fit.caster, "Home and Fit leave the hidden meshes out of the shadow casters");+  assert(framed.home.onPad && framed.fit.onPad && framed.fit.r < framed.whole.r * 0.5,+    `Home and Fit frame the isolated mesh, not the whole model (radius ${framed.fit.r.toFixed(4)} vs ${framed.whole.r.toFixed(4)})`);+  assert(sameSpot(framed.home.spot, framed.whole.spot) && sameSpot(framed.fit.spot, framed.whole.spot) && framed.home.upper >= framed.whole.upper * (1 - 1e-6),+    "the light and the zoom-out limit keep the whole model's bounds");+  const back = await run(() => {+    const v = window.__v, m = window.__mesh;+    window.__iso.clear();+    v.frameModel();+    return [m("U1_body").visibility, m("U1_body").isPickable, v.getShadowGenerator().getShadowMap().renderList.includes(m("U1_body")), v.getCamera().radius];+  });+  assert(JSON.stringify(back.slice(0, 3)) === "[1,true,true]", `clear() gives every mesh its visibility, picks and shadow back (${back.slice(0, 3)})`);+  assert(Math.abs(back[3] - framed.whole.r) < framed.whole.r * 1e-3, `after clear(), Fit frames the whole model again (radius ${back[3].toFixed(4)})`);+  const ghost = await run(() => {+    const v = window.__v, m = window.__mesh;+    const h = v.isolate("U1", { mode: "ghost", alpha: 0.3 });+    const r = { kept: h.meshes.map(x => x.name), pad7: [+m("pad_7").visibility.toFixed(3), m("pad_7").isPickable], body: m("U1_body").visibility };+    h.clear();+    return r;+  });+  assert(JSON.stringify(ghost.kept) === '["U1_body"]' && JSON.stringify(ghost.pad7) === "[0.3,false]" && ghost.body === 1, `ghost draws the rest at alpha and takes no picks (${JSON.stringify(ghost)})`);+  const swap = await run(() => {+    const v = window.__v, m = window.__mesh;+    const a = v.isolate("pad_7");+    const b = v.isolate("pad_17");+    const during = [m("pad_7").visibility, m("pad_17").visibility, m("U1_body").visibility];+    a.clear();+    const afterStale = m("pad_7").visibility;+    v.clearIsolate();+    const none = v.isolate("nope");+    return { during, afterStale, after: [m("pad_7").visibility, m("pad_17").visibility, m("U1_body").visibility], none: none.meshes.length, untouched: m("pad_7").visibility };+  });+  assert(JSON.stringify(swap.during) === "[0,1,0]", `a new isolate replaces the last (${swap.during})`);+  assert(swap.afterStale === 0, "clear() on a replaced isolation does nothing");+  assert(JSON.stringify(swap.after) === "[1,1,1]", "clearIsolate() ends it");+  assert(swap.none === 0 && swap.untouched === 1, "a target that matches nothing changes nothing");+  const layered = await run(() => {+    const v = window.__v, name = v.getLayers()[0].name, mesh = window.__mesh(name);+    v.setLayerVisible(name, false);+    v.isolate("pad_7");+    v.clearIsolate();+    const r = { name, mesh: !!mesh, hiddenStill: !!mesh && mesh.isVisible === false && v.getLayers().find(l => l.name === name).visible === false };+    v.setLayerVisible(name, true);+    return r;+  });+  assert(layered.mesh && layered.hiddenStill, `a layer hidden before isolate stays hidden after (${layered.name})`);+  const badIso = await run(() => [["hide", "blur"], ["alpha", 2]].map(([k, val]) => {+    try { window.__v.isolate("pad_7", k === "hide" ? { mode: val } : { alpha: val }); return null; } catch (e) { return e.message; }+  }));+  assert(badIso.every(Boolean), `an unknown mode and alpha 2 throw (${badIso.join(" | ")})`);+  await run(() => window.__v.clearIsolate());++  section("focus");+  const foc = await run(async () => {+    const v = window.__v;+    await v.moveCamera("home");+    const before = v.getCameraState();+    const st = await v.focus("pad_7", { ms: 200 });+    const c = window.__mesh("pad_7").getBoundingInfo().boundingBox.centerWorld;+    const none = await v.focus("nope");+    return { before, st, center: [c.x, c.y, c.z], none };+  });+  assert(foc.st && foc.st.target.every((t, i) => near(t, foc.center[i], 1e-6)), `focus centers the target (${foc.st && foc.st.target.map(t => t.toFixed(4))})`);+  assert(foc.st && near(foc.st.alpha, foc.before.alpha) && near(foc.st.beta, foc.before.beta) && foc.st.radius < foc.before.radius, "and keeps the angles, coming closer");+  assert(foc.none === null, "focus on nothing resolves null");++  section("picks skip disabled meshes");+  await run(() => { window.__v.frameModel(); window.__picks = []; window.__mesh("pad_17").setEnabled(false); });+  await page.mouse.click(P17.x, P17.y);+  await waitFor("window.__picks.length >= 1", 5000);+  assert(await run(() => window.__picks[0]) !== "pad_17", "a disabled mesh is not picked");+  await run(() => window.__mesh("pad_17").setEnabled(true));++  section("background");+  const bg = await run(async () => {+    const out = {};+    for (const b of ["studio", "transparent", "#ff0000"]) {+      await window.__make({ background: b, showViewCube: false }, false);+      await new Promise(r => setTimeout(r, 300));+      out[b] = { px: window.__pixel(320, 6), shot: await window.__pngPixel(await window.__v.captureScreenshot({ width: 64, height: 40 }), 32, 1) };+    }+    try { await window.__make({ background: "blue" }, false); out.bad = null; } catch (e) { out.bad = e.message; }+    return out;+  });+  assert(bg.studio.px[3] === 255 && bg.studio.px[2] > bg.studio.px[0], `studio is the opaque blue-grey gradient (${bg.studio.px})`);+  assert(bg.transparent.px[3] === 0, `transparent leaves the canvas clear (${bg.transparent.px})`);+  assert(bg.transparent.shot[3] === 0, `and screenshots keep the alpha (${bg.transparent.shot})`);+  assert(bg["#ff0000"].px[0] > 200 && bg["#ff0000"].px[1] < 60 && bg["#ff0000"].px[3] === 255, `a color fills the background (${bg["#ff0000"].px})`);+  assert(!!bg.bad, `an unknown background throws (${bg.bad})`);++  section("loadBabylon contract");+  const lb = await run(async () => {+    await window.__make({}, false);+    const V = window.Adom3DViewerBabylon9, full = await V.loadBabylon();+    return {+      scene: window.__v.getScene() instanceof full.Scene,+      mesh: full.Mesh === V.BABYLON.Mesh,+      same: (await window.__v.loadBabylon()) === full,+      version: V.babylonVersion,+      engine: full.Engine.Version,+    };+  });+  assert(lb.scene && lb.mesh && lb.same, "loadBabylon() resolves with the module the viewer runs on");+  assert(lb.version === lb.engine && lb.version === PKG.devDependencies["@babylonjs/core"], `babylonVersion is the bundled Babylon release (${lb.version}; package.json ${PKG.devDependencies["@babylonjs/core"]})`);++  assert(pageErrors.length === 0, `no page errors (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/gate.test.mjsadded+240
@@ -0,0 +1,240 @@+// The click-to-load gate and the WebGL context events. A viewer created with+// `gate` shows a card with the model's size, creates no engine until the+// reader presses Load or the host calls openGate(), and runs the loads asked+// for in the meantime once it opens. A load asked for right after init waits+// for the scene. When the browser takes the WebGL context away and gives it+// back, onContextLost and onContextRestored fire and the model paints again.+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }++/** A GLB of one 2 cm emissive red cube named `Part_cube`, so it shows in pixel counts. */+function makeGlb() {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));+  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+  const bin = Buffer.concat([posBuf, idxBuf]);+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0] }],+    nodes: [{ name: "Part_cube", mesh: 0 }],+    meshes: [{ name: "Part_mesh", primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],+    materials: [{ name: "Part_mat", pbrMetallicRoughness: { baseColorFactor: [1, 0, 0, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: [1, 0, 0] }],+    buffers: [{ byteLength: bin.length }],+    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const CUBE = makeGlb();+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  // A fresh viewer in #wrap with these options; the previous one is destroyed.+  window.__init = (opts) => {+    if (window.__v) window.__v.destroy();+    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showGround: false, showHelp: false, ...opts });+  };+  // Settles to 'pending' if the promise has not settled within ms.+  window.__within = (p, ms) => Promise.race([p.then(() => 'resolved', (e) => 'rejected: ' + (e && e.message)), new Promise(r => setTimeout(() => r('pending'), ms))]);+  // Strongly red pixels on the viewer's canvas.+  window.__red = () => {+    const src = window.__v.getEngine().getRenderingCanvas();+    const c = document.createElement('canvas'); c.width = src.width; c.height = src.height;+    const g = c.getContext('2d'); g.drawImage(src, 0, 0);+    const d = g.getImageData(0, 0, c.width, c.height).data;+    let red = 0;+    for (let i = 0; i < d.length; i += 4) if (d[i] > d[i + 1] + 80 && d[i] > d[i + 2] + 80) red++;+    return red;+  };+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (url.pathname === "/cube.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(CUBE); }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);+  const waitFor = (cond, timeout = 30000) => page.waitForFunction(cond, { timeout, polling: 250 }).then(() => true, () => false);++  section("a gated viewer waits for Load");+  const closed = await run(async () => {+    window.__init({ gate: { bytes: 250 * 1048576, vertices: 3400000, downloadUrl: "/cube.glb" } });+    window.__load = window.__v.loadModel("/cube.glb");+    const card = document.querySelector("#wrap .a3d-gate");+    return {+      gated: window.__v.isGated(),+      engine: window.__v.getEngine(),+      scene: window.__v.getScene(),+      text: card ? card.textContent.replace(/\s+/g, " ").trim() : null,+      button: !!document.querySelector("#wrap .a3d-gate-load"),+      download: document.querySelector("#wrap .a3d-gate a[download]")?.getAttribute("href") || null,+      ready: await window.__within(window.__v.whenReady(), 800),+      load: await window.__within(window.__load, 10),+    };+  });+  assert(closed.gated === true, "isGated() is true before Load");+  assert(!closed.engine && !closed.scene, "no engine or scene exists before Load");+  assert(!!closed.text && closed.text.includes("250.0 MB") && closed.text.includes("3.4 M vertices"), `the card gives the size (${closed.text})`);+  assert(closed.button, "the card has a Load button");+  assert(closed.download === "/cube.glb", `the card links the download (${closed.download})`);+  assert(closed.ready === "pending", `whenReady() waits for Load (${closed.ready})`);+  assert(closed.load === "pending", `a load asked for before Load waits (${closed.load})`);++  await page.click("#wrap .a3d-gate-load");+  const opened = await run(async () => {+    const report = await window.__v.whenReady();+    const load = await window.__within(window.__load, 20000);+    return {+      gated: window.__v.isGated(),+      card: !!document.querySelector("#wrap .a3d-gate"),+      report: !!report,+      load,+      meshes: window.__v.getScene().meshes.filter(m => m.name === "Part_cube").length,+    };+  });+  assert(opened.gated === false && !opened.card, "pressing Load removes the card and clears isGated()");+  assert(opened.report, "whenReady() resolves after Load");+  assert(opened.load === "resolved" && opened.meshes === 1, `the waiting load runs once the scene is up (${opened.load}, ${opened.meshes} mesh)`);++  section("openGate() from the host");+  const host = await run(async () => {+    window.__init({ gate: {} });+    const card = document.querySelector("#wrap .a3d-gate p")?.textContent || "";+    const report = await window.__v.openGate();+    const again = await window.__within(window.__v.openGate(), 2000);+    return { card, version: report && report.version, gated: window.__v.isGated(), again, engine: !!window.__v.getEngine() };+  });+  assert(!/MB|vertices/.test(host.card), `without sizes the card leaves them out (${host.card})`);+  assert(typeof host.version === "string" && host.version.length > 0, `openGate() resolves with the ready report (version ${host.version})`);+  assert(host.gated === false && host.engine, "the viewer is running after openGate()");+  assert(host.again === "resolved", "a second openGate() resolves too");++  section("destroy while gated");+  const gone = await run(async () => {+    let hooks = 0;+    window.__init({ gate: {}, onReady: () => { hooks++; } });+    const v = window.__v;+    const load = v.loadModel("/cube.glb");+    const ready = v.whenReady();+    v.destroy();+    window.__v = null;+    const within = (p) => Promise.race([p, new Promise(r => setTimeout(() => r(null), 3000))]);+    const report = await within(ready);+    return { load: await window.__within(load, 3000), report, hooks };+  });+  assert(gone.load !== "pending", `a load waiting behind the gate settles when the viewer is destroyed (${gone.load})`);+  assert(!!gone.report && gone.report.destroyed === true && gone.report.ok === false,+    `whenReady() asked for before the destroy resolves with destroyed: true, ok: false (${gone.report ? JSON.stringify({ destroyed: gone.report.destroyed, ok: gone.report.ok }) : "pending"})`);+  assert(!!gone.report && gone.report.hints.some(h => h.code === "VIEWER_DESTROYED") && gone.report.loadingOverlay === "hidden",+    `its hints say VIEWER_DESTROYED and nothing about an overlay (${gone.report ? gone.report.hints.map(h => h.code).join(", ") : "none"})`);+  assert(gone.hooks === 0, `onReady is not called for a viewer that never came up (${gone.hooks} calls)`);++  section("no gate");+  const early = await run(async () => {+    window.__init({});+    const gated = window.__v.isGated();+    await window.__v.loadModel("/cube.glb");+    await window.__v.whenReady();+    return { gated, card: !!document.querySelector("#wrap .a3d-gate"), meshes: window.__v.getScene().meshes.filter(m => m.name === "Part_cube").length };+  });+  assert(early.gated === false && !early.card, "without gate the viewer starts at once");+  assert(early.meshes === 1, `a load asked for right after init waits for the scene (${early.meshes} mesh)`);++  section("WebGL context lost and restored");+  await run(async () => {+    window.__events = [];+    window.__init({+      onContextLost: () => window.__events.push("lost"),+      onContextRestored: () => window.__events.push("restored"),+    });+    await window.__v.whenReady();+    await window.__v.loadModel("/cube.glb");+    window.__v.frameModel();+  });+  const before = await waitFor("window.__red() > 2000");+  assert(before, "the model paints before the loss");+  const hasExt = await run(() => {+    const c = window.__v.getEngine().getRenderingCanvas();+    const gl = c.getContext("webgl2") || c.getContext("webgl");+    window.__lose = gl && gl.getExtension("WEBGL_lose_context");+    return !!window.__lose;+  });+  assert(hasExt, "WEBGL_lose_context is available");+  if (hasExt) {+    await run(() => window.__lose.loseContext());+    const lost = await waitFor("window.__events.includes('lost')", 10000);+    assert(lost, "onContextLost fires");+    await run(() => window.__lose.restoreContext());+    const restored = await waitFor("window.__events.includes('restored')", 30000);+    assert(restored, `onContextRestored fires (${await run(() => window.__events.join(", "))})`);+    const after = await waitFor("window.__red() > 2000", 30000);+    assert(after, `the model paints again after the restore (${await run(() => window.__red())} red pixels)`);+  }++  section("gate.downloadUrl takes only http(s) and relative URLs");+  const urls = await run(() => {+    const out = {};+    for (const u of ["/cube.glb", "cube.glb", "https://example.com/a.glb", "javascript:alert(1)", " JavaScript:alert(1)", "java\tscript:alert(1)", "data:text/html,x"]) {+      const host = document.createElement("div"); document.body.appendChild(host);+      try {+        const v = window.Adom3DViewerBabylon9.init(host, { showHelp: false, gate: { downloadUrl: u } });+        out[u] = host.querySelector(".a3d-gate a") ? "link" : "no link";+        v.destroy();+      } catch (e) { out[u] = "threw"; }+      host.remove();+    }+    return out;+  });+  assert(urls["/cube.glb"] === "link" && urls["cube.glb"] === "link" && urls["https://example.com/a.glb"] === "link", `relative and https URLs get the link (${JSON.stringify(urls)})`);+  assert(["javascript:alert(1)", " JavaScript:alert(1)", "java\tscript:alert(1)", "data:text/html,x"].every(u => urls[u] === "threw"),+    "javascript: (any case, with a leading space or a tab inside) and data: URLs make init() throw");++  assert(pageErrors.length === 0, `no page errors (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/intro.test.mjs+22−8
@@ -86,7 +86,14 @@ const state = (page) => page.evaluate(() => {     rowChecked: [...document.querySelectorAll(".layers-row")].map(r => r.textContent.trim() + ":" + r.querySelector("input").checked + ":" + r.classList.contains("intro")),     replay: !!document.querySelector(".layers-replay") }; });-const sleep = (ms) => new Promise(r => setTimeout(r, ms));+// The intro's timers start at load, and a busy machine can be anywhere in+// them by the time a fixed sleep ends, so each check waits for the state it+// is about.+const until = (page, fn, timeout = 20000) => page.waitForFunction(fn, { timeout, polling: "raf" });+const introActive = () => { const i = window.__viewer.getIntros()[0]; return !!i && i.active; };+const introOver = () => { const i = window.__viewer.getIntros()[0]; return !!i && !i.active && !i.pending; };+// Past the moment the intro's fade-out would have ended (fadeOutAt 2.8 s + 200 ms), counted from after load.+const pastFadeOut = () => performance.now() - window.__t0 > 3300;  try {   section("declared intro: hidden at load, shows pressed while fading in, rests hidden after");@@ -99,13 +106,13 @@ try {     eq(t0.intros[0].fadeInAt, 1.2, "fadeInAt parsed"); eq(t0.intros[0].fadeOutAt, 2.8, "fadeOutAt parsed");     assert(t0.intros[0].pending, "pending right after load"); assert(!t0.fovShown, "the layer is hidden before fadeInAt");     assert(t0.replay, "the panel offers Replay intro");-    await sleep(1900);+    await until(page, introActive);     const mid = await state(page);     assert(mid.intros[0].active, "active between fadeInAt and fadeOutAt");     assert(mid.fovShown, "the meshes show during the intro");     assert(mid.rowChecked.some(r => r.startsWith("Field of view:true:true")), `the toggle reads pressed and pulsing (${mid.rowChecked.join(" | ")})`);     assert(mid.layers.find(l => l.name === "fov").visible === false, "but the layer's own state stays hidden");-    await sleep(1700);+    await until(page, introOver);     const after = await state(page);     assert(!after.intros[0].active && !after.intros[0].pending, "settled after fadeOutAt");     assert(!after.fovShown, "the layer rests hidden");@@ -118,16 +125,16 @@ try {   {     const page = await open("model=/intro.glb");     await page.evaluate(() => document.querySelector(".layers-toggle").click());-    await sleep(1900);+    await until(page, introActive);     await page.evaluate(() => { const row = [...document.querySelectorAll(".layers-row")].find(r => r.textContent.includes("Field of view")); row.querySelector("input").click(); });-    await sleep(1400);+    await until(page, pastFadeOut);     const kept = await state(page);     assert(kept.layers.find(l => l.name === "fov").visible === true && kept.fovShown, "the layer stays on after the intro would have ended");     assert(!kept.intros[0].active, "and the intro is over");     await page.evaluate(() => window.__viewer.setLayerVisible("fov", false));     const replayed = await page.evaluate(() => window.__viewer.replayIntros());     eq(replayed, true, "replay accepted");-    await sleep(1900);+    await until(page, introActive);     const again = await state(page);     assert(again.intros[0].active && again.fovShown, "the intro plays again");     await page.evaluate(() => window.__viewer.stopIntros());@@ -139,9 +146,16 @@ try {   section("intros:false never plays; no intro means no replay control; bad numbers fall back");   {     const page = await open("model=/intro.glb&intros=0");-    await sleep(2000);+    // Watch every frame until past the fade-out: the intro must never show.+    const everActive = await page.evaluate(() => new Promise(r => {+      const s = window.__viewer.getScene(); let seen = false;+      const o = s.onAfterRenderObservable.add(() => {+        if (window.__viewer.getIntros()[0].active) seen = true;+        if (performance.now() - window.__t0 > 3300) { s.onAfterRenderObservable.remove(o); r(seen); }+      });+    }));     const s = await state(page);-    assert(!s.intros[0].active && !s.intros[0].pending && !s.fovShown, "nothing plays with intros:false");+    assert(!everActive && !s.intros[0].active && !s.intros[0].pending && !s.fovShown, "nothing plays with intros:false");     eq(await page.evaluate(() => window.__viewer.replayIntros()), true, "an explicit replay still works");     await page.close();     const plain = await open("model=/plain.glb");
test/multi.test.mjsadded+321
@@ -0,0 +1,321 @@+// Two viewers on one page. Each init() gets its own engine, scene, camera,+// lights and view cube, draws its own model into its own canvas, and keeps+// its camera, bottom light and shadow settings to itself. Shadow maps shrink+// while several viewers have shadows and grow back after. Destroying one+// leaves the other running, a viewer created afterwards starts clean, a+// viewer destroyed during startup throws nothing and settles whenReady(), the+// ? key and camera:change_view reach one viewer, and a destroyed viewer keeps+// its scene until its textures finish loading.+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }++/** A GLB of one 2 cm cube named `<prefix>_cube` in a flat colour. */+function makeGlb(prefix, rgb) {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));+  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+  const bin = Buffer.concat([posBuf, idxBuf]);+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0] }],+    nodes: [{ name: `${prefix}_cube`, mesh: 0 }],+    meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],+    materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: { baseColorFactor: [...rgb, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: rgb }],+    buffers: [{ byteLength: bin.length }],+    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const PNG_1PX = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64");+const MODELS = {+  "/red.glb": makeGlb("Red", [1, 0, 0]),+  "/green.glb": makeGlb("Green", [0, 1, 0]),+};+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}+.v{position:absolute;top:0;width:320px;height:400px}#a{left:0}#b{left:320px}</style></head><body><div id="a" class="v"></div><div id="b" class="v"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  const V = window.Adom3DViewerBabylon9;+  const make = (id) => V.init(document.getElementById(id), { zUp: true, showViewCube: true, showGround: false, showHelp: false });+  window.__make = make;+  window.__a = make('a'); window.__b = make('b');+  await Promise.all([window.__a.whenReady(), window.__b.whenReady()]);+  // Pixels of a viewer's canvas: how many are strongly red, strongly green,+  // and how many are not transparent at all.+  window.__pixels = (v) => {+    const src = v.getEngine().getRenderingCanvas();+    const c = document.createElement('canvas'); c.width = src.width; c.height = src.height;+    const g = c.getContext('2d'); g.drawImage(src, 0, 0);+    const d = g.getImageData(0, 0, c.width, c.height).data;+    let red = 0, green = 0, opaque = 0;+    for (let i = 0; i < d.length; i += 4) {+      if (d[i + 3] > 0) opaque++;+      if (d[i] > d[i + 1] + 80 && d[i] > d[i + 2] + 80) red++;+      if (d[i + 1] > d[i] + 80 && d[i + 1] > d[i + 2] + 80) green++;+    }+    return { red, green, opaque, total: c.width * c.height };+  };+  window.__frames = (v, ms) => new Promise(r => { let n = 0; const s = v.getScene(); const o = s.onAfterRenderObservable.add(() => n++); setTimeout(() => { s.onAfterRenderObservable.remove(o); r(n); }, ms); });+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (MODELS[url.pathname]) { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(MODELS[url.pathname]); }+  // A 1x1 PNG that answers after 3 s: a texture still loading when its viewer is destroyed.+  if (url.pathname === "/slow.png") { setTimeout(() => { res.writeHead(200, { "Content-Type": "image/png" }); res.end(PNG_1PX); }, 3000); return; }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);+  const waitPixels = (cond) => page.waitForFunction(cond, { timeout: 30000, polling: 250 }).catch(() => {});++  section("each viewer has its own engine, scene, camera and view cube");+  const own = await run(() => {+    const a = window.__a, b = window.__b;+    const cubes = (v) => v.getEngine().scenes.filter(s => s.getMeshByName("viewCubeSPS")).length;+    return {+      engines: a.getEngine() !== b.getEngine(), scenes: a.getScene() !== b.getScene(), cameras: a.getCamera() !== b.getCamera(),+      shadows: a.getShadowGenerator() !== b.getShadowGenerator(),+      mapA: a.getShadowGenerator().mapSize, mapB: b.getShadowGenerator().mapSize,+      lastIsCube: !!window.BABYLON.EngineStore.LastCreatedScene?.getMeshByName("viewCubeSPS"),+      lastIsMain: [a.getScene(), b.getScene()].includes(window.BABYLON.EngineStore.LastCreatedScene),+      canvasA: document.getElementById('a').contains(a.getEngine().getRenderingCanvas()),+      canvasB: document.getElementById('b').contains(b.getEngine().getRenderingCanvas()),+      cubesA: cubes(a), cubesB: cubes(b),+      okA: a.getReadyReport().ok, okB: b.getReadyReport().ok,+    };+  });+  assert(own.engines && own.scenes && own.cameras && own.shadows, "engine, scene, camera and shadow generator differ between the two viewers");+  assert(own.canvasA && own.canvasB, "each engine renders into the canvas inside its own container");+  assert(own.cubesA === 1 && own.cubesB === 1, `one view cube per engine (got ${own.cubesA} and ${own.cubesB})`);+  assert(own.okA && own.okB, "both ready reports are ok");+  assert(own.mapA === 4096 && own.mapB === 4096, `with two viewers each shadow map is 4096 (A ${own.mapA}, B ${own.mapB})`);+  assert(own.lastIsMain && !own.lastIsCube, "Babylon's default scene is a viewer's main scene, never a view cube scene");++  section("each viewer shows only its own model");+  await run(async () => {+    await window.__a.loadModel("/red.glb"); window.__a.frameModel();+    await window.__b.loadModel("/green.glb"); window.__b.frameModel();+    for (const v of [window.__a, window.__b]) v.toggleAxes('world', false);+  });+  // Each engine compiles its own shaders, which takes seconds under software+  // GL: wait for the cubes to show rather than for a fixed time.+  await waitPixels("window.__pixels(window.__a).red > 2000 && window.__pixels(window.__b).green > 2000");+  const names = await run(() => ({+    a: window.__a.getScene().meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)),+    b: window.__b.getScene().meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)),+  }));+  assert(names.a.includes("Red_cube") && !names.a.some(n => n.startsWith("Green")), `viewer A's scene holds the red cube only (${names.a.join(", ")})`);+  assert(names.b.includes("Green_cube") && !names.b.some(n => n.startsWith("Red")), `viewer B's scene holds the green cube only (${names.b.join(", ")})`);+  const pa = await run(() => window.__pixels(window.__a));+  const pb = await run(() => window.__pixels(window.__b));+  console.log(`    pixels A ${JSON.stringify(pa)}  B ${JSON.stringify(pb)}`);+  assert(pa.opaque === pa.total && pb.opaque === pb.total, "both canvases are painted edge to edge");+  assert(pa.red > 2000 && pa.green < pa.red / 5, "canvas A shows the red cube and no green one");+  assert(pb.green > 2000 && pb.red < pb.green / 5, "canvas B shows the green cube and no red one");++  section("camera, bottom light and shadow settings stay with their viewer");+  const iso = await run(async () => {+    const a = window.__a, b = window.__b;+    const cam = (v) => { const c = v.getCamera(); return [c.alpha, c.beta, c.radius, c.target.x, c.target.y, c.target.z]; };+    const before = cam(b);+    a.getCamera().alpha += 1; a.getCamera().radius *= 2; a.frameModel(0.3);+    a.setBottomLight(true);+    a.setShadowRefreshRate(2);+    await new Promise(r => setTimeout(r, 300));+    const after = cam(b);+    return {+      camSame: before.every((x, i) => Math.abs(x - after[i]) < 1e-9),+      bottomA: a.getBottomLightState(), bottomB: b.getBottomLightState(),+      rateA: a.getShadowGenerator().getShadowMap().refreshRate, rateB: b.getShadowGenerator().getShadowMap().refreshRate,+    };+  });+  assert(iso.camSame, "moving and reframing A's camera leaves B's camera where it was");+  assert(iso.bottomA === true && iso.bottomB === false, "A's bottom light is on, B's stays off");+  assert(iso.rateA === 2 && iso.rateB !== 2, `A's pinned shadow refresh rate does not reach B (A ${iso.rateA}, B ${iso.rateB})`);++  section("destroying one viewer leaves the other running");+  const after = await run(async () => {+    window.__a.destroy();+    const b = window.__b;+    const frames = await window.__frames(b, 600);+    await b.replaceModel("/red.glb"); b.frameModel();+    await new Promise(r => setTimeout(r, 500));+    const s = b.getScene();+    return { alive: !!s && !s.isDisposed && !b.getEngine().isDisposed, frames, ok: b.getReadyReport().ok,+      meshes: s.meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)) };+  });+  assert(after.alive, "B's scene and engine are not disposed");+  assert(after.frames > 0, `B keeps rendering (${after.frames} frames in 600 ms)`);+  assert(after.meshes.includes("Red_cube") && !after.meshes.includes("Green_cube"), "B can still replace its model");+  assert(after.ok, "B's ready report is still ok");+  const grown = await page.waitForFunction("window.__b.getShadowGenerator().mapSize === 8192", { timeout: 35000, polling: 100 }).then(() => true, () => false);+  const castersKept = await run(() => window.__b.getShadowGenerator().getShadowMap().renderList.some(m => m.name === "Red_cube"));+  assert(grown, "once A's map is freed, B, now the only viewer with shadows, gets an 8192 map back");+  assert(castersKept, "the resized map keeps B's shadow casters");++  section("a viewer created after a destroy starts clean");+  const fresh = await run(async () => {+    const c = window.__make('a'); window.__c = c;+    const r = await c.whenReady();+    await c.loadModel("/green.glb"); c.frameModel(); c.toggleAxes('world', false);+    return { ok: r.ok, bottom: c.getBottomLightState(), rate: c.getShadowGenerator().getShadowMap().refreshRate,+      ownEngine: c.getEngine() !== window.__b.getEngine() };+  });+  await waitPixels("window.__pixels(window.__c).green > 2000");+  fresh.px = await run(() => window.__pixels(window.__c));+  assert(fresh.ok && fresh.ownEngine, "the new viewer reports ok on its own engine");+  assert(fresh.bottom === false && fresh.rate !== 2, `it does not inherit the destroyed viewer's bottom light or shadow rate (rate ${fresh.rate})`);+  assert(fresh.px.green > 2000, "it draws its own model");+  const both = await run(() => [window.__b.getShadowGenerator().mapSize, window.__c.getShadowGenerator().mapSize]);+  assert(both[0] === 4096 && both[1] === 4096, `a second viewer with shadows takes both maps to 4096 (${both.join(", ")})`);+  const noShadow = await run(async () => {+    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);+    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: false, showHelp: false, shadows: false });+    await d.whenReady();+    const sizes = [window.__b.getShadowGenerator().mapSize, window.__c.getShadowGenerator().mapSize];+    d.destroy(); host.remove();+    return sizes;+  });+  assert(noShadow[0] === 4096 && noShadow[1] === 4096, `a viewer with shadows:false does not count (${noShadow.join(", ")})`);++  section("a viewer destroyed during startup throws nothing");+  const before = pageErrors.length;+  const early = await run(async () => {+    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);+    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: true, showHelp: false });+    const ready = d.whenReady();+    d.destroy();+    const r = await Promise.race([ready, new Promise(res => setTimeout(() => res(null), 3000))]);+    await new Promise(r => setTimeout(r, 1500));+    host.remove();+    return r && { destroyed: r.destroyed, ok: r.ok };+  });+  assert(pageErrors.length === before, `no page errors after an immediate destroy (${pageErrors.slice(before).join(" | ") || "none"})`);+  assert(!!early && early.destroyed === true && early.ok === false, `its whenReady() resolves with destroyed: true (${JSON.stringify(early)})`);+  const stillB = await run(() => window.__frames(window.__b, 400));+  assert(stillB > 0, "B still renders afterwards");++  section("a viewer destroyed right after its first model loads throws nothing");+  // The first PBR material makes Babylon decode an RGBD lookup texture+  // through an async shader import, after which it reads the texture's+  // scene; a destroy inside that window used to throw there.+  const beforeLoad = pageErrors.length;+  await run(async () => {+    // The window opens on the frames after the load, so try several delays.+    for (const ms of [0, 20, 50, 100, 200, 400]) {+      const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);+      const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: true, showHelp: false });+      await d.whenReady();+      await d.loadModel("/red.glb");+      await new Promise(r => setTimeout(r, ms));+      d.destroy();+      host.remove();+    }+    await new Promise(r => setTimeout(r, 2500));+  });+  assert(pageErrors.length === beforeLoad, `no page errors after destroys 0 to 400 ms after a load (${pageErrors.slice(beforeLoad).join(" | ") || "none"})`);++  section("page-level keys and events reach one viewer");+  // Two viewers with their help cards, side by side where A and B were.+  await run(async () => {+    window.__b.destroy(); window.__c.destroy();+    for (const k of ["a", "b"]) document.getElementById(k).innerHTML = "";+    const mk = (id) => window.Adom3DViewerBabylon9.init(document.getElementById(id), { zUp: true, showViewCube: true, showHelp: true });+    window.__d = mk("a"); window.__e = mk("b");+    await Promise.all([window.__d.whenReady(), window.__e.whenReady()]);+  });+  const cards = () => run(() => ["a", "b"].map(id => { const c = document.getElementById(id).querySelector(".a3d-help-card"); return !!c && !c.hidden; }));+  await page.mouse.move(480, 200);+  await page.keyboard.press("?");+  const overE = await cards();+  assert(!overE[0] && overE[1], `with the pointer over the right viewer, ? opens only its card (${overE})`);+  await page.keyboard.press("?");+  await page.mouse.move(160, 200);+  await page.keyboard.press("?");+  const overD = await cards();+  assert(overD[0] && !overD[1], `after moving to the left viewer, ? opens only that card (${overD})`);+  await page.keyboard.press("Escape");+  const views = await run(async () => {+    const d = window.__d.getCamera(), e = window.__e.getCamera();+    for (const c of [d, e]) { c.alpha = 0.7; c.beta = 1.2; }+    const settle = () => new Promise(r => setTimeout(r, 1500));+    window.dispatchEvent(new CustomEvent("camera:change_view", { detail: { orientation: "top" } }));+    await settle();+    const onWindow = [d.beta, e.beta];+    for (const c of [d, e]) { c.alpha = 0.7; c.beta = 1.2; }+    window.__e.getEngine().getRenderingCanvas().dispatchEvent(new CustomEvent("camera:change_view", { bubbles: true, detail: { orientation: "top" } }));+    await settle();+    return { onWindow, onCanvasE: [d.beta, e.beta] };+  });+  assert(views.onWindow[0] < 0.1 && Math.abs(views.onWindow[1] - 1.2) < 1e-6, `camera:change_view on window turns only the viewer last pointed at (betas ${views.onWindow.map(b => b.toFixed(3))})`);+  assert(views.onCanvasE[1] < 0.1 && Math.abs(views.onCanvasE[0] - 1.2) < 1e-6, `dispatched on a viewer's canvas, it turns that viewer (betas ${views.onCanvasE.map(b => b.toFixed(3))})`);++  section("a destroyed viewer keeps its scene until its textures finish loading");+  // The texture answers after 3 s, longer than any fixed wait the dispose+  // used to allow; the scene must outlive it and then be released.+  const slow = await run(async () => {+    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);+    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: false, showHelp: false });+    await d.whenReady();+    const scene = d.getScene();+    new window.BABYLON.Texture("/slow.png", scene);+    const t0 = performance.now();+    d.destroy();+    host.remove();+    await new Promise(r => setTimeout(r, 2500));+    const keptAt2500 = !scene.isDisposed;+    while (!scene.isDisposed && performance.now() - t0 < 20000) await new Promise(r => setTimeout(r, 50));+    return { keptAt2500, disposed: scene.isDisposed, ms: Math.round(performance.now() - t0) };+  });+  assert(slow.keptAt2500, "2.5 s after destroy the scene is still alive while the texture loads");+  assert(slow.disposed && slow.ms >= 2900, `the scene is released once the texture arrives (${slow.ms} ms after destroy)`);+  assert(pageErrors.length === 0, `no page errors in the whole run (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/options.test.mjsadded+225
@@ -0,0 +1,225 @@+// Scene options a host sets at init(): animate, repeat and replayAnimations(),+// tooltips, axes, bottomLight, shadows, homeView and homeOnLoad. Each is+// checked against the default it changes.+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }+const near = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;++/** A GLB of one 2 cm cube. `extras` goes on the node; `seconds` adds a+ *  translation animation from x = 0 to x = 0.02 over that many seconds. */+function makeGlb(nodeName, { extras = null, seconds = 0 } = {}) {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const parts = [pad(Buffer.from(new Float32Array(pos).buffer)), pad(Buffer.from(new Uint16Array(idx).buffer))];+  if (seconds) parts.push(pad(Buffer.from(new Float32Array([0, seconds]).buffer)), pad(Buffer.from(new Float32Array([0, 0, 0, 0.02, 0, 0]).buffer)));+  const views = []; let off = 0;+  for (const p of parts) { views.push({ buffer: 0, byteOffset: off, byteLength: p.length }); off += p.length; }+  const bin = Buffer.concat(parts);+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0] }],+    nodes: [{ name: nodeName, mesh: 0, ...(extras ? { extras } : {}) }],+    meshes: [{ name: "mesh", primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],+    materials: [{ name: "mat", pbrMetallicRoughness: { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],+    ...(seconds ? { animations: [{ name: "slide", samplers: [{ input: 2, output: 3, interpolation: "LINEAR" }], channels: [{ sampler: 0, target: { node: 0, path: "translation" } }] }] } : {}),+    buffers: [{ byteLength: bin.length }],+    bufferViews: views,+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+      ...(seconds ? [{ bufferView: 2, componentType: 5126, count: 2, type: "SCALAR", min: [0], max: [seconds] }, { bufferView: 3, componentType: 5126, count: 2, type: "VEC3" }] : []),+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const MODELS = {+  "/slide.glb": makeGlb("Slider_part", { seconds: 0.3 }),+  "/plain.glb": makeGlb("Plain_part"),+  "/authored.glb": makeGlb("Authored_part", { extras: { tooltip: "Authored label" } }),+};+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  window.__tips = [];+  // A fresh viewer in #wrap with these options; the previous one is destroyed.+  window.__make = async (opts) => {+    if (window.__v) window.__v.destroy();+    window.__tips = [];+    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), {+      zUp: true, showViewCube: false, showHelp: false,+      onMeshHover: (mesh, tip) => { if (mesh) window.__tips.push(tip); },+      ...opts });+    await window.__v.whenReady();+  };+  window.__slide = () => {+    const s = window.__v.getScene(); const g = s.animationGroups[0]; const n = s.getTransformNodeByName("Slider_part") || s.getMeshByName("Slider_part");+    return { groups: s.animationGroups.length, playing: !!g && g.isPlaying, loop: !!g && g.loopAnimation, x: n ? n.position.x : null };+  };+  window.__cam = () => { const c = window.__v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius }; };+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (MODELS[url.pathname]) { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(MODELS[url.pathname]); }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);+  const wait = (ms) => new Promise(r => setTimeout(r, ms));+  // Babylon advances animations by rendered frames, so a loaded machine+  // stretches them: wait for the group to stop instead of a fixed time.+  const animationStops = () => page.waitForFunction("(() => { const g = window.__v.getScene().animationGroups[0]; return !!g && !g.isPlaying; })()", { timeout: 20000, polling: 100 }).catch(() => {});+  const make = (opts) => run((o) => window.__make(o), opts);+  const load = (url) => run(async (u) => { await window.__v.loadModel(u); }, url);+  // Hover the middle of the viewer a few times; the viewer picks at most every 50 ms.+  async function hoverTips() {+    await run(() => { window.__tips = []; });+    for (const [x, y] of [[318, 200], [320, 202], [322, 198], [320, 200]]) { await page.mouse.move(x, y); await wait(120); }+    const tips = await run(() => window.__tips.slice());+    await page.mouse.move(5, 5); await wait(120);+    return tips;+  }++  section("animate and repeat");+  await make({});+  await load("/slide.glb");+  await wait(900);+  let a = await run(() => window.__slide());+  assert(a.groups === 1 && a.playing && a.loop, `by default the model's animation keeps looping (${JSON.stringify(a)})`);+  assert(await run(() => window.__v.getAxesState().world) === true, "by default the world axes are on");+  assert(await run(() => window.__v.getBottomLightState()) === false, "by default the bottom light is off");+  assert(await run(() => window.__v.getScene().shadowsEnabled) === true, "by default shadows are on");++  await make({ animate: false });+  await load("/slide.glb");+  await wait(600);+  a = await run(() => window.__slide());+  assert(!a.playing && near(a.x, 0), `animate:false holds the animation at its first frame (${JSON.stringify(a)})`);+  assert(await run(() => window.__v.replayAnimations()) === true, "replayAnimations() returns true for an animated model");+  await animationStops();+  a = await run(() => window.__slide());+  assert(!a.playing && near(a.x, 0.02), `with animate:false a replay plays once and rests on the last frame (${JSON.stringify(a)})`);++  await make({ repeat: 2 });+  await load("/slide.glb");+  await run(() => { window.__ends = 0; window.__v.getScene().animationGroups[0].onAnimationGroupEndObservable.add(() => window.__ends++); });+  await animationStops();+  a = await run(() => window.__slide());+  let ends = await run(() => window.__ends);+  assert(!a.playing && near(a.x, 0.02) && ends === 2, `repeat:2 plays twice, then rests on the last frame (ends ${ends}, ${JSON.stringify(a)})`);+  await run(() => { window.__ends = 0; window.__v.replayAnimations(); });+  await animationStops();+  a = await run(() => window.__slide());+  ends = await run(() => window.__ends);+  assert(!a.playing && near(a.x, 0.02) && ends === 2, `a replay plays twice again (ends ${ends})`);++  await make({});+  await load("/plain.glb");+  assert(await run(() => window.__v.replayAnimations()) === false, "replayAnimations() returns false for a model without animation");++  section("tooltips");+  await make({});+  await load("/plain.glb");+  let tips = await hoverTips();+  assert(tips.length > 0 && tips.every(t => t === "Plain part"), `'all' labels a mesh by its readable name (${JSON.stringify(tips)})`);+  await make({ tooltips: "authored" });+  await load("/plain.glb");+  tips = await hoverTips();+  assert(tips.length > 0 && tips.every(t => t === null), `'authored' gives no label for a mesh without extras.tooltip (${JSON.stringify(tips)})`);+  await make({ tooltips: "authored" });+  await load("/authored.glb");+  tips = await hoverTips();+  assert(tips.length > 0 && tips.every(t => t === "Authored label"), `'authored' keeps extras.tooltip (${JSON.stringify(tips)})`);+  await make({ tooltips: "off" });+  await load("/authored.glb");+  tips = await hoverTips();+  assert(tips.length > 0 && tips.every(t => t === null), `'off' gives no label even with extras.tooltip, and onMeshHover still runs (${tips.length} hovers)`);++  section("axes, bottom light, shadows");+  await make({ axes: false, bottomLight: true, shadows: false });+  await load("/plain.glb");+  await run(() => window.__v.frameModel());+  const s = await run(() => ({ axes: window.__v.getAxesState().world, bottom: window.__v.getBottomLightState(), shadows: window.__v.getScene().shadowsEnabled,+    generator: window.__v.getShadowGenerator(), maps: window.__v.getScene().textures.filter(t => /_shadowMap$/.test(t.name)).length }));+  assert(s.axes === false, "axes:false starts with the world axes off, and a load keeps them off");+  assert(s.bottom === true, "bottomLight:true starts with the bottom light on");+  assert(s.shadows === false, "shadows:false keeps shadows off through a load and a reframe");+  assert(s.generator === null && s.maps === 0, `shadows:false creates no shadow generator and no shadow map (${s.maps} maps)`);++  section("homeView and homeOnLoad");+  const view = { alpha: 1.1, beta: 0.6, radiusScale: 2 };+  await make({ homeView: view, homeOnLoad: true });+  await load("/plain.glb");+  const opened = await run(() => window.__cam());+  assert(near(opened.alpha, 1.1) && near(opened.beta, 0.6), `homeOnLoad opens at the host's home view (${JSON.stringify(opened)})`);+  await run(() => { const c = window.__v.getCamera(); c.alpha = 0.2; c.beta = 1.2; window.__v.goHome(); });+  const back = await run(() => window.__cam());+  assert(near(back.alpha, 1.1) && near(back.beta, 0.6) && near(back.radius, opened.radius, 1e-6), "goHome() returns to the same view");+  await load("/authored.glb");+  const second = await run(() => window.__cam());+  assert(near(second.alpha, 1.1) && near(second.beta, 0.6), "a second load keeps the current angle (only the first load goes Home)");++  await run(async (v) => {+    window.__v.destroy();+    window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showHelp: false, homeView: v, homeOnLoad: true });+    await window.__v.loadModel("/plain.glb");+  }, view);+  const early = await run(() => window.__cam());+  assert(near(early.alpha, 1.1) && near(early.beta, 0.6), `a load started right after init(), before the viewer is ready, also opens at the home view (${JSON.stringify(early)})`);++  await make({ homeOnLoad: true });+  await load("/plain.glb");+  const corner = await run(() => window.__cam());+  await run(() => window.__v.goHome());+  const corner2 = await run(() => window.__cam());+  assert(near(corner.alpha, corner2.alpha) && near(corner.beta, corner2.beta), "homeOnLoad without homeView opens at the cube corner, where Home goes");++  await make({ homeView: view });+  await load("/plain.glb");+  const plain = await run(() => window.__cam());+  assert(!near(plain.alpha, 1.1) || !near(plain.beta, 0.6), "without homeOnLoad the first load frames from the starting view, not Home");++  assert(pageErrors.length === 0, `no page errors (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/pin-finish.test.mjs+53−13
@@ -7,6 +7,7 @@ import puppeteer from 'puppeteer-core';  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const DIST = join(ROOT, process.env.VIEWER_DIST || 'dist-standalone');+let passed = 0; const ok = m => { passed++; console.log('    ok ' + m); }; const positions = new Float32Array([-0.001,-0.001,0, 0.001,-0.001,0, 0,0.001,0]); const normals = new Float32Array([0,0,1, 0,0,1, 0,0,1]); const bin = Buffer.concat([Buffer.from(positions.buffer), Buffer.from(normals.buffer)]);@@ -25,7 +26,13 @@ text = Buffer.concat([text,Buffer.alloc((4-text.length%4)%4,32)]); const head = Buffer.alloc(20);head.write('glTF');head.writeUInt32LE(2,4);head.writeUInt32LE(28+text.length+bin.length,8);head.writeUInt32LE(text.length,12);head.write('JSON',16); const chunk = Buffer.alloc(8);chunk.writeUInt32LE(bin.length);chunk.write('BIN\0',4); const glb = Buffer.concat([head,text,chunk,bin]);-const html = `<div id="wrap" style="width:640px;height:480px"></div><script type="module">+// window.__slowDecode (ms) holds back every image decode, so a test can catch the pin studio map mid-load.+const html = `<div id="wrap" style="width:640px;height:480px"></div><div id="wrap2" style="position:absolute;left:0;top:0;width:320px;height:240px"></div><script type="module">+const decode=window.createImageBitmap.bind(window);window.__slowDecode=0;+window.createImageBitmap=async(src,...rest)=>{if(window.__slowDecode)await new Promise(r=>setTimeout(r,window.__slowDecode));return decode(src,...rest);};+// Ready, rendered, and still ready after that frame (a frame can start a shader compile, which a loaded+// CI runner makes slow). A scene that never gets there gives up after 60 s and fails the check that follows.+window.__settle=async s=>{const end=performance.now()+60000;do{await Promise.race([s.whenReadyAsync(true),new Promise(r=>setTimeout(r,1000))]);s.render();}while(!s.isReady()&&performance.now()<end);}; await import('/adom-3d-viewer-babylon9.esm.js'); window.v = Adom3DViewerBabylon9.init(document.getElementById('wrap'),{showGround:false,showViewCube:false,showHelp:false,environment:new URLSearchParams(location.search).has('none')?'none':'studio'}); const early = new URLSearchParams(location.search).get('early');@@ -59,16 +66,16 @@ try {   for (const early of ['url','bytes']) {     await page.goto(url+'/?early='+early);await page.waitForFunction('window.ready===true',{timeout:90000});     const applied=await page.evaluate(async()=>{-      const s=v.getScene();await s.whenReadyAsync();s.render();+      const s=v.getScene();await __settle(s);       const gold=s.materials.find(m=>m.name==='AdomMachineGold');       return {grain:!!gold?.pluginManager?.getPlugin('AdomPinGrain')?.on,reflections:!!gold?.reflectionTexture?.isReady()};     });-    assert.deepEqual(applied,{grain:true,reflections:true},'immediate '+early+' load keeps the pin finish');+    assert.deepEqual(applied,{grain:true,reflections:true},'immediate '+early+' load keeps the pin finish');ok('a '+early+' load right after init gets the grain and reflections');   }   await page.goto(url);await page.waitForFunction('window.ready===true',{timeout:90000});   const load=async(add=false)=>page.evaluate(async additive=>{     await (additive?v.addModel('/pins.glb'):v.replaceModel('/pins.glb'));-    const s=v.getScene();await s.whenReadyAsync();s.render();+    const s=v.getScene();await __settle(s);     const gold=s.materials.filter(m=>m.name==='AdomMachineGold');     return {gold:gold.length,active:gold.filter(m=>m.pluginManager?.getPlugin('AdomPinGrain')?.on).length,       reflected:gold.filter(m=>m.reflectionTexture?.isReady()).length, textures:s.textures.length,@@ -76,20 +83,53 @@ try {       compiled:s.meshes.filter(m=>gold.includes(m.material)).every(m=>m.subMeshes.every(sm=>sm.effect?.isReady())),       ready:s.isReady(),intensity:s.environmentIntensity,tone:s.imageProcessingConfiguration.toneMappingEnabled};   },add);-  const first=await load();assert.equal(first.active,1);assert.equal(first.reflected,1);assert.equal(first.compiled,true);assert.equal(first.unrelated,true);assert.equal(first.intensity,0.5);assert.equal(first.tone,true);-  for(let i=0;i<3;i++) assert.deepEqual(await load(),first);+  const first=await load();assert.equal(first.active,1);assert.equal(first.reflected,1);assert.equal(first.compiled,true);assert.equal(first.unrelated,true);assert.equal(first.intensity,0.5);assert.equal(first.tone,true);ok('grain and reflections on the pin only; intensity 0.5 and tone mapping on');+  for(let i=0;i<3;i++) assert.deepEqual(await load(),first);ok('replacing the model three times leaves the same textures');   const added=await load(true);assert.equal(added.active,2);assert.equal(added.reflected,2);assert.equal(added.ready,true);-  assert.deepEqual(await load(),first);+  assert.deepEqual(await load(),first);ok('an added model gets its own reflections; replacing it goes back to one');   const fallback=await page.evaluate(async()=>{     const s=v.getScene(), m=s.materials.find(m=>m.name==='AdomMachineGold');let removed=false;     m.onError({isReady:()=>false,dispose:()=>{removed=true;}},'deliberate test compile failure');-    await new Promise(r=>setTimeout(r,30));await s.whenReadyAsync();s.render();+    await new Promise(r=>setTimeout(r,30));await __settle(s);     return {removed,ready:s.isReady(),active:m.pluginManager.getPlugin('AdomPinGrain').on};   });-  assert.deepEqual(fallback,{removed:true,ready:true,active:false});+  assert.deepEqual(fallback,{removed:true,ready:true,active:false});ok('a grain shader that does not compile falls back');+  // destroy() with the pin studio map still decoding, and 0 to 400 ms after a pin load: the load+  // settles, the scene is released, and nothing throws.+  const midDecode=await page.evaluate(async()=>{+    const d=Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{showGround:false,showViewCube:false,showHelp:false});+    await d.whenReady();+    window.__slowDecode=1500;+    let settled=null;d.loadModel('/pins.glb').then(()=>{settled='resolved';},e=>{settled='rejected: '+e.message;});+    const s=d.getScene(),t0=performance.now();+    let caught=false;+    while(performance.now()-t0<5000){+      if(s.textures.some(t=>t.name==='AdomPinStudio'&&!t.isReady())){caught=true;break;}+      await new Promise(r=>setTimeout(r,5));+    }+    d.destroy();+    const t1=performance.now();+    while(!s.isDisposed&&performance.now()-t1<20000) await new Promise(r=>setTimeout(r,50));+    await new Promise(r=>setTimeout(r,2000));+    window.__slowDecode=0;+    return {caught,settled,disposed:s.isDisposed};+  });+  assert.deepEqual(midDecode,{caught:true,settled:'resolved',disposed:true},'a destroy while the pin studio map decodes settles the load and releases the scene');ok('a destroy while the studio map decodes settles the load and releases the scene');+  await page.evaluate(async()=>{+    for(const ms of [0,20,50,100,200,400]){+      const d=Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{showGround:false,showViewCube:false,showHelp:false});+      await d.whenReady();+      await d.loadModel('/pins.glb');+      await new Promise(r=>setTimeout(r,ms));+      d.destroy();+    }+    await new Promise(r=>setTimeout(r,2500));+  });+  assert.deepEqual(errors,[],'no page errors from destroys while the pin finish loads');ok('destroys during and 0 to 400 ms after a pin load throw nothing');   await page.goto(url+'/?none');await page.waitForFunction('window.ready===true',{timeout:90000});-  const none=await load();assert.equal(none.active,1);assert.equal(none.reflected,0);assert.equal(none.ready,true);-  assert.deepEqual(errors,[]);assert.deepEqual(violations,[]);-  console.log(JSON.stringify({first,added,fallback,none}));-  console.log('Pin grain compiles; bundled reflections obey CSP; non-pin materials, replacement, additive loads, no-environment and compile fallback pass.');+  const none=await load();assert.equal(none.active,1);assert.equal(none.reflected,0);assert.equal(none.ready,true);ok("environment: 'none' keeps the grain and drops the reflections");+  assert.deepEqual(errors,[]);assert.deepEqual(violations,[]);ok('no page errors and no CSP violations');+  console.log(JSON.stringify({first,added,fallback,midDecode,none}));+  console.log('Pin grain compiles; bundled reflections obey CSP; non-pin materials, replacement, additive loads, destroy during loads, no-environment and compile fallback pass.');+  console.log(`${passed} passed, 0 failed`); } finally {await browser.close();server.close();}
test/select.test.mjsadded+343
@@ -0,0 +1,343 @@+// Pick and hover events, findNodes and highlight. A click that does not drag+// fires 'pick' with the content mesh under it (null on empty space) and its+// path from the model root; a drag, the view cube's corner and a removed+// listener fire nothing. 'hover' fires when the mesh under the pointer+// changes. findNodes matches names, RegExps and predicates over content+// only. Highlights light one mesh even when its material is shared, stack+// with the latest on top, and give each mesh its own look back on clear.+// Picks and the view cube's corner are also checked on a 2x display.+import http from "node:http";+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, "..");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");+let passed = 0, failed = 0; const failures = [];+function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }+function section(t) { console.log("\n  [" + t + "]"); }+const near = (a, b, eps = 1e-3) => Math.abs(a - b) < eps;++/**+ * A GLB of 1 cm grey boxes sharing one material: node U1 holding mesh node+ * U1_body at the origin, and pad_7 and pad_17 2.5 cm to either side.+ */+function makeGlb() {+  const pos = [], idx = [];+  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];+  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.005, v[1] * 0.005, v[2] * 0.005); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);+  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));+  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+  const bin = Buffer.concat([posBuf, idxBuf]);+  const prim = { attributes: { POSITION: 0 }, indices: 1, material: 0 };+  const json = {+    asset: { version: "2.0" }, scene: 0,+    scenes: [{ nodes: [0, 2, 3] }],+    nodes: [+      { name: "U1", children: [1] },+      { name: "U1_body", mesh: 0 },+      { name: "pad_7", mesh: 1, translation: [0.025, 0, 0] },+      { name: "pad_17", mesh: 2, translation: [-0.025, 0, 0] },+    ],+    meshes: [{ name: "body", primitives: [prim] }, { name: "p7", primitives: [prim] }, { name: "p17", primitives: [prim] }],+    materials: [{ name: "grey", pbrMetallicRoughness: { baseColorFactor: [0.5, 0.5, 0.5, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: [0.5, 0.5, 0.5] }],+    buffers: [{ byteLength: bin.length }],+    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],+    accessors: [+      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.005, -0.005, -0.005], max: [0.005, 0.005, 0.005] },+      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },+    ],+  };+  let jsonBuf = Buffer.from(JSON.stringify(json));+  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);+  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);+  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };+  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);+}++const PARTS = makeGlb();+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), {+    zUp: true, showViewCube: true, showHelp: false,+    onGroundCreated: (g) => { window.__ground = g; },+  });+  await window.__v.whenReady();+  await window.__v.loadModel('/parts.glb');+  window.__v.frameModel();+  window.__mesh = (name) => window.__v.getScene().getMeshByName(name);+  // A page point over the middle of the named mesh, found by picking a grid+  // in CSS pixels (scene.pick's unit at any pixel density).+  window.__at = (name) => {+    const s = window.__v.getScene(), c = window.__v.getEngine().getRenderingCanvas();+    const hits = [];+    for (let y = 4; y < c.clientHeight; y += 4) for (let x = 4; x < c.clientWidth; x += 4) {+      const p = s.pick(x, y, m => m.isPickable && m.isVisible);+      if (p.hit && p.pickedMesh && p.pickedMesh.name === name) hits.push([x, y]);+    }+    if (!hits.length) return null;+    const cx = hits.reduce((a, h) => a + h[0], 0) / hits.length, cy = hits.reduce((a, h) => a + h[1], 0) / hits.length;+    hits.sort((a, b) => Math.hypot(a[0] - cx, a[1] - cy) - Math.hypot(b[0] - cx, b[1] - cy));+    const r = c.getBoundingClientRect();+    return { x: r.left + hits[0][0], y: r.top + hits[0][1] };+  };+  // Strongly blue pixels on the canvas.+  window.__blue = () => {+    const src = window.__v.getEngine().getRenderingCanvas();+    const c = document.createElement('canvas'); c.width = src.width; c.height = src.height;+    const g = c.getContext('2d'); g.drawImage(src, 0, 0);+    const d = g.getImageData(0, 0, c.width, c.height).data;+    let n = 0;+    for (let i = 0; i < d.length; i += 4) if (d[i + 2] > d[i] + 80 && d[i + 2] > d[i + 1] + 50) n++;+    return n;+  };+  window.__ready = true;+</script></body></html>`;++if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }+const server = http.createServer((req, res) => {+  const url = new URL(req.url, "http://x");+  if (url.pathname === "/parts.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(PARTS); }+  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  if (url.pathname === "/favicon.ico") { res.writeHead(204); return res.end(); }+  const file = join(DIST, url.pathname.replace(/^\/+/, ""));+  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }+  res.writeHead(404); res.end();+});+await new Promise(r => server.listen(0, "127.0.0.1", r));+const port = server.address().port;+let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }+function findChrome() {+  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;+  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");+  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }+  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");+}+const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });+try {+  const page = await browser.newPage();+  const pageErrors = [];+  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  page.on("console", (m) => { if (m.type() === "error") pageErrors.push("console: " + m.text() + " " + (m.location()?.url || "")); });+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  const run = (fn, ...args) => page.evaluate(fn, ...args);+  const waitFor = (cond, timeout = 30000) => page.waitForFunction(cond, { timeout, polling: 100 }).then(() => true, () => false);+  const pause = (ms) => new Promise(r => setTimeout(r, ms));++  section("findNodes");+  const found = await run(() => {+    const v = window.__v, names = (a) => a.map(n => n.name);+    const all = v.findNodes(() => true);+    const sceneMeshes = v.getScene().meshes;+    let threw = null;+    try { v.findNodes(42); } catch (e) { threw = e.message; }+    const g = /^pad_/g;+    return {+      byName: names(v.findNodes("U1")),+      byRe: names(v.findNodes(/^pad_/)),+      byGlobalRe: [names(v.findNodes(g)), names(v.findNodes(g))],+      byFn: names(v.findNodes(n => n.name.endsWith("_body"))),+      none: v.findNodes("nope").length,+      groundIncluded: !!window.__ground && all.includes(window.__ground),+      viewerMeshesLeftOut: sceneMeshes.filter(m => !all.includes(m)).length,+      threw,+    };+  });+  assert(JSON.stringify(found.byName) === '["U1"]', `a name finds that node (${found.byName})`);+  assert(JSON.stringify(found.byRe) === '["pad_7","pad_17"]', `a RegExp finds every match in scene order (${found.byRe})`);+  assert(found.byGlobalRe[0].length === 2 && found.byGlobalRe[1].length === 2, "a RegExp with the g flag finds the same nodes on every call");+  assert(JSON.stringify(found.byFn) === '["U1_body"]', `a function finds the nodes it accepts (${found.byFn})`);+  assert(found.none === 0, "an unknown name finds nothing");+  assert(!found.groundIncluded && found.viewerMeshesLeftOut > 0, `the ground and the viewer's own meshes are left out (${found.viewerMeshesLeftOut} left out)`);+  assert(!!found.threw, `a query that is not a name, RegExp or function throws (${found.threw})`);++  section("highlight: overlay");+  await waitFor("window.__blue() < 50");+  const blueBefore = await run(() => window.__blue());+  const lit = await run(() => {+    const v = window.__v, p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");+    const own = { on: p7.renderOverlay, color: p7.overlayColor.asArray(), alpha: p7.overlayAlpha };+    window.__own = own;+    window.__h = v.highlight("pad_7");+    return {+      meshes: window.__h.meshes.map(m => m.name),+      shared: p7.material === p17.material,+      on: p7.renderOverlay, alpha: p7.overlayAlpha, color: p7.overlayColor.asArray(),+      other: !!p17.renderOverlay,+    };+  });+  assert(JSON.stringify(lit.meshes) === '["pad_7"]', `highlight(name) returns the meshes it lit (${lit.meshes})`);+  assert(lit.on && near(lit.alpha, 0.75) && near(lit.color[0], 0.2) && near(lit.color[1], 0.52) && near(lit.color[2], 1), `default overlay: blue at 0.75 (${lit.color.map(c => c.toFixed(2))} @ ${lit.alpha})`);+  assert(lit.shared && lit.other === false, "a mesh sharing the material stays unlit");+  const blueLit = await waitFor(`window.__blue() > ${blueBefore + 300}`);+  assert(blueLit, `the highlight paints (${blueBefore} blue pixels before, ${await run(() => window.__blue())} after)`);+  const unlit = await run(() => {+    window.__h.clear();+    const p7 = window.__mesh("pad_7");+    return { on: p7.renderOverlay, color: p7.overlayColor.asArray(), alpha: p7.overlayAlpha, own: window.__own };+  });+  assert(unlit.on === unlit.own.on && unlit.alpha === unlit.own.alpha && JSON.stringify(unlit.color) === JSON.stringify(unlit.own.color), "clear() gives the mesh its own overlay settings back");+  const group = await run(() => { const h = window.__v.highlight("U1"); const r = h.meshes.map(m => m.name); h.clear(); return r; });+  assert(JSON.stringify(group) === '["U1_body"]', `a transform node lights the meshes under it (${group})`);++  section("highlight: stacking");+  const stack = await run(() => {+    const v = window.__v, p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");+    const c = (m) => [...m.overlayColor.asArray().map(x => +x.toFixed(2)), +m.overlayAlpha.toFixed(2), !!m.renderOverlay];+    const a = v.highlight(/^pad_/, { color: "#ff0000" });+    const b = v.highlight("pad_7", { color: [0, 1, 0], alpha: 0.5 });+    const both = [c(p7), c(p17)];+    b.clear();+    const afterB = c(p7);+    a.clear();+    const afterA = [c(p7), c(p17)];+    const x = v.highlight("pad_7"), y = v.highlight("U1");+    v.clearHighlight();+    let staleOk = true;+    try { x.clear(); y.clear(); } catch { staleOk = false; }+    return { both, afterB, afterA, cleared: [!!p7.renderOverlay, !!window.__mesh("U1_body").renderOverlay], staleOk };+  });+  assert(JSON.stringify(stack.both[0]) === "[0,1,0,0.5,true]" && JSON.stringify(stack.both[1]) === "[1,0,0,0.75,true]", `where two highlights share a mesh the later shows (${JSON.stringify(stack.both)})`);+  assert(JSON.stringify(stack.afterB) === "[1,0,0,0.75,true]", `clearing the later one brings back the one beneath (${stack.afterB})`);+  assert(stack.afterA[0][4] === false && stack.afterA[1][4] === false, "clearing both leaves nothing lit");+  assert(stack.cleared.every(on => on === false), "clearHighlight() removes every highlight");+  assert(stack.staleOk, "clear() on a highlight already removed does nothing");++  section("highlight: outline");+  const outline = await run(async () => {+    const v = window.__v, s = v.getScene(), p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");+    const o = v.highlight("pad_17", { mode: "outline", color: "#ffaa00" });+    const layer = s.effectLayers.find(l => l.name === "a3d-highlight");+    const r = { layer: !!layer, has: !!layer && layer.hasMesh(p17), overlay: !!p17.renderOverlay };+    await new Promise(res => { let n = 0; const ob = s.onAfterRenderObservable.add(() => { if (++n >= 3) { s.onAfterRenderObservable.remove(ob); res(); } }); });+    o.clear();+    r.afterClear = layer.hasMesh(p17);+    const out = v.highlight("pad_7", { mode: "outline" });+    const over = v.highlight("pad_7");+    r.overlayOnTop = [!!p7.renderOverlay, layer.hasMesh(p7)];+    over.clear();+    r.outlineBack = [!!p7.renderOverlay, layer.hasMesh(p7)];+    out.clear();+    return r;+  });+  assert(outline.layer && outline.has && outline.overlay === false, "mode outline draws the mesh in the viewer's highlight layer, without an overlay");+  assert(outline.afterClear === false, "clear() takes it out of the layer");+  assert(JSON.stringify(outline.overlayOnTop) === "[true,false]" && JSON.stringify(outline.outlineBack) === "[false,true]", `an overlay over an outline shows, and clearing it brings the outline back (${JSON.stringify(outline)})`);+  const bad = await run(() => ["glow", "red", 2].map((x, i) => {+    try { window.__v.highlight("pad_7", i === 0 ? { mode: x } : i === 1 ? { color: x } : { alpha: x }); return null; } catch (e) { return e.message; }+  }));+  assert(bad.every(Boolean), `an unknown mode, a color name and alpha 2 throw (${bad.join(" | ")})`);+  await run(() => window.__v.clearHighlight());++  section("pick");+  const P7 = await run(() => window.__at("pad_7"));+  const BODY = await run(() => window.__at("U1_body"));+  assert(!!P7 && !!BODY, `pad_7 and U1_body are on screen (${JSON.stringify(P7)} ${JSON.stringify(BODY)})`);+  await run(() => {+    window.__picks = [];+    window.__thrown = 0;+    window.__offThrow = window.__v.on("pick", () => { window.__thrown++; throw new Error("listener bug"); });+    window.__offPick = window.__v.on("pick", (e) => window.__picks.push({ name: e.mesh ? e.mesh.name : null, path: e.path, point: e.point, button: e.button, x: e.x, y: e.y }));+  });+  await page.mouse.click(P7.x, P7.y);+  await waitFor("window.__picks.length >= 1", 5000);+  await page.mouse.click(BODY.x, BODY.y);+  await waitFor("window.__picks.length >= 2", 5000);+  await page.mouse.click(30, 370);+  await waitFor("window.__picks.length >= 3", 5000);+  const picks = await run(() => ({ picks: window.__picks, thrown: window.__thrown }));+  const [p1, p2, p3] = picks.picks;+  assert(p1 && p1.name === "pad_7" && JSON.stringify(p1.path) === '["pad_7"]' && p1.button === 0, `a click on pad_7 picks it (${JSON.stringify(p1)})`);+  assert(p1 && Array.isArray(p1.point) && p1.point.length === 3 && p1.point.every(Number.isFinite) && Math.abs(p1.x - P7.x) < 1 && Math.abs(p1.y - P7.y) < 1, "the pick carries the world point and the canvas position");+  assert(p2 && p2.name === "U1_body" && JSON.stringify(p2.path) === '["U1","U1_body"]', `the path runs from the model root down (${p2 && JSON.stringify(p2.path)})`);+  assert(p3 && p3.name === null && p3.path.length === 0 && p3.point === null, `a click on empty space picks null (${JSON.stringify(p3)})`);+  assert(picks.thrown === 3, "a listener that throws does not stop the others");+  await page.mouse.move(P7.x, P7.y);+  await page.mouse.down();+  for (let i = 1; i <= 8; i++) await page.mouse.move(P7.x + i * 6, P7.y + i * 2);+  await page.mouse.up();+  await pause(400);+  assert(await run(() => window.__picks.length) === 3, "a drag is not a pick");++  section("hover");+  await run(() => { window.__hovers = []; window.__offHover = window.__v.on("hover", (e) => window.__hovers.push(e.mesh ? e.mesh.name : null)); });+  // Settle on empty space first so the next move is a change.+  await page.mouse.move(30, 370); await pause(200);+  await run(() => { window.__hovers = []; });+  await page.mouse.move(P7.x, P7.y);+  const h1 = await waitFor("window.__hovers[window.__hovers.length - 1] === 'pad_7'", 5000);+  await pause(150);+  await page.mouse.move(P7.x + 2, P7.y + 1);+  await pause(300);+  const sameCount = await run(() => window.__hovers.length);+  await page.mouse.move(BODY.x, BODY.y);+  const h2 = await waitFor("window.__hovers[window.__hovers.length - 1] === 'U1_body'", 5000);+  await pause(150);+  await page.mouse.move(30, 370);+  const h3 = await waitFor("window.__hovers[window.__hovers.length - 1] === null", 5000);+  const hovers = await run(() => window.__hovers);+  assert(h1, `moving onto pad_7 fires hover (${hovers})`);+  assert(sameCount === 1, `moving within the same mesh fires nothing more (${sameCount} events)`);+  assert(h2 && h3, `moving to another mesh, then off content, fires each change (${hovers.join(", ")})`);+  await run(() => window.__offHover());++  section("the view cube's corner and removed listeners");+  // The cube sits in the top-right corner; aim at its middle.+  const cube = await run(() => { const c = window.__v.getEngine().getRenderingCanvas(); return { x: c.clientWidth - 50, y: 50 }; });+  const before = await run(() => window.__picks.length);+  await page.mouse.click(cube.x, cube.y);+  await pause(400);+  assert(await run(() => window.__picks.length) === before, "a click in the view cube's corner is not a pick");+  await run(() => { window.__offPick(); window.__offThrow(); });+  await page.mouse.click(30, 370);+  await pause(400);+  assert(await run(() => window.__picks.length) === before, "a removed listener hears nothing");+  const unknown = await run(() => { try { window.__v.on("click", () => {}); return null; } catch (e) { return e.message; } });+  assert(!!unknown, `an unknown event name throws (${unknown})`);++  section("highlights across a model reload");+  const reload = await run(async () => {+    const v = window.__v;+    const h = v.highlight("pad_7");+    v.clearScene();+    let ok = true;+    try { h.clear(); v.clearHighlight(); } catch { ok = false; }+    const gone = v.findNodes(/^pad_/).length;+    await v.loadModel("/parts.glb");+    const again = v.highlight("pad_7");+    return { ok, gone, again: again.meshes.length, on: window.__mesh("pad_7").renderOverlay };+  });+  assert(reload.ok && reload.gone === 0, "clearing a highlight whose model was cleared does nothing");+  assert(reload.again === 1 && reload.on, "the reloaded model highlights again");++  section("picks on a 2x display");+  const hi = await browser.newPage();+  hi.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));+  await hi.setViewport({ width: 640, height: 400, deviceScaleFactor: 2 });+  await hi.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });+  await hi.waitForFunction("window.__ready === true", { timeout: 90000 });+  const backing = await hi.evaluate(() => { const c = window.__v.getEngine().getRenderingCanvas(); return [c.width, c.clientWidth]; });+  assert(backing[0] === backing[1] * 2, `the canvas renders at 2x (${backing[0]} for ${backing[1]} CSS pixels)`);+  const P7hi = await hi.evaluate(() => window.__at("pad_7"));+  await hi.evaluate(() => { window.__picks = []; window.__v.on("pick", (e) => window.__picks.push({ name: e.mesh ? e.mesh.name : null, x: e.x, y: e.y })); });+  await hi.mouse.click(P7hi.x, P7hi.y);+  await hi.waitForFunction("window.__picks.length >= 1", { timeout: 5000, polling: 100 }).catch(() => {});+  const hiPick = await hi.evaluate(() => window.__picks[0]);+  assert(hiPick && hiPick.name === "pad_7" && Math.abs(hiPick.x - P7hi.x) < 1 && Math.abs(hiPick.y - P7hi.y) < 1, `a click on pad_7 picks it, in CSS pixels (${JSON.stringify(hiPick)})`);+  await hi.mouse.click(640 - 50, 50);+  await pause(400);+  assert(await hi.evaluate(() => window.__picks.length) === 1, "a click in the view cube's corner is not a pick");+  await hi.close();++  assert(pageErrors.length === 0, `no page or console errors (${pageErrors.join(" | ") || "none"})`);+} finally {+  await browser.close();+  server.close();+}+console.log(`\n${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }
test/viewcube.test.mjs+52−4
@@ -60,6 +60,20 @@ const HARNESS = `<!doctype html><html><head><meta charset="utf-8">   window.__viewer = v;   window.__cam = () => { const c = v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius }; };   window.__setPose = (a, b) => { const c = v.getCamera(); c.alpha = a; c.beta = b; c.inertialAlphaOffset = 0; c.inertialBetaOffset = 0; };+  // Resolves once the camera has no animation, no inertia and the same pose+  // for five rendered frames in a row. Counted in frames, not milliseconds,+  // so a slow machine waits longer instead of reading the pose mid-move.+  window.__settled = () => new Promise(resolve => {+    const s = v.getScene(), c = v.getCamera();+    let last = '', still = 0;+    const o = s.onAfterRenderObservable.add(() => {+      const pose = [c.alpha, c.beta, c.radius].map(x => x.toFixed(5)).join();+      const busy = s.getAllAnimatablesByTarget(c).length > 0 || c.inertialAlphaOffset !== 0 || c.inertialBetaOffset !== 0 || c.inertialRadiusOffset !== 0;+      still = !busy && pose === last ? still + 1 : 0;+      last = pose;+      if (still >= 5) { s.onAfterRenderObservable.remove(o); resolve(); }+    });+  });   window.__ready = true; </script></body></html>`; @@ -90,14 +104,19 @@ const browser = await puppeteer.launch({   args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"], }); +// The camera once any animation and inertia have run out (see __settled).+async function settled(page) {+  await page.evaluate(() => window.__settled());+  return page.evaluate(() => window.__cam());+}+ // Press at (x, y), move by dx in steps, release; then let inertia settle. async function drag(page, x, y, dx, steps = 10) {   await page.mouse.move(x, y);   await page.mouse.down();   for (let i = 1; i <= steps; i++) { await page.mouse.move(x + (dx * i) / steps, y); await sleep(25); }   await page.mouse.up();-  await sleep(900);-  return page.evaluate(() => window.__cam());+  return settled(page); } const START = { alpha: 0.7, beta: 1.2 }; const wrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));@@ -142,8 +161,7 @@ try {   const held = await page.evaluate(() => window.__cam());   assert(Math.abs(wrap(held.alpha - START.alpha)) < 0.02 && Math.abs(held.beta - START.beta) < 0.02, `nothing moves while the button is held (${held.alpha.toFixed(3)}, ${held.beta.toFixed(3)})`);   await page.mouse.up();-  await sleep(900);-  const clicked = await page.evaluate(() => window.__cam());+  const clicked = await settled(page);   const movedBy = Math.abs(wrap(clicked.alpha - START.alpha)) + Math.abs(clicked.beta - START.beta);   assert(movedBy > 0.15, `the release animates the camera to the face (moved ${movedBy.toFixed(3)} rad)`);   // Face poses are axis-aligned in beta (0, PI/2, PI) or on a 45-degree edge/corner.@@ -160,6 +178,36 @@ try {   const wbOnGrid = [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI].some(g => Math.abs(wandered.beta - g) < 0.01);   assert(!wbOnGrid || Math.abs(wandered.beta - START.beta) < 0.1, `no snap animation ran (beta ${wandered.beta.toFixed(3)})`); +  section("hover and camera moves leave every cube colour where it started");+  // The cube's particle colours, as written to its mesh.+  const colours = () => page.evaluate(() => {+    const m = window.__viewer.getScene().getEngine().scenes.map(s => s.getMeshByName("viewCubeSPS")).find(Boolean);+    return m ? Array.from(m.getVerticesData("color") || []) : [];+  });+  const sameAs = (a, b) => a.length === b.length && a.length > 0 && a.every((x, i) => Math.abs(x - b[i]) < 1e-6);+  await page.mouse.move(model.x, model.y);+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(500);+  const before = await colours();+  assert(before.length > 0, `the cube mesh carries colours (${before.length} values)`);+  await page.mouse.move(cube.x, cube.y);+  await sleep(300);+  const hovered = await colours();+  assert(!sameAs(hovered, before), "hovering a face changes its colour");+  for (const pose of [{ alpha: 1.6, beta: 0.9 }, { alpha: -0.4, beta: 1.5 }, START]) {+    await page.evaluate((s) => window.__setPose(s.alpha, s.beta), pose);+    await sleep(250);+  }+  await page.mouse.move(model.x, model.y);+  await sleep(300);+  for (let i = 0; i < 3; i++) {+    await page.mouse.move(cube.x, cube.y); await sleep(150);+    await page.mouse.move(model.x, model.y); await sleep(150);+  }+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(500);+  assert(sameAs(await colours(), before), "after hovering, moving the camera under the pointer, and leaving, every colour is back to its value at the start");+   assert(errors.length === 0, `no page errors (${errors.join("; ").slice(0, 200)})`);   await page.close();  }