← Commit history
0.10.0: replaceModel, explicit addModel, and loads that release what they brought (adom/adom-3d-viewer#11)
7 files changed
+325−23
README.md+12−1@@ -78,7 +78,18 @@ window.Adom3DViewerBabylon9 = { `ViewerInstance` exposes: -- `loadModel(url)` / `loadModelBytes(bytes, { extension? })` / `clearScene()` / `frameModel(fillFraction?)`+- `replaceModel(url)` / `replaceModelBytes(bytes, { extension? })`: show this+ model INSTEAD of what is loaded. The new model loads first; then every+ earlier model and all it brought (meshes, materials, textures, animation+ groups, skeletons, content lights, layer and state-group inventory) is+ disposed. Camera, controls, ground, environment and anything added with+ `addContentRoot` stay. A failed load keeps the current model; of two+ overlapping calls the later wins. Use this to swap models in one viewer.+- `loadModel(url)` / `loadModelBytes(bytes, { extension? })`: ADD a model to+ what is shown (a second call shows both, for scenes composed from several+ files). `addModel` / `addModelBytes` are the same, named for what they do.+- `clearScene()` (removes every loaded model with its materials, textures and+ animations) / `frameModel(fillFraction?)` - `whenReady()` / `getReadyReport()`: the ready report (see "Sandboxed frames" below): resolves once the first scene is up and reflects the current state on every later call; never rejects
SKILL.md+4@@ -42,6 +42,10 @@ The extracted VERSION file records exactly which build you have. </script> ``` +To show a different model in the same viewer, call `replaceModel(url)`:+`loadModel` ADDS (a second call shows both models), `replaceModel` swaps and+releases everything the old model brought.+ Full API (loadModel, frameModel, toggleAxes, layers toolbar, laser etch, BABYLON namespace re-export) is documented in the README on this page. Source lives on the Files tab; `adom-wiki repo clone adom/adom-3d-viewer`
VERSION+1−1@@ -1 +1 @@-0.9.3+0.10.0
package.json+4−3@@ -1,6 +1,6 @@ { "name": "adom-3d-viewer-babylon9",- "version": "0.9.3",+ "version": "0.10.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",@@ -25,10 +25,11 @@ "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": "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 && node test/replace.test.mjs", "test:viewcube": "node test/viewcube.test.mjs", "test:help": "node test/help.test.mjs",- "test:lights": "node test/lights.test.mjs"+ "test:lights": "node test/lights.test.mjs",+ "test:replace": "node test/replace.test.mjs" }, "dependencies": {}, "devDependencies": {
src/ThreeDViewer.svelte+113−16@@ -166,9 +166,26 @@ let canvas: HTMLCanvasElement; let resizeObserver: ResizeObserver | null = null; let loadedRootNodes: TransformNode[] = [];+ // Everything each model import brought into the scene, so replacing or+ // clearing a model releases all of it, not only the mesh tree: its+ // animation groups, skeletons, loose transform nodes, materials and+ // textures (adom/adom-3d-viewer#11).+ type LoadedImport = { meshes: AbstractMesh[]; animationGroups: any[]; skeletons: any[]; transformNodes: any[] };+ let loadedImports: LoadedImport[] = [];+ // Bumped by every replace and clear: an import that finishes after a newer+ // one started is thrown away instead of joining the scene.+ let modelGen = 0; /** User-added roots (e.g. native Babylon meshes) included in framing. */ let contentRoots: TransformNode[] = []; let groundMesh: Mesh | null = null;+ // The ground's own material and fade texture, released whenever the ground+ // is rebuilt (every reframe): disposing only the mesh left one of each behind+ // per model load. A material a host put on it (onGroundCreated) is the host's.+ let groundOwn: { mat: any; tex: any } | null = null;+ function disposeGround(): void {+ if (groundMesh) { try { groundMesh.dispose(); } catch { /* already gone */ } groundMesh = null; }+ if (groundOwn) { try { groundOwn.tex?.dispose(); } catch { /* already gone */ } try { groundOwn.mat?.dispose(false, true); } catch { /* already gone */ } groundOwn = null; }+ } let isOrtho: boolean = false; // Tooltip / dropdown state driven by ViewCube callbacks@@ -882,9 +899,52 @@ resizeObserver.observe(container); } + /**+ * Load a model from a URL and ADD it to what is already shown: calling it+ * twice shows both models. Kept additive so hosts that compose a scene+ * from several files keep working; to swap one model for another, use+ * replaceModel(). Same as addModel().+ */ export async function loadModel(url: string): Promise<void> {+ return addModel(url);+ }++ /** 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) attachLoadedModel(result);+ }++ /**+ * Replace the shown model with the one at `url`: the new model loads+ * first, then every earlier model (meshes, materials, textures, animation+ * groups, skeletons, content lights, layer and state-group inventory) is+ * disposed. The camera, controls, ground, environment and anything added+ * with addContentRoot stay. If the load fails, the current model stays.+ * Of two overlapping calls, the later one wins.+ */+ export async function replaceModel(url: string): Promise<void> {+ const gen = ++modelGen;+ const result = await importModelFromUrl(url);+ if (!result) return;+ if (gen !== modelGen) { disposeImport(result); return; }+ disposeLoadedModels();+ attachLoadedModel(result);+ }++ /** replaceModel() for bytes already in hand (see loadModelBytes). */+ export async function replaceModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {+ const gen = ++modelGen;+ const result = await importModelFromBytes(bytes, options);+ if (!result) return;+ if (gen !== modelGen) { disposeImport(result); return; }+ disposeLoadedModels();+ attachLoadedModel(result);+ }++ async function importModelFromUrl(url: string): Promise<any> { const scene = AdomStatics.scene;- if (!scene) return;+ if (!scene) return null; const lastSlash = url.lastIndexOf('/'); const rootUrl = lastSlash >= 0 ? url.substring(0, lastSlash + 1) : '';@@ -909,17 +969,12 @@ throw e; } lastModelError = null;- attachLoadedModel(result);+ return result; } - /**- * Load a model from bytes already in hand (a verified transfer, a- * private-page fetch done by the host page, a generated GLB). Nothing- * is fetched, so the frame's CSP never sees a URL.- */- export async function loadModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {+ async function importModelFromBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<any> { const scene = AdomStatics.scene;- if (!scene) return;+ if (!scene) return null; modelRequested = true; const ext = (options && options.extension) || '.glb'; let result;@@ -930,7 +985,35 @@ throw e; } lastModelError = null;- attachLoadedModel(result);+ return result;+ }++ /**+ * Load a model from bytes already in hand (a verified transfer, a+ * private-page fetch done by the host page, a generated GLB). Nothing+ * is fetched, so the frame's CSP never sees a URL. Additive like+ * loadModel(); replaceModelBytes() swaps instead. Same as addModelBytes().+ */+ export async function loadModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {+ return addModelBytes(bytes, options);+ }++ /** loadModelBytes(), explicitly additive. */+ export async function addModelBytes(bytes: ArrayBufferView, options?: { extension?: string }): Promise<void> {+ const result = await importModelFromBytes(bytes, options);+ if (result) attachLoadedModel(result);+ }++ // Release one import completely: animations stop and go, skeletons go,+ // and the meshes go WITH their materials and textures (Babylon keeps+ // those by default, so every reload used to leave the last model's GPU+ // resources behind). Loose transform nodes (lights' parents, empties)+ // last. Content lights are cleared by the caller.+ function disposeImport(r: any): void {+ for (const g of r.animationGroups || []) { try { g.stop(); g.dispose(); } catch { /* already gone */ } }+ for (const sk of r.skeletons || []) { try { sk.dispose(); } catch { /* already gone */ } }+ for (const m of r.meshes || []) { try { if (!m.isDisposed()) m.dispose(false, true); } catch { /* already gone */ } }+ for (const t of r.transformNodes || []) { try { if (!t.isDisposed()) t.dispose(false, true); } catch { /* already gone */ } } } function attachLoadedModel(result: { meshes: AbstractMesh[] }): void {@@ -953,6 +1036,7 @@ } const root = result.meshes[0];+ loadedImports.push({ meshes: result.meshes || [], animationGroups: (result as any).animationGroups || [], skeletons: (result as any).skeletons || [], transformNodes: (result as any).transformNodes || [] }); if (root) { loadedRootNodes.push(root); result.meshes.forEach((m: AbstractMesh) => {@@ -1068,13 +1152,27 @@ } } + /**+ * Remove every loaded model and everything it brought (meshes, materials,+ * textures, animation groups, skeletons, content lights, layer and state+ * inventory). Content added with addContentRoot stays. A model still+ * loading when this runs is discarded when it arrives if it was started+ * by replaceModel().+ */ export function clearScene(): void {+ modelGen++;+ disposeLoadedModels();+ }++ function disposeLoadedModels(): void { // Content lights hang off transform nodes, not meshes, so disposing the // mesh roots can leave them lighting the NEXT model. Dispose them here. stopIntros(); 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 */ } }+ for (const r of loadedImports) disposeImport(r);+ loadedRootNodes.forEach((node) => { try { if (!node.isDisposed()) node.dispose(false, true); } catch { /* already gone */ } });+ loadedImports = []; stateGroups = []; loadedRootNodes = []; layers = [];@@ -1180,8 +1278,7 @@ if (loadedRootNodes.length > 0 || contentRoots.length > 0) { frameModel(); } else if (!visible && groundMesh) {- groundMesh.dispose();- groundMesh = null;+ disposeGround(); } } @@ -1481,7 +1578,7 @@ if (showGround) { const groundSize = modelSize * 4;- if (groundMesh) groundMesh.dispose();+ disposeGround(); groundMesh = MeshBuilder.CreateGround('shadowGround', { width: groundSize, height: groundSize }, scene); groundMesh.receiveShadows = true; const mat = new PBRMetallicRoughnessMaterial('groundMat', scene);@@ -1508,6 +1605,7 @@ fadeTex.update(); fadeTex.hasAlpha = true; mat.baseTexture = fadeTex;+ groundOwn = { mat, tex: fadeTex }; mat.transparencyMode = 2; // ALPHABLEND: final alpha = texture.a * mat.alpha groundMesh.material = mat; groundMesh.isPickable = false;@@ -1529,8 +1627,7 @@ catch (e) { console.warn('[viewer] onGroundCreated threw', e); } } } else if (groundMesh) {- groundMesh.dispose();- groundMesh = null;+ disposeGround(); } // Register the model as shadow casters HERE (not only in loadModel).
standalone.ts+14−2@@ -2,7 +2,7 @@ declare const __VIEWER_VERSION__: string; /** * Standalone entry point for the Adom 3D Viewer. * Bundles Svelte + Babylon.js + the ThreeDViewer component into a single IIFE.- * Exposes window.Adom3DViewer with init/loadModel/clearScene/getScene APIs.+ * Exposes window.Adom3DViewer with init/loadModel/replaceModel/clearScene/getScene APIs. * Includes laser etch and Y-up→Z-up helpers inside the bundle scope. */ @@ -39,9 +39,17 @@ import type { Scene } from '@babylonjs/core/scene'; import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; interface ViewerInstance {+ /** Load a model and ADD it to the scene (a second call shows both). Same as addModel. */ loadModel: (url: string) => Promise<void>;- /** Load a model from bytes already in hand; nothing is fetched. */+ /** Load a model from bytes already in hand; nothing is fetched. Additive, like loadModel. */ loadModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>;+ /** Swap the shown model for this one, disposing everything the earlier models brought+ * (meshes, materials, textures, animations, layers); controls and content roots stay. */+ replaceModel: (url: string) => Promise<void>;+ replaceModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>;+ /** Explicitly additive load (what loadModel does). */+ addModel: (url: string) => Promise<void>;+ addModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>; /** Resolves with the ready report once the first scene is up (never * rejects: failures are in the report's hints). */ whenReady: () => Promise<ViewerReadyReport & { version: string }>;@@ -171,6 +179,10 @@ function init(container: HTMLElement, options?: { hideHelp: () => { help && help.hide(); }, loadModel: (url: string) => component.loadModel(url), loadModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.loadModelBytes(bytes, o),+ replaceModel: (url: string) => component.replaceModel(url),+ replaceModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.replaceModelBytes(bytes, o),+ addModel: (url: string) => component.addModel(url),+ addModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.addModelBytes(bytes, o), whenReady: () => component.whenReady().then(withVersion), getReadyReport: () => { const r = component.getReadyReport(); return r ? withVersion(r) : null; }, clearScene: () => component.clearScene(),
test/replace.test.mjsadded+177@@ -0,0 +1,177 @@+// Replacing the shown model (adom/adom-3d-viewer#11). loadModel() is additive+// by design (a second call shows both models: John's harness meshes doubled+// that way); replaceModel() swaps, disposing everything the earlier model+// brought: meshes, materials, textures, animation groups, skeletons and the+// layer inventory. Repeated replacement keeps the scene the same size, the+// later of two overlapping replacements wins, a failed load keeps the current+// model, and clearScene() releases materials and textures too.+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(JSON.stringify(a) === JSON.stringify(b), `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);+function section(t) { console.log("\n [" + t + "]"); }++// A 1x1 PNG, for a textured material.+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");++/** A GLB of named cubes; `textured` gives them a textured material, `animated` a translation animation. */+function makeGlb(prefix, names, { textured = false, animated = false } = {}) {+ const pos = [], uv = [], 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); }); uv.push(0, 0, 1, 0, 1, 1, 0, 1); 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 uvBuf = pad(Buffer.from(new Float32Array(uv).buffer));+ const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));+ const times = pad(Buffer.from(new Float32Array([0, 1]).buffer));+ const trans = pad(Buffer.from(new Float32Array([0, 0, 0, 0.02, 0, 0]).buffer));+ const png = pad(PNG);+ const parts = [posBuf, uvBuf, idxBuf, times, trans, png];+ const views = []; let off = 0;+ for (const p of parts) { views.push({ buffer: 0, byteOffset: off, byteLength: p.length }); off += p.length; }+ views[5].byteLength = PNG.length;+ const bin = Buffer.concat(parts);+ const json = {+ asset: { version: "2.0" }, scene: 0,+ scenes: [{ nodes: names.map((_, i) => i) }],+ nodes: names.map((n, i) => ({ name: `${prefix}_${n}`, mesh: 0, translation: [i * 0.03, 0, 0] })),+ meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0 }] }],+ materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: textured ? { baseColorTexture: { index: 0 } } : { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],+ ...(textured ? { textures: [{ source: 0, name: `${prefix}_tex` }], images: [{ name: `${prefix}_img`, bufferView: 5, mimeType: "image/png" }] } : {}),+ ...(animated ? { animations: [{ name: `${prefix}_anim`, samplers: [{ input: 3, output: 4, 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: 5126, count: uv.length / 2, type: "VEC2" },+ { bufferView: 2, componentType: 5123, count: idx.length, type: "SCALAR" },+ { bufferView: 3, componentType: 5126, count: 2, type: "SCALAR", min: [0], max: [1] },+ { bufferView: 4, 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 = {+ // The old harness: two sensor wires, textured and animated.+ "/old.glb": makeGlb("OldWire", ["sense", "return"], { textured: true, animated: true }),+ // The new export: a different set of parts.+ "/new.glb": makeGlb("NewPart", ["body", "lid", "screw"]),+};+const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;inset:0;width:640px;height:400px}</style></head><body><div id="wrap"></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: true, showHelp: false });+ await v.whenReady(); window.__viewer = v;+ // What the scene holds that a model brought (names carry the model prefix).+ window.__census = () => {+ const s = v.getScene();+ const pick = (list) => list.map(x => x.name).filter(n => /^(OldWire|NewPart)/.test(n)).sort();+ return { meshes: pick(s.meshes), materials: pick(s.materials), textures: s.textures.filter(t => /OldWire|NewPart/.test(t.name || "")).length,+ animationGroups: s.animationGroups.filter(g => /OldWire|NewPart/.test(g.name)).length, totalMeshes: s.meshes.length, totalMaterials: s.materials.length,+ totalTextures: s.textures.length, camera: !!v.getCamera() };+ };+ 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();+ 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 census = () => run(() => window.__census());++ section("loadModel is additive (the doubled-harness case)");+ await run(async () => { await window.__viewer.loadModel("/old.glb"); await window.__viewer.loadModel("/new.glb"); });+ let c = await census();+ assert(c.meshes.some(n => n.startsWith("OldWire")) && c.meshes.some(n => n.startsWith("NewPart")), "both models are in the scene after two loadModel calls");++ section("replaceModel swaps: nothing of the old model stays");+ await run(async () => { await window.__viewer.replaceModel("/old.glb"); });+ c = await census();+ assert(c.meshes.every(n => n.startsWith("OldWire")) && c.meshes.length > 0, "only the replacing model's meshes");+ eq(c.animationGroups, 1, "its animation group is there");+ assert(c.textures >= 1, "its texture is there");+ await run(async () => { await window.__viewer.replaceModel("/new.glb"); });+ c = await census();+ eq(c.meshes.filter(n => n.startsWith("OldWire")), [], "no old wire meshes");+ eq(c.materials.filter(n => n.startsWith("OldWire")), [], "no old materials");+ eq(c.textures, 0, "no old textures");+ eq(c.animationGroups, 0, "no old animation groups");+ assert(c.meshes.some(n => n === "NewPart_body"), "the new model is shown");+ assert(c.camera, "the camera (viewer controls) stays");++ section("repeated replacement keeps the scene the same size");+ const sizes = [];+ for (let i = 0; i < 6; i++) {+ await run(async (u) => { await window.__viewer.replaceModel(u); }, i % 2 ? "/new.glb" : "/old.glb");+ const k = await census();+ sizes.push([k.totalMeshes, k.totalMaterials, k.totalTextures]);+ }+ eq(sizes[2], sizes[0], "old -> new -> old: the same counts as the first old");+ eq(sizes[4], sizes[0], "and again");+ eq(sizes[5], sizes[3], "new counts stable too");++ section("bytes replace the same way");+ await run(async () => { const b = new Uint8Array(await (await fetch("/old.glb")).arrayBuffer()); await window.__viewer.replaceModelBytes(b, { extension: ".glb" }); });+ c = await census();+ assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), "replaceModelBytes leaves only the new bytes' model");++ section("the later of two overlapping replacements wins");+ await run(async () => { const v = window.__viewer; await Promise.all([v.replaceModel("/new.glb"), v.replaceModel("/old.glb")]); });+ c = await census();+ assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), `only the second call's model (${c.meshes.join(",")})`);++ section("a failed replacement keeps the current model");+ const err = await run(async () => { try { await window.__viewer.replaceModel("/missing.glb"); return null; } catch (e) { return String(e && e.message || e); } });+ assert(!!err, "the failure is reported to the caller");+ c = await census();+ assert(c.meshes.length > 0 && c.meshes.every(n => n.startsWith("OldWire")), "the current model is still shown");++ section("addModel is the explicit additive load; clearScene releases everything");+ await run(async () => { await window.__viewer.addModel("/new.glb"); });+ c = await census();+ assert(c.meshes.some(n => n.startsWith("OldWire")) && c.meshes.some(n => n.startsWith("NewPart")), "addModel shows both");+ await run(() => window.__viewer.clearScene());+ c = await census();+ eq(c.meshes, [], "no model meshes after clearScene");+ eq(c.materials, [], "no model materials after clearScene");+ eq([c.textures, c.animationGroups], [0, 0], "no model textures or animations after clearScene");+} finally {+ await browser.close();+ server.close();+}+console.log(`\n=== replace ===\n${passed} passed, ${failed} failed`);+if (failures.length) for (const f of failures) console.log(" - " + f);+process.exit(failed ? 1 : 0);