Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(glb-tools): add buildLodChain, a real multi-level LOD decimator with MSFT_lod
nirholas8408b655a082
diff --git a/packages/glb-tools/README.md b/packages/glb-tools/README.mdindex 9a8f9417c..366511851 100644--- a/packages/glb-tools/README.md+++ b/packages/glb-tools/README.md@@ -17,6 +17,7 @@<a href="#install">Install</a> ·<a href="#quick-start">Quick start</a> ·<a href="#api">API</a> ·+ <a href="#buildlodchainglb-options--promiselodchainresult">LOD chains</a> ·<a href="#how-it-works">How it works</a> ·<a href="#pricing">Pricing</a> ·<a href="https://three.ws">three.ws</a>@@ -64,9 +65,14 @@ functions instead of MCP tools.npm install @three-ws/glb-tools```-Zero runtime dependencies. Works in Node 18+, modern browsers, and CI runners-(uses `fetch`). To *generate* the GLBs you inspect, add-[`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge).+`inspect`, `theme`, `bake`, and the default import have zero runtime+dependencies: they work in Node 18+, modern browsers, and CI runners (uses+`fetch`). The one exception is [`buildLodChain()`](#buildlodchainglb-options--promiselodchainresult),+a Node.js-only local computation (no network call) that pulls in+`@gltf-transform/*`, `meshoptimizer`, and `draco3dgltf` to actually decimate+geometry; it's dynamically imported so calling only `inspect`/`theme`/`bake`+never adds that weight to a browser bundle. To *generate* the GLBs you+inspect, add [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge).## Quick start@@ -107,13 +113,32 @@ const baked = await bake('avatar_8f3a…', {console.log(baked.bakedStorageKey, baked.sizeBytes);```+Build a real, engine-ready LOD chain from a local GLB (Node.js only, no+network call):++```js+import { buildLodChain } from '@three-ws/glb-tools';+import { readFile, writeFile } from 'node:fs/promises';++const source = await readFile('character.glb');+const { source: stats, levels, combined } = await buildLodChain(source);++console.log(stats.triangleCount); // → 4672+levels.forEach((l) => console.log(l.name, l.triangleCount)); // LOD0 4672, LOD1 2336, LOD2 700++await writeFile('character.lod.glb', combined); // one file, MSFT_lod-tagged+await writeFile('character.lod0.glb', levels[0].glb); // discrete per-level files for+await writeFile('character.lod1.glb', levels[1].glb); // engines (Unity/Unreal/Godot+await writeFile('character.lod2.glb', levels[2].glb); // importers) that want them separate+```+## API-Public exports: `inspect`, `theme`, `bake`, `createGlbTools`, `ThreeWsError`,-`PaymentRequiredError`, and `DEFAULT_BASE_URL`. The three headline functions-use a shared zero-config client; `createGlbTools({ baseUrl, fetch, apiKey,-headers })` builds your own when you need a payment-aware fetch, an owner-token, or a custom origin reused across calls.+Public exports: `inspect`, `theme`, `bake`, `buildLodChain`, `createGlbTools`,+`ThreeWsError`, `PaymentRequiredError`, and `DEFAULT_BASE_URL`. The three+headline functions use a shared zero-config client; `createGlbTools({+baseUrl, fetch, apiKey, headers })` builds your own when you need a+payment-aware fetch, an owner token, or a custom origin reused across calls.### `inspect(url, options?) → Promise<InspectReport>`@@ -203,6 +228,49 @@ avatar fields, shaped to camelCase). An **empty / cleared** appearance clearsthe cached baked GLB (the base model is served again) and resolves with`bakedStorageKey: null` and `cleared: true`.+### `buildLodChain(glb, options?) → Promise<LodChainResult>`++Decimate a GLB into a real multi-level LOD chain, entirely locally (no+network call, no x402 charge). Runs gltf-transform's `simplify()`+(meshoptimizer's `MeshoptSimplifier` under the hood) at each requested ratio,+then wires the result two ways: a single **combined** GLB that carries every+level plus the archived [`MSFT_lod`](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/MSFT_lod)+extension (for engines that switch LOD at runtime from one file), and a+standalone GLB per level (for engines/importers that want discrete LOD files+on disk). A viewer that doesn't understand `MSFT_lod` renders the combined+file's `LOD0` only: the alternate levels are real nodes in the document but+excluded from the default scene's graph, so they're addressable, never+double-rendered.++**Input**: `glb` is a `Uint8Array` or `ArrayBuffer` containing a real GLB+(any valid glTF 2.0 binary; Draco- and meshopt-compressed inputs decode+transparently).++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `levels` | `Array<number \| { name?, ratio, error?, screenCoverage? }>` | 3 levels: `1`, `0.5`, `0.15` | 2-6 entries, highest detail first, strictly decreasing `ratio` in `(0, 1]`. A bare number is shorthand for `{ ratio }`. |++**Returns** `LodChainResult`++| Field | Type | Notes |+|---|---|---|+| `source.triangleCount` / `source.vertexCount` | `number` | The input mesh's own geometry, before any simplification. |+| `levels[]` | `LodLevelResult[]` | One entry per requested level, highest detail first. |+| `combined` | `Uint8Array` | Every level merged into one `MSFT_lod`-tagged GLB. |++Each `LodLevelResult` carries `name`, `ratio`, `error`, `screenCoverage`+(the switch threshold written to `MSFT_screencoverage`, or `null` when+omitted), `triangleCount`, `vertexCount`, and `glb` (a standalone GLB for+that level alone). `buildLodChain()` throws if the source has no triangle+geometry, or if a level comes out *less* decimated than the level before it+(raise that level's `error` tolerance or lower its `ratio`).++Only this one function needs the dependencies above: import it from the+package root (dynamically loaded) or from `@three-ws/glb-tools/lod` directly+in a Node-only module that wants a static import.+## How it worksThree independent endpoints, one client. None of the heavy lifting happens indiff --git a/packages/glb-tools/package.json b/packages/glb-tools/package.jsonindex 3d5a23ead..1099a6c60 100644--- a/packages/glb-tools/package.json+++ b/packages/glb-tools/package.json@@ -12,6 +12,11 @@"import": "./src/index.js","default": "./src/index.js"},+ "./lod": {+ "types": "./src/lod.d.ts",+ "import": "./src/lod.js",+ "default": "./src/lod.js"+ },"./package.json": "./package.json"},"files": [@@ -48,7 +53,13 @@"engines": {"node": ">=18"},- "dependencies": {},+ "dependencies": {+ "@gltf-transform/core": "^4.4.0",+ "@gltf-transform/extensions": "^4.4.0",+ "@gltf-transform/functions": "^4.5.0",+ "draco3dgltf": "^1.5.7",+ "meshoptimizer": "^1.2.0"+ },"publishConfig": {"access": "public"}diff --git a/packages/glb-tools/src/glb-container.js b/packages/glb-tools/src/glb-container.jsnew file mode 100644index 000000000..83bc389d8--- /dev/null+++ b/packages/glb-tools/src/glb-container.js@@ -0,0 +1,90 @@+// Minimal GLB 2.0 binary container reader/writer.+//+// gltf-transform's public Document API has no way to attach an unregistered+// extension (MSFT_lod is archived, not one of the extensions gltf-transform+// ships a class for), so buildLodChain() in lod.js writes its GLB with+// gltf-transform and then uses these two functions to patch the JSON chunk+// directly. Spec: https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/README.md#binary-gltf-layout++const GLB_MAGIC = 0x46546c67; // 'glTF'+const CHUNK_TYPE_JSON = 0x4e4f534a; // 'JSON'+const CHUNK_TYPE_BIN = 0x004e4942; // 'BIN\0'+const HEADER_BYTES = 12;+const CHUNK_HEADER_BYTES = 8;++/**+ * @param {Uint8Array} glb+ * @returns {{ json: object, binChunk: Uint8Array | null }}+ */+export function readGlbChunks(glb) {+ const buf = glb instanceof Uint8Array ? glb : new Uint8Array(glb);+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);+ if (buf.byteLength < HEADER_BYTES || view.getUint32(0, true) !== GLB_MAGIC) {+ throw new Error('readGlbChunks: not a GLB container (bad magic)');+ }+ const totalLength = view.getUint32(8, true);+ if (totalLength > buf.byteLength) {+ throw new Error('readGlbChunks: declared length exceeds buffer size');+ }++ let offset = HEADER_BYTES;+ let json = null;+ let binChunk = null;+ while (offset + CHUNK_HEADER_BYTES <= totalLength) {+ const chunkLength = view.getUint32(offset, true);+ const chunkType = view.getUint32(offset + 4, true);+ const chunkStart = offset + CHUNK_HEADER_BYTES;+ const chunkEnd = chunkStart + chunkLength;+ if (chunkEnd > totalLength) throw new Error('readGlbChunks: chunk overruns container');+ const chunkData = buf.subarray(chunkStart, chunkEnd);+ if (chunkType === CHUNK_TYPE_JSON) {+ json = JSON.parse(new TextDecoder('utf-8').decode(chunkData));+ } else if (chunkType === CHUNK_TYPE_BIN) {+ binChunk = chunkData;+ }+ offset = chunkEnd;+ }+ if (!json) throw new Error('readGlbChunks: no JSON chunk found');+ return { json, binChunk };+}++function pad4(buf, fillByte) {+ const remainder = buf.byteLength % 4;+ if (remainder === 0) return buf;+ const padded = new Uint8Array(buf.byteLength + (4 - remainder));+ padded.set(buf);+ padded.fill(fillByte, buf.byteLength);+ return padded;+}++/**+ * @param {{ json: object, binChunk?: Uint8Array | null }} parts+ * @returns {Uint8Array}+ */+export function writeGlb({ json, binChunk = null }) {+ const jsonBytes = pad4(new TextEncoder().encode(JSON.stringify(json)), 0x20); // space-pad JSON+ const binBytes = binChunk ? pad4(binChunk, 0x00) : null; // zero-pad BIN++ const totalLength =+ HEADER_BYTES + CHUNK_HEADER_BYTES + jsonBytes.byteLength + (binBytes ? CHUNK_HEADER_BYTES + binBytes.byteLength : 0);++ const out = new Uint8Array(totalLength);+ const view = new DataView(out.buffer);+ view.setUint32(0, GLB_MAGIC, true);+ view.setUint32(4, 2, true); // version+ view.setUint32(8, totalLength, true);++ let offset = HEADER_BYTES;+ view.setUint32(offset, jsonBytes.byteLength, true);+ view.setUint32(offset + 4, CHUNK_TYPE_JSON, true);+ out.set(jsonBytes, offset + CHUNK_HEADER_BYTES);+ offset += CHUNK_HEADER_BYTES + jsonBytes.byteLength;++ if (binBytes) {+ view.setUint32(offset, binBytes.byteLength, true);+ view.setUint32(offset + 4, CHUNK_TYPE_BIN, true);+ out.set(binBytes, offset + CHUNK_HEADER_BYTES);+ }++ return out;+}diff --git a/packages/glb-tools/src/index.d.ts b/packages/glb-tools/src/index.d.tsindex 9eaa60d11..795d07420 100644--- a/packages/glb-tools/src/index.d.ts+++ b/packages/glb-tools/src/index.d.ts@@ -164,3 +164,10 @@ export declare function createGlbTools(options?: GlbToolsClientOptions): GlbToolexport declare function inspect(url: string, opts?: InspectOptions): Promise<InspectReport>;export declare function theme(mint: string, opts?: ThemeOptions): Promise<ThemedMesh>;export declare function bake(avatarId: string, appearance: Appearance | null, opts?: BakeOptions): Promise<BakeResult>;++export type { LodLevelInput, LodLevelResult, LodChainResult } from './lod.js';+/** Node.js-only. See './lod.js' for the full contract and README.md#buildlodchain. */+export declare function buildLodChain(+ glb: Uint8Array | ArrayBuffer,+ options?: { levels?: import('./lod.js').LodLevelInput[] },+): Promise<import('./lod.js').LodChainResult>;diff --git a/packages/glb-tools/src/index.js b/packages/glb-tools/src/index.jsindex 6fe2bf3fd..b553821f9 100644--- a/packages/glb-tools/src/index.js+++ b/packages/glb-tools/src/index.js@@ -102,6 +102,20 @@ export function bake(avatarId, appearance, opts) {return defaultClient().bake(avatarId, appearance, opts);}+// buildLodChain is Node.js-only (gltf-transform's NodeIO, meshoptimizer's WASM+// simplifier) and the one real dependency this otherwise zero-dependency+// package carries. It's dynamically imported here so a browser bundle that+// only calls inspect()/theme()/bake() never pulls gltf-transform into its+// graph; a Node-only caller can also import '@three-ws/glb-tools/lod' directly.+/**+ * Build a real multi-level LOD chain for a GLB (Node.js only). See+ * README.md#buildlodchain for the levels/MSFT_lod contract.+ */+export async function buildLodChain(glb, options) {+ const { buildLodChain: impl } = await import('./lod.js');+ return impl(glb, options);+}+// ── Response shaping ─────────────────────────────────────────────────────────// The inspect endpoint already returns camelCase JSON (it ships the isomorphicdiff --git a/packages/glb-tools/src/lod.d.ts b/packages/glb-tools/src/lod.d.tsnew file mode 100644index 000000000..27674a1a7--- /dev/null+++ b/packages/glb-tools/src/lod.d.ts@@ -0,0 +1,44 @@+// Type definitions for @three-ws/glb-tools/lod (Node.js-only entry point)++export type LodLevelInput =+ | number+ | {+ name?: string;+ ratio: number;+ error?: number;+ screenCoverage?: number;+ };++export interface LodLevelResult {+ name: string;+ ratio: number;+ error: number;+ screenCoverage: number | null;+ triangleCount: number;+ vertexCount: number;+ /** Standalone GLB for this level alone (no MSFT_lod, just the decimated mesh). */+ glb: Uint8Array;+}++export interface LodChainResult {+ source: { triangleCount: number; vertexCount: number };+ levels: LodLevelResult[];+ /** A single GLB with every level merged in and MSFT_lod wired to switch between them. */+ combined: Uint8Array;+}++export declare const DEFAULT_LOD_LEVELS: ReadonlyArray<{+ name: string;+ ratio: number;+ error?: number;+ screenCoverage: number;+}>;++export declare const MSFT_LOD_EXTENSION_NAME: 'MSFT_lod';++export declare function buildLodChain(+ glb: Uint8Array | ArrayBuffer,+ options?: { levels?: LodLevelInput[] },+): Promise<LodChainResult>;++export declare function countDocumentGeometry(doc: unknown): { triangles: number; vertices: number };diff --git a/packages/glb-tools/src/lod.js b/packages/glb-tools/src/lod.jsnew file mode 100644index 000000000..87bc2780c--- /dev/null+++ b/packages/glb-tools/src/lod.js@@ -0,0 +1,186 @@+// Real LOD chain generation for a GLB: decimates the mesh at each requested+// ratio with gltf-transform's simplify() (meshoptimizer under the hood), then+// emits both a combined GLB (MSFT_lod-tagged, for engines that switch LODs at+// runtime from one file) and one standalone GLB per level (for engines, like+// most game-engine importers, that want discrete LOD files on disk).+//+// MSFT_lod (https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/MSFT_lod)+// is archived and gltf-transform ships no Extension class for it, so the+// combined GLB's JSON chunk is patched by hand after gltf-transform writes+// it. See glb-container.js for the chunk-level read/write this relies on.++import { NodeIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';+import { simplify, cloneDocument, mergeDocuments, unpartition } from '@gltf-transform/functions';+import { MeshoptSimplifier, MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';+import draco3dgltf from 'draco3dgltf';+import { readGlbChunks, writeGlb } from './glb-container.js';++const TRIANGLES_MODE = 4; // glTF primitive.mode for GL_TRIANGLES++// Highest detail first. ratio 1 ships the source mesh untouched (LOD0 is the+// delivered quality bar, never itself simplified); LOD1/LOD2 are the two+// most common runtime switch points for real-time engines (Unity, Unreal,+// Godot all default to 2-4 LOD levels past the base mesh).+export const DEFAULT_LOD_LEVELS = Object.freeze([+ Object.freeze({ name: 'LOD0', ratio: 1, screenCoverage: 0.5 }),+ Object.freeze({ name: 'LOD1', ratio: 0.5, error: 0.01, screenCoverage: 0.15 }),+ Object.freeze({ name: 'LOD2', ratio: 0.15, error: 0.02, screenCoverage: 0 }),+]);++export const MSFT_LOD_EXTENSION_NAME = 'MSFT_lod';++let ioPromise = null;+function getIo() {+ if (!ioPromise) {+ ioPromise = (async () => {+ await Promise.all([MeshoptSimplifier.ready, MeshoptDecoder.ready, MeshoptEncoder.ready]);+ const [dracoDecoder, dracoEncoder] = await Promise.all([+ draco3dgltf.createDecoderModule(),+ draco3dgltf.createEncoderModule(),+ ]);+ return new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({+ 'meshopt.decoder': MeshoptDecoder,+ 'meshopt.encoder': MeshoptEncoder,+ 'draco3d.decoder': dracoDecoder,+ 'draco3d.encoder': dracoEncoder,+ });+ })();+ }+ return ioPromise;+}++function normalizeLevels(levels) {+ if (levels === undefined || levels === null) return DEFAULT_LOD_LEVELS;+ if (!Array.isArray(levels) || levels.length < 2 || levels.length > 6) {+ throw new RangeError('buildLodChain: levels must be an array of 2-6 entries');+ }+ const normalized = levels.map((lvl, i) => {+ const entry = typeof lvl === 'number' ? { ratio: lvl } : lvl && typeof lvl === 'object' ? lvl : {};+ const ratio = Number(entry.ratio);+ if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) {+ throw new RangeError(`buildLodChain: levels[${i}].ratio must be a number in (0, 1]`);+ }+ return {+ name: typeof entry.name === 'string' && entry.name ? entry.name : `LOD${i}`,+ ratio,+ error: Number.isFinite(entry.error) ? entry.error : 0.01,+ screenCoverage: Number.isFinite(entry.screenCoverage) ? entry.screenCoverage : null,+ };+ });+ for (let i = 1; i < normalized.length; i++) {+ if (normalized[i].ratio >= normalized[i - 1].ratio) {+ throw new RangeError('buildLodChain: levels must be ordered highest to lowest detail (strictly decreasing ratio)');+ }+ }+ return normalized;+}++/** Sums triangle/vertex counts across every triangle-list primitive in the document. */+export function countDocumentGeometry(doc) {+ let triangleCount = 0;+ let vertexCount = 0;+ for (const mesh of doc.getRoot().listMeshes()) {+ for (const prim of mesh.listPrimitives()) {+ if (prim.getMode() !== TRIANGLES_MODE) continue;+ const indices = prim.getIndices();+ const positions = prim.getAttribute('POSITION');+ const count = indices ? indices.getCount() : positions ? positions.getCount() : 0;+ triangleCount += Math.floor(count / 3);+ vertexCount += positions ? positions.getCount() : 0;+ }+ }+ return { triangleCount, vertexCount };+}++/**+ * Build a real LOD chain for a GLB.+ *+ * @param {Uint8Array | ArrayBuffer} glb+ * @param {{ levels?: Array<number | { name?: string, ratio: number, error?: number, screenCoverage?: number }> }} [options]+ * @returns {Promise<{+ * source: { triangleCount: number, vertexCount: number },+ * levels: Array<{ name: string, ratio: number, error: number, screenCoverage: number | null, triangleCount: number, vertexCount: number, glb: Uint8Array }>,+ * combined: Uint8Array,+ * }>}+ */+export async function buildLodChain(glb, options = {}) {+ const input = glb instanceof Uint8Array ? glb : new Uint8Array(glb);+ const levels = normalizeLevels(options.levels);+ const io = await getIo();++ const sourceDoc = await io.readBinary(input);+ const source = countDocumentGeometry(sourceDoc);+ if (source.triangleCount === 0) {+ throw new Error('buildLodChain: source GLB has no triangle geometry to simplify');+ }++ const target = cloneDocument(sourceDoc);+ const scene = target.getRoot().listScenes()[0];+ if (!scene) throw new Error('buildLodChain: source GLB has no default scene');+ const primaryRootNodes = scene.listChildren();++ const levelDocs = [];+ const results = [];+ for (const level of levels) {+ const doc = cloneDocument(sourceDoc);+ if (level.ratio < 1) {+ await doc.transform(simplify({ simplifier: MeshoptSimplifier, ratio: level.ratio, error: level.error }));+ }+ const stats = countDocumentGeometry(doc);+ const bytes = await io.writeBinary(doc);+ levelDocs.push(doc);+ results.push({+ name: level.name,+ ratio: level.ratio,+ error: level.error,+ screenCoverage: level.screenCoverage,+ triangleCount: stats.triangleCount,+ vertexCount: stats.vertexCount,+ glb: bytes,+ });+ }++ for (let i = 1; i < results.length; i++) {+ if (results[i].triangleCount > results[i - 1].triangleCount) {+ throw new Error(+ `buildLodChain: ${results[i].name} (${results[i].triangleCount} tris) is not lower detail than ${results[i - 1].name} (${results[i - 1].triangleCount} tris) - raise the error tolerance or lower the ratio`,+ );+ }+ }++ // Merge LOD1..N as orphan nodes: present in the Document (and therefore the+ // JSON chunk) but excluded from the Scene's child graph, so a viewer that+ // does not understand MSFT_lod only ever traverses and renders LOD0.+ const altRootNodesByLevel = [];+ for (let i = 1; i < levelDocs.length; i++) {+ mergeDocuments(target, levelDocs[i]);+ const mergedScenes = target.getRoot().listScenes();+ const extraScene = mergedScenes[mergedScenes.length - 1];+ const altRootNodes = extraScene.listChildren();+ extraScene.dispose(); // the wrapper scene goes; its root nodes stay alive as orphans+ altRootNodesByLevel.push(altRootNodes);+ }++ await target.transform(unpartition());++ const combinedBytes = await io.writeBinary(target);+ const { json, binChunk } = readGlbChunks(combinedBytes);+ const docNodes = target.getRoot().listNodes();+ const indexOfNode = (node) => docNodes.indexOf(node);++ json.extensionsUsed = Array.from(new Set([...(json.extensionsUsed ?? []), MSFT_LOD_EXTENSION_NAME]));+ const screenCoverages = levels.slice(1).map((l) => l.screenCoverage ?? 0);++ primaryRootNodes.forEach((primaryNode, i) => {+ const primaryIndex = indexOfNode(primaryNode);+ const altIds = altRootNodesByLevel.map((altRoots) => indexOfNode(altRoots[i]));+ const jsonNode = json.nodes[primaryIndex];+ jsonNode.extensions = { ...jsonNode.extensions, [MSFT_LOD_EXTENSION_NAME]: { ids: altIds } };+ jsonNode.extras = { ...jsonNode.extras, MSFT_screencoverage: screenCoverages };+ });++ const combined = writeGlb({ json, binChunk });++ return { source, levels: results, combined };+}diff --git a/packages/glb-tools/test/lod.test.js b/packages/glb-tools/test/lod.test.jsnew file mode 100644index 000000000..404377349--- /dev/null+++ b/packages/glb-tools/test/lod.test.js@@ -0,0 +1,100 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { buildLodChain, DEFAULT_LOD_LEVELS, MSFT_LOD_EXTENSION_NAME } from '../src/lod.js';+import { readGlbChunks, writeGlb } from '../src/glb-container.js';++// Real, bundled static mesh: honest input for a real decimation pipeline.+// Same fixture glb-compress.test.js uses, so CI guarantees it exists.+const FIXTURE = fileURLToPath(new URL('../../../public/avatars/cesium-man.glb', import.meta.url));+const hasFixture = existsSync(FIXTURE);++test('glb-container round-trips a GLB byte-for-byte through JSON', { skip: !hasFixture }, () => {+ const buf = readFileSync(FIXTURE);+ const { json, binChunk } = readGlbChunks(buf);+ assert.ok(Array.isArray(json.nodes) && json.nodes.length > 0);+ assert.ok(binChunk && binChunk.byteLength > 0);++ const rewritten = writeGlb({ json, binChunk });+ const { json: json2 } = readGlbChunks(rewritten);+ assert.deepEqual(json2.nodes.map((n) => n.name), json.nodes.map((n) => n.name));+});++test('readGlbChunks rejects a non-GLB buffer', () => {+ assert.throws(() => readGlbChunks(Buffer.from('not a glb')), /bad magic/);+});++test('buildLodChain produces 3 default levels with strictly decreasing triangle counts', { skip: !hasFixture, timeout: 60_000 }, async () => {+ const buf = readFileSync(FIXTURE);+ const result = await buildLodChain(buf);++ assert.equal(result.levels.length, DEFAULT_LOD_LEVELS.length);+ assert.ok(result.source.triangleCount > 0);+ assert.equal(result.levels[0].triangleCount, result.source.triangleCount); // LOD0 is untouched++ for (let i = 1; i < result.levels.length; i++) {+ assert.ok(+ result.levels[i].triangleCount < result.levels[i - 1].triangleCount,+ `${result.levels[i].name} (${result.levels[i].triangleCount}) should be lower-poly than ${result.levels[i - 1].name} (${result.levels[i - 1].triangleCount})`,+ );+ }+});++test('buildLodChain levels are each a structurally valid, independently loadable GLB', { skip: !hasFixture, timeout: 60_000 }, async () => {+ const buf = readFileSync(FIXTURE);+ const result = await buildLodChain(buf);++ for (const level of result.levels) {+ const { json, binChunk } = readGlbChunks(level.glb);+ assert.ok(json.meshes.length > 0, `${level.name} standalone GLB has no meshes`);+ assert.ok(binChunk.byteLength > 0, `${level.name} standalone GLB has no binary payload`);+ }+});++test('buildLodChain combined GLB wires MSFT_lod on the scene root and keeps the default scene single-LOD', { skip: !hasFixture, timeout: 60_000 }, async () => {+ const buf = readFileSync(FIXTURE);+ const result = await buildLodChain(buf);+ const { json } = readGlbChunks(result.combined);++ assert.ok(json.extensionsUsed.includes(MSFT_LOD_EXTENSION_NAME));++ const sceneIndex = json.scene ?? 0;+ const rootNodeIndices = json.scenes[sceneIndex].nodes;+ assert.equal(rootNodeIndices.length, 1);++ const rootNode = json.nodes[rootNodeIndices[0]];+ const lod = rootNode.extensions?.[MSFT_LOD_EXTENSION_NAME];+ assert.ok(lod, 'scene root node is missing the MSFT_lod extension');+ assert.equal(lod.ids.length, result.levels.length - 1); // one alternate id per non-LOD0 level+ assert.equal(rootNode.extras.MSFT_screencoverage.length, result.levels.length - 1);++ // The alternate LOD root nodes exist in the document (addressable by index)+ // but are not reachable from the default scene's own child graph.+ for (const altId of lod.ids) {+ assert.ok(json.nodes[altId], `alternate LOD node ${altId} does not exist`);+ assert.ok(!rootNodeIndices.includes(altId), `alternate LOD node ${altId} leaked into the default scene`);+ }+});++test('buildLodChain accepts a custom 2-level chain', { skip: !hasFixture, timeout: 60_000 }, async () => {+ const buf = readFileSync(FIXTURE);+ const result = await buildLodChain(buf, { levels: [1, 0.3] });+ assert.equal(result.levels.length, 2);+ assert.ok(result.levels[1].triangleCount < result.levels[0].triangleCount);+});++test('buildLodChain rejects a non-decreasing levels array', { skip: !hasFixture }, async () => {+ const buf = readFileSync(FIXTURE);+ await assert.rejects(() => buildLodChain(buf, { levels: [0.5, 0.8] }), /strictly decreasing/);+});++test('buildLodChain rejects an out-of-range ratio', { skip: !hasFixture }, async () => {+ const buf = readFileSync(FIXTURE);+ await assert.rejects(() => buildLodChain(buf, { levels: [1, 0] }), /\(0, 1\]/);+});++test('buildLodChain rejects too few levels', { skip: !hasFixture }, async () => {+ const buf = readFileSync(FIXTURE);+ await assert.rejects(() => buildLodChain(buf, { levels: [1] }), /2-6 entries/);+});