master
AdityaAngajala v0.13.0 12542ed
// Layer intro previews (adom/adom-3d-viewer#8): a hidden layer declared with
// extras.adomLayer.intro fades in after load, holds, fades out, and its panel
// toggle reads as pressed while it shows; afterwards it rests hidden. A click
// during the intro keeps the layer on; replay plays it again; intros:false
// never plays. Runs against dist-standalone in headless Chrome.
import http from "node:http";
import { existsSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
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); } }
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 a visible "chip" layer and a hidden "fov" layer carrying an intro. */
function makeGlb(intro) {
  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 json = {
    asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0, 1] }],
    nodes: [
      { name: "Chip", mesh: 0, extras: { adomLayer: { key: "chip", label: "Chip", group: "Body" } } },
      { name: "Adom.FOV", mesh: 0, translation: [0, 0.004, 0], extras: { adomLayer: { key: "fov", label: "Field of view", group: "Optics", hidden: true, ...(intro ? { intro } : {}) } } },
    ],
    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ name: "cone", pbrMetallicRoughness: { baseColorFactor: [0.2, 0.6, 1, 0.5] }, alphaMode: "BLEND", doubleSided: true }],
    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 = {
  "/intro.glb": makeGlb({ fadeInAt: 1.2, fadeOutAt: 2.8, highlightButton: true, fadeMs: 200 }),
  "/plain.glb": makeGlb(null),
  "/bad.glb": makeGlb({ fadeInAt: "soon", fadeOutAt: -5, fadeMs: 99999 }),
};
const HARNESS = (model, intros) => `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;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: false, showHelp: false, modelUrl: '${model}'${intros === false ? ", intros: false" : ""} });
  await v.whenReady(); window.__viewer = v; window.__ready = true; window.__t0 = performance.now();
</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(url.searchParams.get("model") || "/intro.glb", url.searchParams.get("intros") !== "0")); }
  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(require_fs().readFileSync(file)); }
  res.writeHead(404); res.end();
});
import * as fsMod from "node:fs"; function require_fs() { return fsMod; }
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", "esm", "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"] });
async function open(query) {
  const page = await browser.newPage();
  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 });
  return page;
}
const state = (page) => page.evaluate(() => {
  const v = window.__viewer, s = v.getScene();
  const fov = s.meshes.filter(m => m.name.startsWith("Adom.FOV"));
  return { layers: v.getLayers(), intros: v.getIntros(), fovShown: fov.some(m => m.isVisible), fovAlpha: fov.map(m => Math.round(m.visibility * 100) / 100),
    rowChecked: [...document.querySelectorAll(".layers-row")].map(r => r.textContent.trim() + ":" + r.querySelector("input").checked + ":" + r.classList.contains("intro")),
    replay: !!document.querySelector(".layers-replay") };
});
// The intro's timers start at load, and a busy machine can be anywhere in
// them by the time a fixed sleep ends, so each check waits for the state it
// is about.
const until = (page, fn, timeout = 20000) => page.waitForFunction(fn, { timeout, polling: "raf" });
const introActive = () => { const i = window.__viewer.getIntros()[0]; return !!i && i.active; };
const introOver = () => { const i = window.__viewer.getIntros()[0]; return !!i && !i.active && !i.pending; };
// Past the moment the intro's fade-out would have ended (fadeOutAt 2.8 s + 200 ms), counted from after load.
const pastFadeOut = () => performance.now() - window.__t0 > 3300;

try {
  section("declared intro: hidden at load, shows pressed while fading in, rests hidden after");
  {
    const page = await open("model=/intro.glb");
    await page.evaluate(() => document.querySelector(".layers-toggle").click());
    const t0 = await state(page);
    eq(t0.intros.length, 1, "one intro declared");
    eq(t0.intros[0].name, "fov", "on the hidden layer");
    eq(t0.intros[0].fadeInAt, 1.2, "fadeInAt parsed"); eq(t0.intros[0].fadeOutAt, 2.8, "fadeOutAt parsed");
    assert(t0.intros[0].pending, "pending right after load"); assert(!t0.fovShown, "the layer is hidden before fadeInAt");
    assert(t0.replay, "the panel offers Replay intro");
    await until(page, introActive);
    const mid = await state(page);
    assert(mid.intros[0].active, "active between fadeInAt and fadeOutAt");
    assert(mid.fovShown, "the meshes show during the intro");
    assert(mid.rowChecked.some(r => r.startsWith("Field of view:true:true")), `the toggle reads pressed and pulsing (${mid.rowChecked.join(" | ")})`);
    assert(mid.layers.find(l => l.name === "fov").visible === false, "but the layer's own state stays hidden");
    await until(page, introOver);
    const after = await state(page);
    assert(!after.intros[0].active && !after.intros[0].pending, "settled after fadeOutAt");
    assert(!after.fovShown, "the layer rests hidden");
    assert(after.fovAlpha.every(a => a === 1), "mesh visibility restored to 1 for a clean later toggle");
    assert(after.rowChecked.some(r => r.startsWith("Field of view:false:false")), "the toggle rests off");
    await page.close();
  }

  section("a click during the intro keeps the layer on; replay plays it again");
  {
    const page = await open("model=/intro.glb");
    await page.evaluate(() => document.querySelector(".layers-toggle").click());
    await until(page, introActive);
    await page.evaluate(() => { const row = [...document.querySelectorAll(".layers-row")].find(r => r.textContent.includes("Field of view")); row.querySelector("input").click(); });
    await until(page, pastFadeOut);
    const kept = await state(page);
    assert(kept.layers.find(l => l.name === "fov").visible === true && kept.fovShown, "the layer stays on after the intro would have ended");
    assert(!kept.intros[0].active, "and the intro is over");
    await page.evaluate(() => window.__viewer.setLayerVisible("fov", false));
    const replayed = await page.evaluate(() => window.__viewer.replayIntros());
    eq(replayed, true, "replay accepted");
    await until(page, introActive);
    const again = await state(page);
    assert(again.intros[0].active && again.fovShown, "the intro plays again");
    await page.evaluate(() => window.__viewer.stopIntros());
    const stopped = await state(page);
    assert(!stopped.intros[0].active && !stopped.fovShown, "stopIntros cancels and rests hidden");
    await page.close();
  }

  section("intros:false never plays; no intro means no replay control; bad numbers fall back");
  {
    const page = await open("model=/intro.glb&intros=0");
    // Watch every frame until past the fade-out: the intro must never show.
    const everActive = await page.evaluate(() => new Promise(r => {
      const s = window.__viewer.getScene(); let seen = false;
      const o = s.onAfterRenderObservable.add(() => {
        if (window.__viewer.getIntros()[0].active) seen = true;
        if (performance.now() - window.__t0 > 3300) { s.onAfterRenderObservable.remove(o); r(seen); }
      });
    }));
    const s = await state(page);
    assert(!everActive && !s.intros[0].active && !s.intros[0].pending && !s.fovShown, "nothing plays with intros:false");
    eq(await page.evaluate(() => window.__viewer.replayIntros()), true, "an explicit replay still works");
    await page.close();
    const plain = await open("model=/plain.glb");
    await page.evaluate; await plain.evaluate(() => document.querySelector(".layers-toggle").click());
    const ps = await state(plain);
    eq(ps.intros.length, 0, "no intro declared"); assert(!ps.replay, "no replay control");
    eq(await plain.evaluate(() => window.__viewer.replayIntros()), false, "replay answers false");
    await plain.close();
    const bad = await open("model=/bad.glb");
    const bs = await state(bad);
    eq(bs.intros[0].fadeInAt, 1.5, "a non-number fadeInAt falls back to 1.5 s");
    eq(bs.intros[0].fadeOutAt, 6.5, "a negative fadeOutAt falls back to fadeInAt + 5");
    await bad.close();
  }
} finally {
  await browser.close(); server.close();
}
console.log(`\n=== intro ===\n${passed} passed, ${failed} failed`);
if (failed) { console.log("\nFailures:"); failures.forEach(f => console.log("  - " + f)); process.exit(1); }