master
AdityaAngajala
v0.12.8
160fd3c
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
// State-group choices belong to the model they were made on. The key once
// held only the group's name, so switching Chip off on one part hid the chip
// body on every model in that browser (wiki, 2026-10-23). Pinned:
// - a choice on one model does not touch another model with the same group;
// - it is remembered for the same model across a changed version parameter,
// and a parameter that names another model keeps the two apart;
// - saved choices that would leave nothing on screen are ignored;
// - the old global a3d.state.* keys are removed.
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); } }
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 whose scene is `nodes` (each { name, mesh?: true, children?: [...] }),
// every mesh node a 2 mm cube.
function glb(nodes) {
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 flat = [];
const add = (n) => { const i = flat.length; flat.push(null); const kids = (n.children || []).map(add); flat[i] = { name: n.name, ...(n.mesh ? { mesh: 0 } : {}), ...(kids.length ? { children: kids } : {}) }; return i; };
const top = nodes.map(add);
const json = {
asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: top }], nodes: flat,
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],
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" },
],
bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],
buffers: [{ byteLength: bin.length }],
};
let js = Buffer.from(JSON.stringify(json)); js = Buffer.concat([js, Buffer.alloc((4 - (js.length % 4)) % 4, 0x20)]);
const header = Buffer.alloc(12); header.writeUInt32LE(0x46546c67, 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + js.length + 8 + bin.length, 8);
const ch = (buf, type) => { const h = Buffer.alloc(8); h.writeUInt32LE(buf.length, 0); h.writeUInt32LE(type, 4); return Buffer.concat([h, buf]); };
return Buffer.concat([header, ch(js, 0x4e4f534a), ch(bin, 0x004e4942)]);
}
// Every mesh inside the Chip group: switching it off leaves nothing.
const CHIP_ONLY = glb([{ name: "Adom.Chip", children: [{ name: "body", mesh: true }] }]);
// A board with an LED group beside ungrouped copper.
const BOARD = glb([{ name: "board", mesh: true }, { name: "Adom.Chip", children: [{ name: "led", mesh: true }] }]);
const MODELS = { "/chip.glb": CHIP_ONLY, "/board.glb": BOARD, "/board2.glb": BOARD };
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;width:480px;height:320px}</style></head><body><div id="wrap"></div>
<script type="module">
await import('/adom-3d-viewer-babylon9.esm.js');
const m = new URLSearchParams(location.search).get('m');
const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showHelp: false, intros: false, modelUrl: m });
await v.whenReady();
for (let i = 0; i < 100 && !(v.getStateGroups && v.getStateGroups().length); i++) await new Promise(r => setTimeout(r, 50));
window.__viewer = v; 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"] });
// One page, so every load shares the same localStorage, as one browser does.
const page = await browser.newPage();
async function open(model) {
await page.goto(`http://127.0.0.1:${port}/view.html?m=${encodeURIComponent(model)}`, { waitUntil: "load", timeout: 90000 });
await page.waitForFunction("window.__ready === true", { timeout: 90000 });
}
const chip = () => page.evaluate(() => { const g = window.__viewer.getStateGroups().find(x => x.key === "Adom.Chip"); return g ? g.enabled : null; });
const setChip = (on) => page.evaluate((on) => window.__viewer.setStateGroupEnabled("Adom.Chip", on), on);
const keys = () => page.evaluate(() => Object.keys(localStorage).filter(k => k.startsWith("a3d.state")).sort());
try {
section("the old global keys are removed");
await open("/board.glb");
await page.evaluate(() => { localStorage.setItem("a3d.state.Adom.Chip", "0"); localStorage.setItem("a3d.state.mpn-marking", "0"); });
await open("/board.glb");
eq(await chip(), true, "a global Chip=0 left by an older viewer no longer hides the chip");
eq((await keys()).filter(k => k.startsWith("a3d.state.")).length, 0, "and the global keys are gone");
section("a choice stays with its model");
await setChip(false);
await open("/board.glb?v=2");
eq(await chip(), false, "the same model, republished (new query), keeps Chip off");
await open("/board.glb?id=other");
eq(await chip(), true, "a parameter that names a different model keeps it apart");
await open("/board2.glb");
eq(await chip(), true, "another model with a Chip group is not touched");
await open("/chip.glb");
eq(await chip(), true, "nor is a third");
section("saved choices never leave nothing on screen");
await setChip(false);
eq(await chip(), false, "switching the only group off works for the view it was made in");
await open("/chip.glb");
eq(await chip(), true, "but a reload opens with the model's defaults, since nothing would show");
await open("/board.glb");
eq(await chip(), false, "a model with geometry outside the group keeps its choice");
} finally {
await browser.close(); server.close();
}
console.log(`\n=== state scope ===\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);