master
AdityaAngajala v0.13.0 12542ed
// Two viewers on one page. Each init() gets its own engine, scene, camera,
// lights and view cube, draws its own model into its own canvas, and keeps
// its camera, bottom light and shadow settings to itself. Shadow maps shrink
// while several viewers have shadows and grow back after. Destroying one
// leaves the other running, a viewer created afterwards starts clean, a
// viewer destroyed during startup throws nothing and settles whenReady(), the
// ? key and camera:change_view reach one viewer, and a destroyed viewer keeps
// its scene until its textures finish loading.
import http from "node:http";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");
let passed = 0, failed = 0; const failures = [];
function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }
function section(t) { console.log("\n  [" + t + "]"); }

/** A GLB of one 2 cm cube named `<prefix>_cube` in a flat colour. */
function makeGlb(prefix, rgb) {
  const pos = [], idx = [];
  const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];
  faces.forEach((f, fi) => { f.forEach(v => { pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01); }); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });
  const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);
  const posBuf = pad(Buffer.from(new Float32Array(pos).buffer));
  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));
  const bin = Buffer.concat([posBuf, idxBuf]);
  const json = {
    asset: { version: "2.0" }, scene: 0,
    scenes: [{ nodes: [0] }],
    nodes: [{ name: `${prefix}_cube`, mesh: 0 }],
    meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: { baseColorFactor: [...rgb, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: rgb }],
    buffers: [{ byteLength: bin.length }],
    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],
    accessors: [
      { bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },
      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },
    ],
  };
  let jsonBuf = Buffer.from(JSON.stringify(json));
  jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);
  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);
  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };
  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);
}

const PNG_1PX = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64");
const MODELS = {
  "/red.glb": makeGlb("Red", [1, 0, 0]),
  "/green.glb": makeGlb("Green", [0, 1, 0]),
};
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}
.v{position:absolute;top:0;width:320px;height:400px}#a{left:0}#b{left:320px}</style></head><body><div id="a" class="v"></div><div id="b" class="v"></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  const V = window.Adom3DViewerBabylon9;
  const make = (id) => V.init(document.getElementById(id), { zUp: true, showViewCube: true, showGround: false, showHelp: false });
  window.__make = make;
  window.__a = make('a'); window.__b = make('b');
  await Promise.all([window.__a.whenReady(), window.__b.whenReady()]);
  // Pixels of a viewer's canvas: how many are strongly red, strongly green,
  // and how many are not transparent at all.
  window.__pixels = (v) => {
    const src = v.getEngine().getRenderingCanvas();
    const c = document.createElement('canvas'); c.width = src.width; c.height = src.height;
    const g = c.getContext('2d'); g.drawImage(src, 0, 0);
    const d = g.getImageData(0, 0, c.width, c.height).data;
    let red = 0, green = 0, opaque = 0;
    for (let i = 0; i < d.length; i += 4) {
      if (d[i + 3] > 0) opaque++;
      if (d[i] > d[i + 1] + 80 && d[i] > d[i + 2] + 80) red++;
      if (d[i + 1] > d[i] + 80 && d[i + 1] > d[i + 2] + 80) green++;
    }
    return { red, green, opaque, total: c.width * c.height };
  };
  window.__frames = (v, ms) => new Promise(r => { let n = 0; const s = v.getScene(); const o = s.onAfterRenderObservable.add(() => n++); setTimeout(() => { s.onAfterRenderObservable.remove(o); r(n); }, ms); });
  window.__ready = true;
