← Commit history
docs/CONTENT-CONVENTIONS.md+54
@@ -110,6 +110,60 @@ Notes that matter in practice: - Shadows only darken direct light. If you re-light a scene, keep the spot   dominant (env as fill, ~0.35 intensity) or shadows wash out on PBR surfaces. +## Lights inside the GLB, and switchable groups++A GLB may carry its own lights (`KHR_lights_punctual`). John's LED component+models do: `Adom.LED.State` holds the emissive lens skin and a real spot light,+`Adom.LaserEtch.MPN` holds the part number, each node carrying+`extras.adomRole` (adom/adom-3d-viewer#7, viewer 0.8.0).++### What the viewer does with them++- **Never rescales them.** glTF light `range` is metres and `intensity`+  candela, and neither follows a node matrix. The viewer frames with the+  camera, never by scaling content, so an authored 15 mm throw stays 15 mm. A+  light sitting under a scaled node gets a console warning naming the scale:+  that file is wrong, and only its author can fix it.+- **Budgets them.** Babylon lights a surface with at most+  `maxSimultaneousLights`, and the viewer's own key and fill lights already+  take three, so forty lit LEDs cannot all light the board. The nearest and+  brightest `lightBudget` (default 4) stay on and follow the camera; the rest+  stay emissive-only, which is what a real board looks like anyway. Set it at+  init (`lightBudget: 8`) or live (`setLightBudget(n)`); `0` leaves them all+  off. The emissive skins are geometry and never dim.+- **Casts no shadows from them.** One shadow generator per LED does not scale;+  the ground shadow stays the viewer's own key light.+- **One light per placement.** A board that references the same LED file forty+  times gets forty independent lights, each switching with its own group.++### Declaring a switchable group++Put `extras.adomRole` on the group's node, or name the node `Adom.<Something>`:++```json+{ "name": "Adom.LED.State",+  "extras": { "adomRole": "led-state", "defaultEnabled": true },+  "children": [ ...the lens skin..., ...the light node... ] }+```++| Field | Meaning |+|-------|---------|+| `adomRole` | Groups every placement of the same thing under one toggle. The row's key. |+| `defaultEnabled` | `false` starts the group switched off. |++The **outermost** declaring node wins: declare on `Adom.LED.State` and its+`Adom.LED.Emission` and `Adom.LED.Light` children ride with it, so one toggle+turns the lens and its light off together. Rows appear in the Layers panel+under "Parts", one per role, with the placement count when there are several.+A person's choice is remembered per browser, like the other viewer settings.++The API: `getStateGroups()`, `setStateGroupEnabled(key, on)` for every+placement of a role, `setStateInstanceEnabled(key, index, on)` for one of them,+and `getContentLights()` for what the file brought, as authored.++Layers (above) and state groups are different tools: a layer hides meshes, a+state group switches a whole subtree including its lights.+ ## Verifying lighting/shadow changes (John's protocol)  Freeze the scene, verify twice, hide the ground, then pixel-diff two
package.json+39−6
@@ -3,7 +3,44 @@   "version": "0.8.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/wiki-sandbox.test.mjs && node test/orbit.test.mjs && node test/viewcube.test.mjs && node test/help.test.mjs && node test/lights.test.mjs",+    "test:viewcube": "node test/viewcube.test.mjs",+    "test:help": "node test/help.test.mjs",+    "test:lights": "node test/lights.test.mjs"+  },   "dependencies": {},+  "devDependencies": {+    "@sveltejs/vite-plugin-svelte": "^3.1.2",+    "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 +74,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"-  }-}\ No newline at end of file+  "title": "Adom 3D Viewer"+}
src/ThreeDViewer.svelte+182−1
@@ -9,6 +9,8 @@     import type { Mesh } from '@babylonjs/core/Meshes/mesh';     import { AdomStatics } from './lib/adom-babylon/AdomStatics';     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 } from './lib/adom-babylon/util/prefs';@@ -23,6 +25,9 @@     export let modelUrl: string | undefined = undefined;     export let showViewCube: boolean = true;     export let showGround: boolean = false;+    /** 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;     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@@ -324,6 +329,22 @@     let layers: DetectedLayer[] = [];     let layersPanelOpen = false; +    // Lights that came inside the GLB (adom/adom-3d-viewer#7). The budget+    // keeps a forty-LED board renderable; the photometry is never touched.+    let contentLights: ContentLights | null = null;+    // State groups: a node carrying extras.adomRole, or named Adom.<Something>,+    // is a switchable group (Adom.LED.State holds the lens skin AND its light,+    // Adom.LaserEtch.MPN the part number). Toggling calls setEnabled on the+    // group root, so the light goes with the geometry. Rows aggregate by role,+    // one row per role with every placement behind it; per-placement control is+    // the API's setStateInstanceEnabled.+    type StateGroup = {+        key: string; label: string; role: string | null;+        roots: any[]; enabled: boolean; defaultEnabled: boolean;+    };+    let stateGroups: StateGroup[] = [];+    const STATE_PREF = (key: string) => `a3d.state.${key}`;+     /** A declared layer, from glTF extras or the built-in vocabulary. */     type LayerSpec = { key: string; label?: string; group?: string; hidden?: boolean };     type DetectedLayer = {@@ -453,6 +474,110 @@         if (layer) setLayerVisible(name, !layer.visible);     } +    /** "Adom.LED.State" -> "LED State"; "mpn-marking" -> "Mpn marking". */+    function stateLabel(name: string, role: string | null): string {+        const base = (name || role || '').replace(/^Adom\./i, '').replace(/[._]+/g, ' ').trim();+        const spaced = base.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/\s+/g, ' ').trim();+        if (spaced) return spaced.charAt(0).toUpperCase() + spaced.slice(1);+        return (role || 'Group');+    }++    /** Is this node a switchable content group? */+    function stateRoleFor(node: any): { role: string | null; defaultEnabled: boolean } | null {+        const extras = node?.metadata?.gltf?.extras;+        const role = typeof extras?.adomRole === 'string' && extras.adomRole.trim()+            ? extras.adomRole.trim().slice(0, 64) : null;+        const named = typeof node?.name === 'string' && /^Adom\.[A-Za-z0-9._-]+$/.test(node.name);+        if (!role && !named) return null;+        return { role, defaultEnabled: extras?.defaultEnabled !== false };+    }++    /**+     * Collect switchable groups TOP-DOWN, not bottom-up: the outermost Adom.*+     * node is the switch a person wants (Adom.LED.State turns the lens and the+     * light off together), so its children (Adom.LED.Emission, Adom.LED.Light)+     * must not each become their own row.+     */+    function detectStateGroups(): void {+        const byKey = new Map<string, StateGroup>();+        for (const root of loadedRootNodes) {+            const visit = (node: any) => {+                const hit = stateRoleFor(node);+                if (hit) {+                    const key = hit.role || String(node.name || '');+                    const existing = byKey.get(key);+                    if (existing) { existing.roots.push(node); existing.defaultEnabled = existing.defaultEnabled && hit.defaultEnabled; }+                    else byKey.set(key, { key, label: stateLabel(node.name, hit.role), role: hit.role, roots: [node], enabled: hit.defaultEnabled, defaultEnabled: hit.defaultEnabled });+                    return; // the group owns its subtree+                }+                (node.getChildren?.() || []).forEach(visit);+            };+            visit(root);+        }+        stateGroups = [...byKey.values()].map(g => {+            // A person's choice outlives the page, like every other viewer pref.+            const saved = getPref(STATE_PREF(g.key));+            const enabled = saved === '1' ? true : saved === '0' ? false : g.defaultEnabled;+            g.enabled = enabled;+            g.roots.forEach(r => r.setEnabled(enabled));+            return g;+        });+        contentLights?.invalidate();+    }++    export function getStateGroups(): { key: string; label: string; role: string | null; enabled: boolean; instances: { name: string; enabled: boolean }[] }[] {+        return stateGroups.map(g => ({+            key: g.key, label: g.label, role: g.role, enabled: g.enabled,+            instances: g.roots.map(r => ({ name: String(r.name || ''), enabled: !!r.isEnabled(false) })),+        }));+    }++    /** Switch every placement of a role (the panel row). */+    export function setStateGroupEnabled(key: string, enabled: boolean): boolean {+        const g = stateGroups.find(x => x.key === key);+        if (!g) return false;+        g.enabled = enabled;+        g.roots.forEach(r => r.setEnabled(enabled));+        setPref(STATE_PREF(key), enabled ? '1' : '0');+        stateGroups = stateGroups;+        contentLights?.invalidate();+        AdomStatics.refreshShadows();+        return true;+    }++    /** Switch ONE placement: the third LED on the board, not every LED. */+    export function setStateInstanceEnabled(key: string, index: number, enabled: boolean): boolean {+        const g = stateGroups.find(x => x.key === key);+        const root = g && g.roots[index];+        if (!root) return false;+        root.setEnabled(enabled);+        g.enabled = g.roots.some(r => r.isEnabled(false));+        stateGroups = stateGroups;+        contentLights?.invalidate();+        AdomStatics.refreshShadows();+        return true;+    }++    /** Lights the content brought with it, as authored (candela, metres). */+    export function getContentLights(): ContentLightRow[] {+        return contentLights ? contentLights.rows() : [];+    }++    /** How many content lights may light surfaces at once (default 4). */+    export function getLightBudget(): number {+        return contentLights ? contentLights.getBudget() : lightBudget;+    }++    export function setLightBudget(n: number): void {+        lightBudget = Math.max(0, Math.floor(Number(n) || 0));+        contentLights?.setBudget(lightBudget);+    }++    /** Turn every content light off (the emissive skins keep glowing), or back on. */+    export function setContentLightsEnabled(on: boolean): void {+        contentLights?.setEnabled(on);+    }+     // Orbit-center discoverability (#41): live indicator while shift+alt is     // held, plus a one-shot first-visit hint after the first model loads.     let pivotChordHeld = false;@@ -555,6 +680,9 @@                 zUp, showViewCube, environmentUrl, environmentBytes, environment, viewCubeCallbacks,                 onEnvironment: (s) => { envStatus = s; envResolve?.(s); },             });+            // 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);         } catch (e) {             // The rig failed: report instead of leaving the overlay up forever.             lastModelError = null;@@ -700,11 +828,46 @@             });             AdomStatics.refreshShadows();             detectLayers();+            adoptContentLights(result);+            detectStateGroups();             mitigateCoplanarFighting(result.meshes);             frameModel();         }     } +    /**+     * 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 metres and+     * intensity candela, and neither follows a node matrix, so a light inside+     * a 1000x group throws 1000x too short for the geometry around it. The+     * viewer does not "fix" that by rewriting the light; the file is wrong and+     * its author needs to know.+     */+    function adoptContentLights(result: any): void {+        if (!contentLights) return;+        const lights = (result.lights || []).filter((l: any) => !!l);+        if (!lights.length) return;+        const materials = [...new Set((result.meshes || []).map((m: any) => m.material).filter(Boolean))];+        contentLights.adopt(lights, materials as any[]);+        for (const l of lights) {+            let scale = 1;+            let n: any = l.parent;+            for (let d = 0; n && d < 12; d++) {+                const sc = n.scaling;+                if (sc) scale *= (Math.abs(sc.x) + Math.abs(sc.y) + Math.abs(sc.z)) / 3;+                n = n.parent;+            }+            if (Math.abs(scale - 1) > 0.01) {+                console.warn(+                    '[adom-3d-viewer] Light "' + l.name + '" sits under a node scaled ' + scale.toFixed(4) ++                    'x. glTF light range (' + l.range + ' m) and intensity (' + l.intensity ++                    ' cd) do not follow a node matrix, so this light lights the wrong distance. ' ++                    'Bake the scale into the geometry or author the light in world units.'+                );+            }+        }+    }+     /**      * PCB exports stack the board as nested shells (substrate, mask, copper,      * silk) separated by tens of microns, which z-fight at normal zoom.@@ -770,7 +933,12 @@     }      export function clearScene(): void {+        // Content lights hang off transform nodes, not meshes, so disposing the+        // mesh roots can leave them lighting the NEXT model. Dispose them here.+        contentLights?.clear();         loadedRootNodes.forEach((node) => node.dispose());+        for (const g of stateGroups) for (const r of g.roots) { try { r.dispose?.(false, true); } catch { /* already gone */ } }+        stateGroups = [];         loadedRootNodes = [];         layers = [];         layersPanelOpen = false;@@ -1312,7 +1480,7 @@         </div>     {/if} -    {#if layers.length > 0}+    {#if layers.length > 0 || stateGroups.length > 0}         <div class="layers-wrap" class:open={layersPanelOpen}>             <button                 class="layers-toggle"@@ -1324,6 +1492,19 @@             </button>             {#if layersPanelOpen}                 <div class="layers-panel">+                    {#if stateGroups.length > 0}+                        <div class="layers-group">Parts</div>+                        {#each stateGroups as group (group.key)}+                            <label class="layers-row">+                                <input+                                    type="checkbox"+                                    checked={group.enabled}+                                    on:change={() => setStateGroupEnabled(group.key, !group.enabled)}+                                />+                                <span>{group.label}{group.roots.length > 1 ? ` (${group.roots.length})` : ''}</span>+                            </label>+                        {/each}+                    {/if}                     {#each layerGroups(layers) as section (section.group ?? '_')}                         {#if section.group}                             <div class="layers-group">{section.group}</div>
src/lib/adom-babylon/3DViewer/ContentLights.tsadded+270
@@ -0,0 +1,270 @@+/**+ * Lights that arrive INSIDE a GLB (KHR_lights_punctual), as John's LED+ * component models now do: an Adom.LED.State group holding the emissive lens+ * skin and a real spot light (adom/adom-3d-viewer#7).+ *+ * The viewer never creates these and never edits their photometry: glTF range+ * is metres and intensity candela, and neither follows a node matrix, so a+ * viewer that rescaled them would turn a 15 mm throw into 15 m. What the+ * viewer owns is the BUDGET. Babylon's materials light at most+ * maxSimultaneousLights (4 by default, and the viewer's own key and fill+ * lights already take three of those), so a board with forty lit LEDs cannot+ * light every surface with every LED. Each frame's nearest and brightest N+ * content lights stay on; the rest go dark as lights while their emissive+ * lens keeps glowing, which is what a person sees on a real board anyway.+ *+ * Shadows stay off: one shadow generator per LED does not scale, and the+ * viewer's ground shadow comes from its own key light.+ */+import type { Scene } from '@babylonjs/core/scene';++type AnyLight = any;++export type ContentLightRow = {+    /** Node name from the GLB (e.g. Adom.LED.Light). */+    name: string;+    /** extras.adomRole on the light node or its parent, when the content set one. */+    role: string | null;+    /** As authored: candela and metres, never rescaled by the viewer. */+    intensity: number;+    range: number;+    /** The light's own switch (the budget turns this on and off). */+    enabled: boolean;+    /** Lit right now: its own switch AND every ancestor group enabled. */+    active: boolean;+    /** World position the budget scored it at. */+    position: { x: number; y: number; z: number };+};++type Item = {+    light: AnyLight;+    role: string | null;+    intensity: number;+    range: number;+    /** World position, resolved once (see refreshPositions). */+    x: number; y: number; z: number;+};++const DEFAULT_BUDGET = 4;+/** Ceiling for maxSimultaneousLights; past this, shaders pay for lights nobody sees. */+const MAX_MATERIAL_LIGHTS = 8;++function roleOf(light: AnyLight): string | null {+    let n: any = light;+    for (let depth = 0; n && depth < 3; depth++) {+        const r = n.metadata?.gltf?.extras?.adomRole;+        if (typeof r === 'string' && r.trim()) return r.trim().slice(0, 64);+        n = n.parent;+    }+    return null;+}++/** Ancestors enabled? (a light inside a switched-off state group is not lit). */+function ancestorsEnabled(light: AnyLight): boolean {+    let n: any = light.parent;+    for (let depth = 0; n && depth < 12; depth++) {+        if (n.isEnabled && n.isEnabled(false) === false) return false;+        n = n.parent;+    }+    return true;+}++export class ContentLights {+    private scene: Scene;+    private items: Item[] = [];+    private budget = DEFAULT_BUDGET;+    private viewerLightCount = 0;+    private observer: any = null;+    private lastRunAt = 0;+    private lastCamKey = '';+    private dirty = true;++    constructor(scene: Scene, budget?: number) {+        this.scene = scene;+        // The lights already in the scene when we start are the viewer's own+        // (key, fill, bottom); everything adopted later is content.+        this.viewerLightCount = scene.lights ? scene.lights.length : 0;+        if (typeof budget === 'number') this.budget = Math.max(0, Math.floor(budget));+    }++    /** Take the lights an import produced. Photometry is left exactly as authored. */+    adopt(lights: AnyLight[] | undefined | null, materials?: any[]): void {+        for (const light of lights || []) {+            if (!light || this.items.some(i => i.light === light)) continue;+            // #2: no per-LED shadows. Any generator attached later is the+            // caller's deliberate choice.+            light.shadowEnabled = false;+            this.items.push({+                light,+                role: roleOf(light),+                intensity: typeof light.intensity === 'number' ? light.intensity : 0,+                range: typeof light.range === 'number' ? light.range : 0,+                x: 0, y: 0, z: 0,+            });+        }+        this.refreshPositions();+        this.applyMaterialBudget(materials);+        this.dirty = true;+        this.update(true);+        this.attach();+    }++    /** Raise the per-material light cap to fit the viewer's lights plus the budget. */+    applyMaterialBudget(materials?: any[]): void {+        if (!this.items.length) return;+        const want = Math.min(this.viewerLightCount + this.budget, MAX_MATERIAL_LIGHTS);+        const list = materials && materials.length ? materials : (this.scene.materials || []);+        for (const m of list) {+            if (!m || typeof m.maxSimultaneousLights !== 'number') continue;+            if (m.maxSimultaneousLights < want) m.maxSimultaneousLights = want;+        }+    }++    private attach(): void {+        if (this.observer || !this.items.length) return;+        this.observer = this.scene.onBeforeRenderObservable.add(() => this.update(false));+    }++    detach(): void {+        if (this.observer) {+            this.scene.onBeforeRenderObservable.remove(this.observer);+            this.observer = null;+        }+    }++    /**+     * Dispose every adopted light and forget them. Content lights hang off+     * transform nodes rather than meshes, so disposing the mesh roots alone+     * leaves them in the scene lighting the NEXT model.+     */+    clear(): void {+        this.detach();+        for (const i of this.items) { try { i.light.dispose(); } catch { /* already gone */ } }+        this.items = [];+        this.lastCamKey = '';+        this.dirty = true;+    }++    count(): number { return this.items.length; }+    getBudget(): number { return this.budget; }++    setBudget(n: number): void {+        const next = Math.max(0, Math.floor(Number(n) || 0));+        if (next === this.budget) return;+        this.budget = next;+        this.applyMaterialBudget();+        this.dirty = true;+        this.update(true);+    }++    /** Switch every content light off (or back to budgeted behavior). */+    setEnabled(on: boolean): void {+        if (!on) {+            this.detach();+            for (const i of this.items) i.light.setEnabled(false);+            return;+        }+        this.dirty = true;+        this.update(true);+        this.attach();+    }++    /**+     * Resolve each light's world position. A transform node whose only child+     * is a light never gets its world matrix computed by the render loop (no+     * geometry hangs off it), so getAbsolutePosition would report the origin+     * for every LED on the board and the budget would pick arbitrarily.+     * Positions are static for a static model; call this again after moving+     * content.+     */+    refreshPositions(): void {+        for (const i of this.items) {+            try {+                let n: any = i.light.parent;+                const chain: any[] = [];+                for (let d = 0; n && d < 12; d++) { chain.push(n); n = n.parent; }+                for (let k = chain.length - 1; k >= 0; k--) chain[k].computeWorldMatrix?.(true);+                // Not getAbsolutePosition(): a Light only refreshes its+                // transformed position while it is being rendered, so a light+                // the budget switched off would report the origin forever and+                // could never win its way back on. Transform the local+                // position by the parent's world matrix ourselves.+                const lp = i.light.position || { x: 0, y: 0, z: 0 };+                const parent: any = i.light.parent;+                const m = parent && parent.getWorldMatrix ? parent.getWorldMatrix().m : null;+                if (m) {+                    i.x = lp.x * m[0] + lp.y * m[4] + lp.z * m[8] + m[12];+                    i.y = lp.x * m[1] + lp.y * m[5] + lp.z * m[9] + m[13];+                    i.z = lp.x * m[2] + lp.y * m[6] + lp.z * m[10] + m[14];+                } else { i.x = lp.x; i.y = lp.y; i.z = lp.z; }+            } catch { /* leave it at the origin */ }+        }+    }++    /** Note that something changed (a group toggled, a model loaded). */+    invalidate(): void { this.dirty = true; }++    /**+     * Enable the nearest and brightest `budget` lights, disable the rest.+     * Cheap: skipped entirely while the camera is still and nothing changed,+     * and a no-op when the content has no more lights than the budget.+     */+    update(force: boolean): void {+        if (!this.items.length) return;+        const cam: any = this.scene.activeCamera;+        const now = Date.now();+        if (!force) {+            if (now - this.lastRunAt < 100) return;+            // The TARGET belongs in the key as much as the position: an orbit+            // camera re-aimed at the far end of a board keeps its position and+            // would otherwise never re-score.+            const p = cam?.position, t = cam?.target;+            const key = cam+                ? `${p?.x?.toFixed(5)},${p?.y?.toFixed(5)},${p?.z?.toFixed(5)}|${t?.x?.toFixed(5)},${t?.y?.toFixed(5)},${t?.z?.toFixed(5)}`+                : '';+            if (!this.dirty && key === this.lastCamKey) return;+            this.lastCamKey = key;+        }+        this.lastRunAt = now;+        this.dirty = false;++        // Under budget: every light stays on, no scoring at all.+        if (this.items.length <= this.budget) {+            for (const i of this.items) i.light.setEnabled(true);+            return;+        }+        if (this.budget === 0) {+            for (const i of this.items) i.light.setEnabled(false);+            return;+        }+        const focus = (cam && (cam.target || cam.position)) || null;+        const scored = this.items.map(i => {+            if (!ancestorsEnabled(i.light)) return { i, score: -1 };+            let d2 = 0;+            if (focus) {+                const dx = i.x - focus.x, dy = i.y - focus.y, dz = i.z - focus.z;+                d2 = dx * dx + dy * dy + dz * dz;+            }+            // Brightness falling off with distance: the LED you are looking at+            // wins over a brighter one across the board.+            return { i, score: (i.intensity || 1e-9) / (d2 + 1e-12) };+        });+        scored.sort((a, b) => b.score - a.score);+        for (let k = 0; k < scored.length; k++) {+            const on = scored[k].score >= 0 && k < this.budget;+            if (scored[k].i.light.isEnabled(false) !== on) scored[k].i.light.setEnabled(on);+        }+    }++    rows(): ContentLightRow[] {+        return this.items.map(i => ({+            name: i.light.name,+            role: i.role,+            intensity: i.intensity,+            range: i.range,+            enabled: !!i.light.isEnabled(false),+            active: !!i.light.isEnabled(true),+            position: { x: i.x, y: i.y, z: i.z },+        }));+    }+}
standalone.ts+27
@@ -77,6 +77,21 @@ interface ViewerInstance {    *  content asked for the layer rather than matching the built-in names. */   getLayers: () => { name: string; label: string; group: string | null; visible: boolean; declared: boolean }[];   setLayerVisible: (name: string, visible: boolean) => 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+   *  it (adom/adom-3d-viewer#7). */+  getStateGroups: () => { key: string; label: string; role: string | null; enabled: boolean; instances: { name: string; enabled: boolean }[] }[];+  setStateGroupEnabled: (key: string, enabled: boolean) => boolean;+  /** One placement of a role: the third LED on the board, not every LED. */+  setStateInstanceEnabled: (key: string, index: number, enabled: boolean) => boolean;+  /** Lights that came inside the GLB, as authored (candela, metres). */+  getContentLights: () => { name: string; role: string | null; intensity: number; range: number; enabled: boolean; active: boolean }[];+  /** How many of them may light surfaces at once (default 4). */+  getLightBudget: () => number;+  setLightBudget: (n: number) => void;+  /** All content lights off (their emissive skins keep glowing), or back on. */+  setContentLightsEnabled: (on: boolean) => void;   /** Pin the shadow map refresh rate; null restores auto (adom/wiki#60 #7). */   setShadowRefreshRate: (rate: number | null) => void;   /** PNG data URL of the current view (adom/wiki#60 #9). */@@ -111,6 +126,10 @@ function init(container: HTMLElement, options?: {   /** The ? button and its controls card (default true). Set false when the    *  host draws its own help. The one-time Shift+Alt tip rides with it. */   showHelp?: boolean;+  /** How many lights carried INSIDE the GLB may light surfaces at once+   *  (default 4). A board with forty lit LEDs keeps the nearest and brightest+   *  this many; the rest stay emissive-only. 0 leaves them all off. */+  lightBudget?: number; }): ViewerInstance {   const opts = options || {}; @@ -128,6 +147,7 @@ function init(container: HTMLElement, options?: {       initialViewMode: opts.initialViewMode || 'perspective',       onMeshHover: opts.onMeshHover,       onGroundCreated: opts.onGroundCreated,+      lightBudget: opts.lightBudget !== undefined ? opts.lightBudget : 4,     },   }); @@ -164,6 +184,13 @@ function init(container: HTMLElement, options?: {     captureScreenshot: (o?: { width?: number; height?: number }) => component.captureScreenshot(o),     getLayers: () => component.getLayers(),     setLayerVisible: (name: string, visible: boolean) => component.setLayerVisible(name, visible),+    getStateGroups: () => component.getStateGroups(),+    setStateGroupEnabled: (key: string, enabled: boolean) => component.setStateGroupEnabled(key, enabled),+    setStateInstanceEnabled: (key: string, index: number, enabled: boolean) => component.setStateInstanceEnabled(key, index, enabled),+    getContentLights: () => component.getContentLights(),+    getLightBudget: () => component.getLightBudget(),+    setLightBudget: (n: number) => component.setLightBudget(n),+    setContentLightsEnabled: (on: boolean) => component.setContentLightsEnabled(on),     destroy: () => { help && help.destroy(); component.$destroy(); },   }; }
test/lights.test.mjsadded+268
@@ -0,0 +1,268 @@+// Lights carried INSIDE a GLB (adom/adom-3d-viewer#7). John's LED component+// models ship a KHR_lights_punctual spot inside an Adom.LED.State group with+// the emissive lens skin. The viewer budgets them (Babylon lights at most+// maxSimultaneousLights per material, and the rig already uses three), never+// rescales their photometry, keeps shadows off, gives every declared group a+// toggle, and treats each placement as its own light.+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, "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); } }+const eq = (a, b, msg) => assert(a === b, `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);+function section(t) { console.log("\n  [" + t + "]"); }++/**+ * A GLB with `count` LED placements. Every placement is an Adom.LED.State+ * group holding an emissive lens mesh and a light node; all of them REFERENCE+ * THE SAME glTF light index, which is what a board assembled from one LED file+ * looks like, and the case where a shared light object would switch every LED+ * at once. `parentScale` puts the whole thing under a scaled node.+ */+function makeLedGlb(count, { parentScale = null, spacing = 0.01 } = {}) {+  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.001, v[1] * 0.001, v[2] * 0.001)); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });+  const posBuf = Buffer.from(new Float32Array(pos).buffer), idxBuf = Buffer.from(new Uint16Array(idx).buffer);+  const bin = Buffer.concat([posBuf, idxBuf, Buffer.alloc((4 - (idxBuf.length % 4)) % 4)]);+  const nodes = [], sceneNodes = [];+  for (let i = 0; i < count; i++) {+    const state = nodes.length;+    nodes.push(null); // placeholder, filled after its children exist+    const lens = nodes.length;+    nodes.push({ name: "Adom.LED.Emission", mesh: 0, extras: { adomRole: "led-emission", defaultEnabled: true } });+    const light = nodes.length;+    nodes.push({ name: "Adom.LED.Light", extensions: { KHR_lights_punctual: { light: 0 } }, extras: { adomRole: "led-light" } });+    nodes[state] = { name: "Adom.LED.State", translation: [i * spacing, 0, 0], children: [lens, light], extras: { adomRole: "led-state", defaultEnabled: true } };+    sceneNodes.push(state);+  }+  // An MPN marking outside the LED groups: an independent toggle.+  const mpn = nodes.length;+  nodes.push({ name: "Adom.LaserEtch.MPN", mesh: 0, translation: [0, 0.004, 0], extras: { adomRole: "mpn-marking", defaultEnabled: true } });+  sceneNodes.push(mpn);+  let roots = sceneNodes;+  if (parentScale) {+    const wrap = nodes.length;+    nodes.push({ name: "scaled_group", scale: [parentScale, parentScale, parentScale], children: sceneNodes });+    roots = [wrap];+  }+  const json = {+    asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: roots }],+    extensionsUsed: ["KHR_lights_punctual"],+    extensions: { KHR_lights_punctual: { lights: [{ name: "Adom.LED.Light", type: "spot", color: [0, 1, 0.1], intensity: 0.000075, range: 0.015, spot: { innerConeAngle: 0.97, outerConeAngle: 1.48 } }] } },+    nodes,+    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],+    materials: [{ name: "Adom.LED.Emissive.green", pbrMetallicRoughness: { baseColorFactor: [0.2, 1, 0.3, 1] }, emissiveFactor: [0, 1, 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.001, -0.001, -0.001], max: [0.001, 0.001, 0.001] }, { 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 MODELS = {+  "/one.glb": makeLedGlb(1),+  "/two.glb": makeLedGlb(2),+  "/many.glb": makeLedGlb(8),+  "/scaled.glb": makeLedGlb(1, { parentScale: 1000 }),+};+const HARNESS = (model, budget) => `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#host{position:relative;width:640px;height:400px}#wrap{position:absolute;inset:0}</style></head><body><div id="host"><div id="wrap"></div></div>+<script type="module">+  await import('/adom-3d-viewer-babylon9.esm.js');+  const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showGround: false, showHelp: false, modelUrl: '${model}'${budget === undefined ? "" : `, lightBudget: ${budget}`} });+  await v.whenReady(); window.__viewer = v; 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") {+    const model = url.searchParams.get("model") || "/one.glb";+    const budget = url.searchParams.has("budget") ? Number(url.searchParams.get("budget")) : undefined;+    res.writeHead(200, { "Content-Type": "text/html" });+    return res.end(HARNESS(model, budget));+  }+  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"] });+const warnings = [];+async function open(query) {+  const page = await browser.newPage();+  page.on("console", m => { if (m.type() === "warning" || m.type() === "warn") warnings.push(m.text()); });+  await page.setViewport({ width: 640, height: 400 });+  await page.goto(`http://127.0.0.1:${port}/view.html?${query}`, { waitUntil: "load", timeout: 90000 });+  await page.waitForFunction("window.__ready === true", { timeout: 90000 });+  await new Promise(r => setTimeout(r, 600));+  return page;+}++try {+  section("the GLB's own light survives the import untouched");+  {+    const page = await open("model=/one.glb");+    const d = await page.evaluate(() => {+      const v = window.__viewer, s = v.getScene();+      return {+        lights: v.getContentLights(),+        sceneLights: s.lights.length,+        shadowEnabled: s.lights.filter(l => l.name === "Adom.LED.Light").map(l => l.shadowEnabled),+        contentMax: [...new Set(s.materials.filter(m => (m.name || "").startsWith("Adom.LED.Emissive")).map(m => m.maxSimultaneousLights))],+        budget: v.getLightBudget(),+      };+    });+    eq(d.lights.length, 1, "one content light");+    eq(d.lights[0].range, 0.015, "range is the authored 15 mm, not rescaled");+    eq(d.lights[0].intensity, 0.000075, "intensity is the authored candela");+    eq(d.lights[0].role, "led-light", "its adomRole is reported");+    eq(d.lights[0].active, true, "and it is lit");+    assert(d.shadowEnabled.every(x => x === false), "no per-LED shadows");+    eq(d.budget, 4, "default budget of 4");+    assert(d.contentMax.every(m => m >= 7), `content materials allow the viewer's lights plus the budget (got ${d.contentMax})`);+    await page.close();+  }++  section("a light under a scaled node is called out, never silently rescaled");+  {+    warnings.length = 0;+    const page = await open("model=/scaled.glb");+    const lights = await page.evaluate(() => window.__viewer.getContentLights());+    eq(lights[0].range, 0.015, "the viewer still does not touch the range");+    assert(warnings.some(w => /scaled 1000/.test(w) && /do not follow a node matrix/.test(w)), `the author is warned (${warnings.slice(0, 2).join(" | ")})`);+    await page.close();+  }++  section("each placement is its own light and its own switch");+  {+    const page = await open("model=/two.glb");+    const before = await page.evaluate(() => ({ states: window.__viewer.getStateGroups(), lights: window.__viewer.getContentLights() }));+    eq(before.lights.length, 2, "two placements sharing one glTF light index load as two lights");+    eq(before.states.length, 2, "two switchable roles: the LED state and the MPN");+    const led = before.states.find(g => g.key === "led-state");+    eq(led.label, "LED State", "the row is named after the group");+    eq(led.instances.length, 2, "with both placements behind it");+    const after = await page.evaluate(() => {+      window.__viewer.setStateInstanceEnabled("led-state", 0, false);+      return { lights: window.__viewer.getContentLights(), states: window.__viewer.getStateGroups() };+    });+    eq(after.lights.filter(l => l.active).length, 1, "switching one placement off leaves the other lit");+    eq(after.states.find(g => g.key === "led-state").instances.map(i => i.enabled).join(","), "false,true", "and only that placement is off");+    const both = await page.evaluate(() => {+      window.__viewer.setStateGroupEnabled("led-state", false);+      const geometryOff = window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LED.Emission")).every(m => !m.isEnabled());+      return { lit: window.__viewer.getContentLights().filter(l => l.active).length, geometryOff };+    });+    eq(both.lit, 0, "switching the role off takes every LED light with it");+    assert(both.geometryOff, "and the lens geometry goes with it");+    const mpn = await page.evaluate(() => {+      window.__viewer.setStateGroupEnabled("mpn-marking", false);+      return { mpnOff: window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LaserEtch.MPN")).every(m => !m.isEnabled()), lights: window.__viewer.getContentLights().length };+    });+    assert(mpn.mpnOff, "the MPN toggles independently");+    eq(mpn.lights, 2, "and touches no lights");+    await page.close();+  }++  section("the choice is remembered, like every other viewer preference");+  {+    const page = await open("model=/two.glb");+    const back = await page.evaluate(() => window.__viewer.getStateGroups().map(g => `${g.key}:${g.enabled}`).join(","));+    assert(/led-state:false/.test(back), `a group switched off in the last session comes back off (${back})`);+    await page.evaluate(() => { window.__viewer.setStateGroupEnabled("led-state", true); window.__viewer.setStateGroupEnabled("mpn-marking", true); });+    await page.close();+  }++  section("a board full of LEDs stays within the light budget");+  {+    const page = await open("model=/many.glb");+    const d = await page.evaluate(() => ({ lights: window.__viewer.getContentLights(), budget: window.__viewer.getLightBudget() }));+    eq(d.lights.length, 8, "eight placements");+    eq(d.lights.filter(l => l.active).length, d.budget, "only the budget is lit at once");+    assert(d.lights.every(l => l.range === 0.015), "the unlit ones keep their photometry (they are switched, not edited)");+    const two = await page.evaluate(() => { window.__viewer.setLightBudget(2); return window.__viewer.getContentLights().filter(l => l.active).length; });+    eq(two, 2, "a smaller budget lights fewer");+    const none = await page.evaluate(() => { window.__viewer.setContentLightsEnabled(false); return window.__viewer.getContentLights().filter(l => l.active).length; });+    eq(none, 0, "and they can all be switched off");+    const geometryStillThere = await page.evaluate(() => window.__viewer.getScene().meshes.filter(m => m.name.startsWith("Adom.LED.Emission")).every(m => m.isEnabled()));+    assert(geometryStillThere, "the emissive lenses keep glowing either way");+    await page.close();+  }++  section("the budget follows the camera");+  {+    const page = await open("model=/many.glb&budget=2");+    const d = await page.evaluate(async () => {+      const v = window.__viewer, cam = v.getCamera(), s = v.getScene();+      const lit = () => v.getContentLights().filter(l => l.active).map(l => +l.position.x.toFixed(4)).sort((a, b) => a - b);+      const xs = v.getContentLights().map(l => +l.position.x.toFixed(4)).sort((a, b) => a - b);+      const look = async (x) => {+        const t = cam.target.clone(); t.x = x; t.y = 0; t.z = 0; cam.setTarget(t);+        for (let i = 0; i < 4; i++) { s.render(); await new Promise(r => setTimeout(r, 140)); }+        return lit();+      };+      const near = await look(xs[0]);+      const far = await look(xs[xs.length - 1]);+      return { xs, near, far };+    });+    eq(d.near.length, 2, "two lit at a time");+    assert(d.near.join(",") !== d.far.join(","), `looking elsewhere lights different LEDs (${d.near} then ${d.far})`);+    assert(d.near.includes(d.xs[0]) && d.far.includes(d.xs[d.xs.length - 1]), `the LEDs nearest what you are looking at are the lit ones (${d.near} / ${d.far})`);+    await page.close();+  }++  section("loading another model does not leave the old lights behind");+  {+    const page = await open("model=/two.glb");+    const d = await page.evaluate(async () => {+      const v = window.__viewer;+      const before = v.getScene().lights.length;+      v.clearScene();+      const afterClear = v.getScene().lights.length;+      await v.loadModel("/one.glb");+      await new Promise(r => setTimeout(r, 300));+      return { before, afterClear, afterLoad: v.getContentLights().length, sceneLights: v.getScene().lights.length };+    });+    eq(d.afterClear, d.before - 2, "clearScene disposes the content lights");+    eq(d.afterLoad, 1, "the next model brings its own");+    eq(d.sceneLights, d.before - 1, "and nothing accumulates");+    await page.close();+  }++  section("a GLB with no lights is untouched");+  {+    const page = await open("model=/one.glb");+    const ok = await page.evaluate(() => {+      const v = window.__viewer;+      v.clearScene();+      return { lights: v.getContentLights().length, states: v.getStateGroups().length };+    });+    eq(ok.lights, 0, "no content lights after a clear");+    eq(ok.states, 0, "and no state rows");+    await page.close();+  }+} finally {+  await browser.close();+  server.close();+}+console.log(`\n=== content lights ===\n${passed} passed, ${failed} failed`);+if (failed) { console.log(failures.map(f => "  - " + f).join("\n")); process.exit(1); }