master
AdityaAngajala v0.13.0 12542ed
// Pick and hover events, findNodes and highlight. A click that does not drag
// fires 'pick' with the content mesh under it (null on empty space) and its
// path from the model root; a drag, the view cube's corner and a removed
// listener fire nothing. 'hover' fires when the mesh under the pointer
// changes. findNodes matches names, RegExps and predicates over content
// only. Highlights light one mesh even when its material is shared, stack
// with the latest on top, and give each mesh its own look back on clear.
// Picks and the view cube's corner are also checked on a 2x display.
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 + "]"); }
const near = (a, b, eps = 1e-3) => Math.abs(a - b) < eps;

/**
 * A GLB of 1 cm grey boxes sharing one material: node U1 holding mesh node
 * U1_body at the origin, and pad_7 and pad_17 2.5 cm to either side.
 */
function makeGlb() {
  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.005, v[1] * 0.005, v[2] * 0.005); }); 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 prim = { attributes: { POSITION: 0 }, indices: 1, material: 0 };
  const json = {
    asset: { version: "2.0" }, scene: 0,
    scenes: [{ nodes: [0, 2, 3] }],
    nodes: [
      { name: "U1", children: [1] },
      { name: "U1_body", mesh: 0 },
      { name: "pad_7", mesh: 1, translation: [0.025, 0, 0] },
      { name: "pad_17", mesh: 2, translation: [-0.025, 0, 0] },
    ],
    meshes: [{ name: "body", primitives: [prim] }, { name: "p7", primitives: [prim] }, { name: "p17", primitives: [prim] }],
    materials: [{ name: "grey", pbrMetallicRoughness: { baseColorFactor: [0.5, 0.5, 0.5, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: [0.5, 0.5, 0.5] }],
    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.005, -0.005, -0.005], max: [0.005, 0.005, 0.005] },
      { 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 PARTS = makeGlb();
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:400px}</style></head><body><div id="wrap"></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), {
    zUp: true, showViewCube: true, showHelp: false,
    onGroundCreated: (g) => { window.__ground = g; },
  });
  await window.__v.whenReady();
  await window.__v.loadModel('/parts.glb');
  window.__v.frameModel();
  window.__mesh = (name) => window.__v.getScene().getMeshByName(name);
  // A page point over the middle of the named mesh, found by picking a grid
  // in CSS pixels (scene.pick's unit at any pixel density).
  window.__at = (name) => {
    const s = window.__v.getScene(), c = window.__v.getEngine().getRenderingCanvas();
    const hits = [];
    for (let y = 4; y < c.clientHeight; y += 4) for (let x = 4; x < c.clientWidth; x += 4) {
      const p = s.pick(x, y, m => m.isPickable && m.isVisible);
      if (p.hit && p.pickedMesh && p.pickedMesh.name === name) hits.push([x, y]);
    }
    if (!hits.length) return null;
    const cx = hits.reduce((a, h) => a + h[0], 0) / hits.length, cy = hits.reduce((a, h) => a + h[1], 0) / hits.length;
    hits.sort((a, b) => Math.hypot(a[0] - cx, a[1] - cy) - Math.hypot(b[0] - cx, b[1] - cy));
    const r = c.getBoundingClientRect();
    return { x: r.left + hits[0][0], y: r.top + hits[0][1] };
  };
  // Strongly blue pixels on the canvas.
  window.__blue = () => {
    const src = window.__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 n = 0;
    for (let i = 0; i < d.length; i += 4) if (d[i + 2] > d[i] + 80 && d[i + 2] > d[i + 1] + 50) n++;
    return n;
  };
  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 (url.pathname === "/parts.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(PARTS); }
  if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }
  if (url.pathname === "/favicon.ico") { res.writeHead(204); return res.end(); }
  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)));
  page.on("console", (m) => { if (m.type() === "error") pageErrors.push("console: " + m.text() + " " + (m.location()?.url || "")); });
  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 waitFor = (cond, timeout = 30000) => page.waitForFunction(cond, { timeout, polling: 100 }).then(() => true, () => false);
  const pause = (ms) => new Promise(r => setTimeout(r, ms));

  section("findNodes");
  const found = await run(() => {
    const v = window.__v, names = (a) => a.map(n => n.name);
    const all = v.findNodes(() => true);
    const sceneMeshes = v.getScene().meshes;
    let threw = null;
    try { v.findNodes(42); } catch (e) { threw = e.message; }
    const g = /^pad_/g;
    return {
      byName: names(v.findNodes("U1")),
      byRe: names(v.findNodes(/^pad_/)),
      byGlobalRe: [names(v.findNodes(g)), names(v.findNodes(g))],
      byFn: names(v.findNodes(n => n.name.endsWith("_body"))),
      none: v.findNodes("nope").length,
      groundIncluded: !!window.__ground && all.includes(window.__ground),
      viewerMeshesLeftOut: sceneMeshes.filter(m => !all.includes(m)).length,
      threw,
    };
  });
  assert(JSON.stringify(found.byName) === '["U1"]', `a name finds that node (${found.byName})`);
  assert(JSON.stringify(found.byRe) === '["pad_7","pad_17"]', `a RegExp finds every match in scene order (${found.byRe})`);
  assert(found.byGlobalRe[0].length === 2 && found.byGlobalRe[1].length === 2, "a RegExp with the g flag finds the same nodes on every call");
  assert(JSON.stringify(found.byFn) === '["U1_body"]', `a function finds the nodes it accepts (${found.byFn})`);
  assert(found.none === 0, "an unknown name finds nothing");
  assert(!found.groundIncluded && found.viewerMeshesLeftOut > 0, `the ground and the viewer's own meshes are left out (${found.viewerMeshesLeftOut} left out)`);
  assert(!!found.threw, `a query that is not a name, RegExp or function throws (${found.threw})`);

  section("highlight: overlay");
  await waitFor("window.__blue() < 50");
  const blueBefore = await run(() => window.__blue());
  const lit = await run(() => {
    const v = window.__v, p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");
    const own = { on: p7.renderOverlay, color: p7.overlayColor.asArray(), alpha: p7.overlayAlpha };
    window.__own = own;
    window.__h = v.highlight("pad_7");
    return {
      meshes: window.__h.meshes.map(m => m.name),
      shared: p7.material === p17.material,
      on: p7.renderOverlay, alpha: p7.overlayAlpha, color: p7.overlayColor.asArray(),
      other: !!p17.renderOverlay,
    };
  });
  assert(JSON.stringify(lit.meshes) === '["pad_7"]', `highlight(name) returns the meshes it lit (${lit.meshes})`);
  assert(lit.on && near(lit.alpha, 0.75) && near(lit.color[0], 0.2) && near(lit.color[1], 0.52) && near(lit.color[2], 1), `default overlay: blue at 0.75 (${lit.color.map(c => c.toFixed(2))} @ ${lit.alpha})`);
  assert(lit.shared && lit.other === false, "a mesh sharing the material stays unlit");
  const blueLit = await waitFor(`window.__blue() > ${blueBefore + 300}`);
  assert(blueLit, `the highlight paints (${blueBefore} blue pixels before, ${await run(() => window.__blue())} after)`);
  const unlit = await run(() => {
    window.__h.clear();
    const p7 = window.__mesh("pad_7");
    return { on: p7.renderOverlay, color: p7.overlayColor.asArray(), alpha: p7.overlayAlpha, own: window.__own };
  });
  assert(unlit.on === unlit.own.on && unlit.alpha === unlit.own.alpha && JSON.stringify(unlit.color) === JSON.stringify(unlit.own.color), "clear() gives the mesh its own overlay settings back");
  const group = await run(() => { const h = window.__v.highlight("U1"); const r = h.meshes.map(m => m.name); h.clear(); return r; });
  assert(JSON.stringify(group) === '["U1_body"]', `a transform node lights the meshes under it (${group})`);

  section("highlight: stacking");
  const stack = await run(() => {
    const v = window.__v, p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");
    const c = (m) => [...m.overlayColor.asArray().map(x => +x.toFixed(2)), +m.overlayAlpha.toFixed(2), !!m.renderOverlay];
    const a = v.highlight(/^pad_/, { color: "#ff0000" });
    const b = v.highlight("pad_7", { color: [0, 1, 0], alpha: 0.5 });
    const both = [c(p7), c(p17)];
    b.clear();
    const afterB = c(p7);
    a.clear();
    const afterA = [c(p7), c(p17)];
    const x = v.highlight("pad_7"), y = v.highlight("U1");
    v.clearHighlight();
    let staleOk = true;
    try { x.clear(); y.clear(); } catch { staleOk = false; }
    return { both, afterB, afterA, cleared: [!!p7.renderOverlay, !!window.__mesh("U1_body").renderOverlay], staleOk };
  });
  assert(JSON.stringify(stack.both[0]) === "[0,1,0,0.5,true]" && JSON.stringify(stack.both[1]) === "[1,0,0,0.75,true]", `where two highlights share a mesh the later shows (${JSON.stringify(stack.both)})`);
  assert(JSON.stringify(stack.afterB) === "[1,0,0,0.75,true]", `clearing the later one brings back the one beneath (${stack.afterB})`);
  assert(stack.afterA[0][4] === false && stack.afterA[1][4] === false, "clearing both leaves nothing lit");
  assert(stack.cleared.every(on => on === false), "clearHighlight() removes every highlight");
  assert(stack.staleOk, "clear() on a highlight already removed does nothing");

  section("highlight: outline");
  const outline = await run(async () => {
    const v = window.__v, s = v.getScene(), p7 = window.__mesh("pad_7"), p17 = window.__mesh("pad_17");
    const o = v.highlight("pad_17", { mode: "outline", color: "#ffaa00" });
    const layer = s.effectLayers.find(l => l.name === "a3d-highlight");
    const r = { layer: !!layer, has: !!layer && layer.hasMesh(p17), overlay: !!p17.renderOverlay };
    await new Promise(res => { let n = 0; const ob = s.onAfterRenderObservable.add(() => { if (++n >= 3) { s.onAfterRenderObservable.remove(ob); res(); } }); });
    o.clear();
    r.afterClear = layer.hasMesh(p17);
    const out = v.highlight("pad_7", { mode: "outline" });
    const over = v.highlight("pad_7");
    r.overlayOnTop = [!!p7.renderOverlay, layer.hasMesh(p7)];
    over.clear();
    r.outlineBack = [!!p7.renderOverlay, layer.hasMesh(p7)];
    out.clear();
    return r;
  });
  assert(outline.layer && outline.has && outline.overlay === false, "mode outline draws the mesh in the viewer's highlight layer, without an overlay");
  assert(outline.afterClear === false, "clear() takes it out of the layer");
  assert(JSON.stringify(outline.overlayOnTop) === "[true,false]" && JSON.stringify(outline.outlineBack) === "[false,true]", `an overlay over an outline shows, and clearing it brings the outline back (${JSON.stringify(outline)})`);
  const bad = await run(() => ["glow", "red", 2].map((x, i) => {
    try { window.__v.highlight("pad_7", i === 0 ? { mode: x } : i === 1 ? { color: x } : { alpha: x }); return null; } catch (e) { return e.message; }
  }));
  assert(bad.every(Boolean), `an unknown mode, a color name and alpha 2 throw (${bad.join(" | ")})`);
  await run(() => window.__v.clearHighlight());

  section("pick");
  const P7 = await run(() => window.__at("pad_7"));
  const BODY = await run(() => window.__at("U1_body"));
  assert(!!P7 && !!BODY, `pad_7 and U1_body are on screen (${JSON.stringify(P7)} ${JSON.stringify(BODY)})`);
  await run(() => {
    window.__picks = [];
    window.__thrown = 0;
    window.__offThrow = window.__v.on("pick", () => { window.__thrown++; throw new Error("listener bug"); });
    window.__offPick = window.__v.on("pick", (e) => window.__picks.push({ name: e.mesh ? e.mesh.name : null, path: e.path, point: e.point, button: e.button, x: e.x, y: e.y }));
  });
  await page.mouse.click(P7.x, P7.y);
  await waitFor("window.__picks.length >= 1", 5000);
  await page.mouse.click(BODY.x, BODY.y);
  await waitFor("window.__picks.length >= 2", 5000);
  await page.mouse.click(30, 370);
  await waitFor("window.__picks.length >= 3", 5000);
  const picks = await run(() => ({ picks: window.__picks, thrown: window.__thrown }));
  const [p1, p2, p3] = picks.picks;
  assert(p1 && p1.name === "pad_7" && JSON.stringify(p1.path) === '["pad_7"]' && p1.button === 0, `a click on pad_7 picks it (${JSON.stringify(p1)})`);
  assert(p1 && Array.isArray(p1.point) && p1.point.length === 3 && p1.point.every(Number.isFinite) && Math.abs(p1.x - P7.x) < 1 && Math.abs(p1.y - P7.y) < 1, "the pick carries the world point and the canvas position");
  assert(p2 && p2.name === "U1_body" && JSON.stringify(p2.path) === '["U1","U1_body"]', `the path runs from the model root down (${p2 && JSON.stringify(p2.path)})`);
  assert(p3 && p3.name === null && p3.path.length === 0 && p3.point === null, `a click on empty space picks null (${JSON.stringify(p3)})`);
  assert(picks.thrown === 3, "a listener that throws does not stop the others");
  await page.mouse.move(P7.x, P7.y);
  await page.mouse.down();
  for (let i = 1; i <= 8; i++) await page.mouse.move(P7.x + i * 6, P7.y + i * 2);
  await page.mouse.up();
  await pause(400);
  assert(await run(() => window.__picks.length) === 3, "a drag is not a pick");

  section("hover");
  await run(() => { window.__hovers = []; window.__offHover = window.__v.on("hover", (e) => window.__hovers.push(e.mesh ? e.mesh.name : null)); });
  // Settle on empty space first so the next move is a change.
  await page.mouse.move(30, 370); await pause(200);
  await run(() => { window.__hovers = []; });
  await page.mouse.move(P7.x, P7.y);
  const h1 = await waitFor("window.__hovers[window.__hovers.length - 1] === 'pad_7'", 5000);
  await pause(150);
  await page.mouse.move(P7.x + 2, P7.y + 1);
  await pause(300);
  const sameCount = await run(() => window.__hovers.length);
  await page.mouse.move(BODY.x, BODY.y);
  const h2 = await waitFor("window.__hovers[window.__hovers.length - 1] === 'U1_body'", 5000);
  await pause(150);
  await page.mouse.move(30, 370);
  const h3 = await waitFor("window.__hovers[window.__hovers.length - 1] === null", 5000);
  const hovers = await run(() => window.__hovers);
  assert(h1, `moving onto pad_7 fires hover (${hovers})`);
  assert(sameCount === 1, `moving within the same mesh fires nothing more (${sameCount} events)`);
  assert(h2 && h3, `moving to another mesh, then off content, fires each change (${hovers.join(", ")})`);
  await run(() => window.__offHover());

  section("the view cube's corner and removed listeners");
  // The cube sits in the top-right corner; aim at its middle.
  const cube = await run(() => { const c = window.__v.getEngine().getRenderingCanvas(); return { x: c.clientWidth - 50, y: 50 }; });
  const before = await run(() => window.__picks.length);
  await page.mouse.click(cube.x, cube.y);
  await pause(400);
  assert(await run(() => window.__picks.length) === before, "a click in the view cube's corner is not a pick");
  await run(() => { window.__offPick(); window.__offThrow(); });
  await page.mouse.click(30, 370);
  await pause(400);
  assert(await run(() => window.__picks.length) === before, "a removed listener hears nothing");
  const unknown = await run(() => { try { window.__v.on("click", () => {}); return null; } catch (e) { return e.message; } });
  assert(!!unknown, `an unknown event name throws (${unknown})`);

  section("highlights across a model reload");
  const reload = await run(async () => {
    const v = window.__v;
    const h = v.highlight("pad_7");
    v.clearScene();
    let ok = true;
    try { h.clear(); v.clearHighlight(); } catch { ok = false; }
    const gone = v.findNodes(/^pad_/).length;
    await v.loadModel("/parts.glb");
    const again = v.highlight("pad_7");
    return { ok, gone, again: again.meshes.length, on: window.__mesh("pad_7").renderOverlay };
  });
  assert(reload.ok && reload.gone === 0, "clearing a highlight whose model was cleared does nothing");
  assert(reload.again === 1 && reload.on, "the reloaded model highlights again");

  section("picks on a 2x display");
  const hi = await browser.newPage();
  hi.on("pageerror", (e) => pageErrors.push(String(e && e.message || e)));
  await hi.setViewport({ width: 640, height: 400, deviceScaleFactor: 2 });
  await hi.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });
  await hi.waitForFunction("window.__ready === true", { timeout: 90000 });
  const backing = await hi.evaluate(() => { const c = window.__v.getEngine().getRenderingCanvas(); return [c.width, c.clientWidth]; });
  assert(backing[0] === backing[1] * 2, `the canvas renders at 2x (${backing[0]} for ${backing[1]} CSS pixels)`);
  const P7hi = await hi.evaluate(() => window.__at("pad_7"));
  await hi.evaluate(() => { window.__picks = []; window.__v.on("pick", (e) => window.__picks.push({ name: e.mesh ? e.mesh.name : null, x: e.x, y: e.y })); });
  await hi.mouse.click(P7hi.x, P7hi.y);
  await hi.waitForFunction("window.__picks.length >= 1", { timeout: 5000, polling: 100 }).catch(() => {});
  const hiPick = await hi.evaluate(() => window.__picks[0]);
  assert(hiPick && hiPick.name === "pad_7" && Math.abs(hiPick.x - P7hi.x) < 1 && Math.abs(hiPick.y - P7hi.y) < 1, `a click on pad_7 picks it, in CSS pixels (${JSON.stringify(hiPick)})`);
  await hi.mouse.click(640 - 50, 50);
  await pause(400);
  assert(await hi.evaluate(() => window.__picks.length) === 1, "a click in the view cube's corner is not a pick");
  await hi.close();

  assert(pageErrors.length === 0, `no page or console errors (${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); }