</script></body></html>`;

if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://x");
  if (MODELS[url.pathname]) { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(MODELS[url.pathname]); }
  // A 1x1 PNG that answers after 3 s: a texture still loading when its viewer is destroyed.
  if (url.pathname === "/slow.png") { setTimeout(() => { res.writeHead(200, { "Content-Type": "image/png" }); res.end(PNG_1PX); }, 3000); return; }
  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }
  const file = join(DIST, url.pathname.replace(/^\/+/, ""));
  if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }
  res.writeHead(404); res.end();
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
const port = server.address().port;
let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }
function findChrome() {
  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;
  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");
  if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }
  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");
}
const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });
try {
  const page = await browser.newPage();
  const pageErrors = [];
  page.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));
  await page.setViewport({ width: 640, height: 400 });
  await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });
  await page.waitForFunction("window.__ready === true", { timeout: 90000 });
  const run = (fn, ...args) => page.evaluate(fn, ...args);
  const waitPixels = (cond) => page.waitForFunction(cond, { timeout: 30000, polling: 250 }).catch(() => {});

  section("each viewer has its own engine, scene, camera and view cube");
  const own = await run(() => {
    const a = window.__a, b = window.__b;
    const cubes = (v) => v.getEngine().scenes.filter(s => s.getMeshByName("viewCubeSPS")).length;
    return {
      engines: a.getEngine() !== b.getEngine(), scenes: a.getScene() !== b.getScene(), cameras: a.getCamera() !== b.getCamera(),
      shadows: a.getShadowGenerator() !== b.getShadowGenerator(),
      mapA: a.getShadowGenerator().mapSize, mapB: b.getShadowGenerator().mapSize,
      lastIsCube: !!window.BABYLON.EngineStore.LastCreatedScene?.getMeshByName("viewCubeSPS"),
      lastIsMain: [a.getScene(), b.getScene()].includes(window.BABYLON.EngineStore.LastCreatedScene),
      canvasA: document.getElementById('a').contains(a.getEngine().getRenderingCanvas()),
      canvasB: document.getElementById('b').contains(b.getEngine().getRenderingCanvas()),
      cubesA: cubes(a), cubesB: cubes(b),
      okA: a.getReadyReport().ok, okB: b.getReadyReport().ok,
    };
  });
  assert(own.engines && own.scenes && own.cameras && own.shadows, "engine, scene, camera and shadow generator differ between the two viewers");
  assert(own.canvasA && own.canvasB, "each engine renders into the canvas inside its own container");
  assert(own.cubesA === 1 && own.cubesB === 1, `one view cube per engine (got ${own.cubesA} and ${own.cubesB})`);
  assert(own.okA && own.okB, "both ready reports are ok");
  assert(own.mapA === 4096 && own.mapB === 4096, `with two viewers each shadow map is 4096 (A ${own.mapA}, B ${own.mapB})`);
  assert(own.lastIsMain && !own.lastIsCube, "Babylon's default scene is a viewer's main scene, never a view cube scene");

  section("each viewer shows only its own model");
  await run(async () => {
    await window.__a.loadModel("/red.glb"); window.__a.frameModel();
    await window.__b.loadModel("/green.glb"); window.__b.frameModel();
    for (const v of [window.__a, window.__b]) v.toggleAxes('world', false);
  });
  // Each engine compiles its own shaders, which takes seconds under software
  // GL: wait for the cubes to show rather than for a fixed time.
  await waitPixels("window.__pixels(window.__a).red > 2000 && window.__pixels(window.__b).green > 2000");
  const names = await run(() => ({
    a: window.__a.getScene().meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)),
    b: window.__b.getScene().meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)),
  }));
  assert(names.a.includes("Red_cube") && !names.a.some(n => n.startsWith("Green")), `viewer A's scene holds the red cube only (${names.a.join(", ")})`);
  assert(names.b.includes("Green_cube") && !names.b.some(n => n.startsWith("Red")), `viewer B's scene holds the green cube only (${names.b.join(", ")})`);
  const pa = await run(() => window.__pixels(window.__a));
  const pb = await run(() => window.__pixels(window.__b));
  console.log(`    pixels A ${JSON.stringify(pa)}  B ${JSON.stringify(pb)}`);
  assert(pa.opaque === pa.total && pb.opaque === pb.total, "both canvases are painted edge to edge");
  assert(pa.red > 2000 && pa.green < pa.red / 5, "canvas A shows the red cube and no green one");
  assert(pb.green > 2000 && pb.red < pb.green / 5, "canvas B shows the green cube and no red one");

  section("camera, bottom light and shadow settings stay with their viewer");
  const iso = await run(async () => {
    const a = window.__a, b = window.__b;
    const cam = (v) => { const c = v.getCamera(); return [c.alpha, c.beta, c.radius, c.target.x, c.target.y, c.target.z]; };
    const before = cam(b);
    a.getCamera().alpha += 1; a.getCamera().radius *= 2; a.frameModel(0.3);
    a.setBottomLight(true);
    a.setShadowRefreshRate(2);
    await new Promise(r => setTimeout(r, 300));
    const after = cam(b);
    return {
      camSame: before.every((x, i) => Math.abs(x - after[i]) < 1e-9),
      bottomA: a.getBottomLightState(), bottomB: b.getBottomLightState(),
      rateA: a.getShadowGenerator().getShadowMap().refreshRate, rateB: b.getShadowGenerator().getShadowMap().refreshRate,
    };
  });
  assert(iso.camSame, "moving and reframing A's camera leaves B's camera where it was");
  assert(iso.bottomA === true && iso.bottomB === false, "A's bottom light is on, B's stays off");
  assert(iso.rateA === 2 && iso.rateB !== 2, `A's pinned shadow refresh rate does not reach B (A ${iso.rateA}, B ${iso.rateB})`);

  section("destroying one viewer leaves the other running");
  const after = await run(async () => {
    window.__a.destroy();
    const b = window.__b;
    const frames = await window.__frames(b, 600);
    await b.replaceModel("/red.glb"); b.frameModel();
    await new Promise(r => setTimeout(r, 500));
    const s = b.getScene();
    return { alive: !!s && !s.isDisposed && !b.getEngine().isDisposed, frames, ok: b.getReadyReport().ok,
      meshes: s.meshes.map(m => m.name).filter(n => /^(Red|Green)_/.test(n)) };
  });
  assert(after.alive, "B's scene and engine are not disposed");
  assert(after.frames > 0, `B keeps rendering (${after.frames} frames in 600 ms)`);
  assert(after.meshes.includes("Red_cube") && !after.meshes.includes("Green_cube"), "B can still replace its model");
  assert(after.ok, "B's ready report is still ok");
  const grown = await page.waitForFunction("window.__b.getShadowGenerator().mapSize === 8192", { timeout: 35000, polling: 100 }).then(() => true, () => false);
  const castersKept = await run(() => window.__b.getShadowGenerator().getShadowMap().renderList.some(m => m.name === "Red_cube"));
  assert(grown, "once A's map is freed, B, now the only viewer with shadows, gets an 8192 map back");
  assert(castersKept, "the resized map keeps B's shadow casters");

  section("a viewer created after a destroy starts clean");
  const fresh = await run(async () => {
    const c = window.__make('a'); window.__c = c;
    const r = await c.whenReady();
    await c.loadModel("/green.glb"); c.frameModel(); c.toggleAxes('world', false);
    return { ok: r.ok, bottom: c.getBottomLightState(), rate: c.getShadowGenerator().getShadowMap().refreshRate,
      ownEngine: c.getEngine() !== window.__b.getEngine() };
  });
  await waitPixels("window.__pixels(window.__c).green > 2000");
  fresh.px = await run(() => window.__pixels(window.__c));
  assert(fresh.ok && fresh.ownEngine, "the new viewer reports ok on its own engine");
  assert(fresh.bottom === false && fresh.rate !== 2, `it does not inherit the destroyed viewer's bottom light or shadow rate (rate ${fresh.rate})`);
  assert(fresh.px.green > 2000, "it draws its own model");
  const both = await run(() => [window.__b.getShadowGenerator().mapSize, window.__c.getShadowGenerator().mapSize]);
  assert(both[0] === 4096 && both[1] === 4096, `a second viewer with shadows takes both maps to 4096 (${both.join(", ")})`);
  const noShadow = await run(async () => {
    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);
    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: false, showHelp: false, shadows: false });
    await d.whenReady();
    const sizes = [window.__b.getShadowGenerator().mapSize, window.__c.getShadowGenerator().mapSize];
    d.destroy(); host.remove();
    return sizes;
  });
  assert(noShadow[0] === 4096 && noShadow[1] === 4096, `a viewer with shadows:false does not count (${noShadow.join(", ")})`);

  section("a viewer destroyed during startup throws nothing");
  const before = pageErrors.length;
  const early = await run(async () => {
    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);
    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: true, showHelp: false });
    const ready = d.whenReady();
    d.destroy();
    const r = await Promise.race([ready, new Promise(res => setTimeout(() => res(null), 3000))]);
    await new Promise(r => setTimeout(r, 1500));
    host.remove();
    return r && { destroyed: r.destroyed, ok: r.ok };
  });
  assert(pageErrors.length === before, `no page errors after an immediate destroy (${pageErrors.slice(before).join(" | ") || "none"})`);
  assert(!!early && early.destroyed === true && early.ok === false, `its whenReady() resolves with destroyed: true (${JSON.stringify(early)})`);
  const stillB = await run(() => window.__frames(window.__b, 400));
  assert(stillB > 0, "B still renders afterwards");

  section("a viewer destroyed right after its first model loads throws nothing");
  // The first PBR material makes Babylon decode an RGBD lookup texture
  // through an async shader import, after which it reads the texture's
  // scene; a destroy inside that window used to throw there.
  const beforeLoad = pageErrors.length;
  await run(async () => {
    // The window opens on the frames after the load, so try several delays.
    for (const ms of [0, 20, 50, 100, 200, 400]) {
      const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);
      const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: true, showHelp: false });
      await d.whenReady();
      await d.loadModel("/red.glb");
      await new Promise(r => setTimeout(r, ms));
      d.destroy();
      host.remove();
    }
    await new Promise(r => setTimeout(r, 2500));
  });
  assert(pageErrors.length === beforeLoad, `no page errors after destroys 0 to 400 ms after a load (${pageErrors.slice(beforeLoad).join(" | ") || "none"})`);

  section("page-level keys and events reach one viewer");
  // Two viewers with their help cards, side by side where A and B were.
  await run(async () => {
    window.__b.destroy(); window.__c.destroy();
    for (const k of ["a", "b"]) document.getElementById(k).innerHTML = "";
    const mk = (id) => window.Adom3DViewerBabylon9.init(document.getElementById(id), { zUp: true, showViewCube: true, showHelp: true });
    window.__d = mk("a"); window.__e = mk("b");
    await Promise.all([window.__d.whenReady(), window.__e.whenReady()]);
  });
  const cards = () => run(() => ["a", "b"].map(id => { const c = document.getElementById(id).querySelector(".a3d-help-card"); return !!c && !c.hidden; }));
  await page.mouse.move(480, 200);
  await page.keyboard.press("?");
  const overE = await cards();
  assert(!overE[0] && overE[1], `with the pointer over the right viewer, ? opens only its card (${overE})`);
  await page.keyboard.press("?");
  await page.mouse.move(160, 200);
  await page.keyboard.press("?");
  const overD = await cards();
  assert(overD[0] && !overD[1], `after moving to the left viewer, ? opens only that card (${overD})`);
  await page.keyboard.press("Escape");
  const views = await run(async () => {
    const d = window.__d.getCamera(), e = window.__e.getCamera();
    for (const c of [d, e]) { c.alpha = 0.7; c.beta = 1.2; }
    const settle = () => new Promise(r => setTimeout(r, 1500));
    window.dispatchEvent(new CustomEvent("camera:change_view", { detail: { orientation: "top" } }));
    await settle();
    const onWindow = [d.beta, e.beta];
    for (const c of [d, e]) { c.alpha = 0.7; c.beta = 1.2; }
    window.__e.getEngine().getRenderingCanvas().dispatchEvent(new CustomEvent("camera:change_view", { bubbles: true, detail: { orientation: "top" } }));
    await settle();
    return { onWindow, onCanvasE: [d.beta, e.beta] };
  });
  assert(views.onWindow[0] < 0.1 && Math.abs(views.onWindow[1] - 1.2) < 1e-6, `camera:change_view on window turns only the viewer last pointed at (betas ${views.onWindow.map(b => b.toFixed(3))})`);
  assert(views.onCanvasE[1] < 0.1 && Math.abs(views.onCanvasE[0] - 1.2) < 1e-6, `dispatched on a viewer's canvas, it turns that viewer (betas ${views.onCanvasE.map(b => b.toFixed(3))})`);

  section("a destroyed viewer keeps its scene until its textures finish loading");
  // The texture answers after 3 s, longer than any fixed wait the dispose
  // used to allow; the scene must outlive it and then be released.
  const slow = await run(async () => {
    const host = document.createElement('div'); host.className = 'v'; host.style.left = '0'; document.body.appendChild(host);
    const d = window.Adom3DViewerBabylon9.init(host, { zUp: true, showViewCube: false, showHelp: false });
    await d.whenReady();
    const scene = d.getScene();
    new window.BABYLON.Texture("/slow.png", scene);
    const t0 = performance.now();
    d.destroy();
    host.remove();
    await new Promise(r => setTimeout(r, 2500));
    const keptAt2500 = !scene.isDisposed;
    while (!scene.isDisposed && performance.now() - t0 < 20000) await new Promise(r => setTimeout(r, 50));
    return { keptAt2500, disposed: scene.isDisposed, ms: Math.round(performance.now() - t0) };
  });
  assert(slow.keptAt2500, "2.5 s after destroy the scene is still alive while the texture loads");
  assert(slow.disposed && slow.ms >= 2900, `the scene is released once the texture arrives (${slow.ms} ms after destroy)`);
  assert(pageErrors.length === 0, `no page errors in the whole run (${pageErrors.join(" | ") || "none"})`);
} finally {
  await browser.close();
  server.close();
}
console.log(`\n${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  FAIL " + f); process.exit(1); }