master
AdityaAngajala
v0.13.0
12542ed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
// The click-to-load gate and the WebGL context events. A viewer created with
// `gate` shows a card with the model's size, creates no engine until the
// reader presses Load or the host calls openGate(), and runs the loads asked
// for in the meantime once it opens. A load asked for right after init waits
// for the scene. When the browser takes the WebGL context away and gives it
// back, onContextLost and onContextRestored fire and the model paints again.
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 emissive red cube named `Part_cube`, so it shows in pixel counts. */
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.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: "Part_cube", mesh: 0 }],
meshes: [{ name: "Part_mesh", primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
materials: [{ name: "Part_mat", pbrMetallicRoughness: { baseColorFactor: [1, 0, 0, 1], metallicFactor: 0, roughnessFactor: 1 }, emissiveFactor: [1, 0, 0] }],
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 CUBE = 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');
// A fresh viewer in #wrap with these options; the previous one is destroyed.
window.__init = (opts) => {
if (window.__v) window.__v.destroy();
window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showGround: false, showHelp: false, ...opts });
};
// Settles to 'pending' if the promise has not settled within ms.
window.__within = (p, ms) => Promise.race([p.then(() => 'resolved', (e) => 'rejected: ' + (e && e.message)), new Promise(r => setTimeout(() => r('pending'), ms))]);
// Strongly red pixels on the viewer's canvas.
window.__red = () => {
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 red = 0;
for (let i = 0; i < d.length; i += 4) if (d[i] > d[i + 1] + 80 && d[i] > d[i + 2] + 80) red++;
return red;
};
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 === "/cube.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(CUBE); }
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 waitFor = (cond, timeout = 30000) => page.waitForFunction(cond, { timeout, polling: 250 }).then(() => true, () => false);
section("a gated viewer waits for Load");
const closed = await run(async () => {
window.__init({ gate: { bytes: 250 * 1048576, vertices: 3400000, downloadUrl: "/cube.glb" } });
window.__load = window.__v.loadModel("/cube.glb");
const card = document.querySelector("#wrap .a3d-gate");
return {
gated: window.__v.isGated(),
engine: window.__v.getEngine(),
scene: window.__v.getScene(),
text: card ? card.textContent.replace(/\s+/g, " ").trim() : null,
button: !!document.querySelector("#wrap .a3d-gate-load"),
download: document.querySelector("#wrap .a3d-gate a[download]")?.getAttribute("href") || null,
ready: await window.__within(window.__v.whenReady(), 800),
load: await window.__within(window.__load, 10),
};
});
assert(closed.gated === true, "isGated() is true before Load");
assert(!closed.engine && !closed.scene, "no engine or scene exists before Load");
assert(!!closed.text && closed.text.includes("250.0 MB") && closed.text.includes("3.4 M vertices"), `the card gives the size (${closed.text})`);
assert(closed.button, "the card has a Load button");
assert(closed.download === "/cube.glb", `the card links the download (${closed.download})`);
assert(closed.ready === "pending", `whenReady() waits for Load (${closed.ready})`);
assert(closed.load === "pending", `a load asked for before Load waits (${closed.load})`);
await page.click("#wrap .a3d-gate-load");
const opened = await run(async () => {
const report = await window.__v.whenReady();
const load = await window.__within(window.__load, 20000);
return {
gated: window.__v.isGated(),
card: !!document.querySelector("#wrap .a3d-gate"),
report: !!report,
load,
meshes: window.__v.getScene().meshes.filter(m => m.name === "Part_cube").length,
};
});
assert(opened.gated === false && !opened.card, "pressing Load removes the card and clears isGated()");
assert(opened.report, "whenReady() resolves after Load");
assert(opened.load === "resolved" && opened.meshes === 1, `the waiting load runs once the scene is up (${opened.load}, ${opened.meshes} mesh)`);
section("openGate() from the host");
const host = await run(async () => {
window.__init({ gate: {} });
const card = document.querySelector("#wrap .a3d-gate p")?.textContent || "";
const report = await window.__v.openGate();
const again = await window.__within(window.__v.openGate(), 2000);
return { card, version: report && report.version, gated: window.__v.isGated(), again, engine: !!window.__v.getEngine() };
});
assert(!/MB|vertices/.test(host.card), `without sizes the card leaves them out (${host.card})`);
assert(typeof host.version === "string" && host.version.length > 0, `openGate() resolves with the ready report (version ${host.version})`);
assert(host.gated === false && host.engine, "the viewer is running after openGate()");
assert(host.again === "resolved", "a second openGate() resolves too");
section("destroy while gated");
const gone = await run(async () => {
let hooks = 0;
window.__init({ gate: {}, onReady: () => { hooks++; } });
const v = window.__v;
const load = v.loadModel("/cube.glb");
const ready = v.whenReady();
v.destroy();
window.__v = null;
const within = (p) => Promise.race([p, new Promise(r => setTimeout(() => r(null), 3000))]);
const report = await within(ready);
return { load: await window.__within(load, 3000), report, hooks };
});
assert(gone.load !== "pending", `a load waiting behind the gate settles when the viewer is destroyed (${gone.load})`);
assert(!!gone.report && gone.report.destroyed === true && gone.report.ok === false,
`whenReady() asked for before the destroy resolves with destroyed: true, ok: false (${gone.report ? JSON.stringify({ destroyed: gone.report.destroyed, ok: gone.report.ok }) : "pending"})`);
assert(!!gone.report && gone.report.hints.some(h => h.code === "VIEWER_DESTROYED") && gone.report.loadingOverlay === "hidden",
`its hints say VIEWER_DESTROYED and nothing about an overlay (${gone.report ? gone.report.hints.map(h => h.code).join(", ") : "none"})`);
assert(gone.hooks === 0, `onReady is not called for a viewer that never came up (${gone.hooks} calls)`);
section("no gate");
const early = await run(async () => {
window.__init({});
const gated = window.__v.isGated();
await window.__v.loadModel("/cube.glb");
await window.__v.whenReady();
return { gated, card: !!document.querySelector("#wrap .a3d-gate"), meshes: window.__v.getScene().meshes.filter(m => m.name === "Part_cube").length };
});
assert(early.gated === false && !early.card, "without gate the viewer starts at once");
assert(early.meshes === 1, `a load asked for right after init waits for the scene (${early.meshes} mesh)`);
section("WebGL context lost and restored");
await run(async () => {
window.__events = [];
window.__init({
onContextLost: () => window.__events.push("lost"),
onContextRestored: () => window.__events.push("restored"),
});
await window.__v.whenReady();
await window.__v.loadModel("/cube.glb");
window.__v.frameModel();
});
const before = await waitFor("window.__red() > 2000");
assert(before, "the model paints before the loss");
const hasExt = await run(() => {
const c = window.__v.getEngine().getRenderingCanvas();
const gl = c.getContext("webgl2") || c.getContext("webgl");
window.__lose = gl && gl.getExtension("WEBGL_lose_context");
return !!window.__lose;
});
assert(hasExt, "WEBGL_lose_context is available");
if (hasExt) {
await run(() => window.__lose.loseContext());
const lost = await waitFor("window.__events.includes('lost')", 10000);
assert(lost, "onContextLost fires");
await run(() => window.__lose.restoreContext());
const restored = await waitFor("window.__events.includes('restored')", 30000);
assert(restored, `onContextRestored fires (${await run(() => window.__events.join(", "))})`);
const after = await waitFor("window.__red() > 2000", 30000);
assert(after, `the model paints again after the restore (${await run(() => window.__red())} red pixels)`);
}
section("gate.downloadUrl takes only http(s) and relative URLs");
const urls = await run(() => {
const out = {};
for (const u of ["/cube.glb", "cube.glb", "https://example.com/a.glb", "javascript:alert(1)", " JavaScript:alert(1)", "java\tscript:alert(1)", "data:text/html,x"]) {
const host = document.createElement("div"); document.body.appendChild(host);
try {
const v = window.Adom3DViewerBabylon9.init(host, { showHelp: false, gate: { downloadUrl: u } });
out[u] = host.querySelector(".a3d-gate a") ? "link" : "no link";
v.destroy();
} catch (e) { out[u] = "threw"; }
host.remove();
}
return out;
});
assert(urls["/cube.glb"] === "link" && urls["cube.glb"] === "link" && urls["https://example.com/a.glb"] === "link", `relative and https URLs get the link (${JSON.stringify(urls)})`);
assert(["javascript:alert(1)", " JavaScript:alert(1)", "java\tscript:alert(1)", "data:text/html,x"].every(u => urls[u] === "threw"),
"javascript: (any case, with a leading space or a tab inside) and data: URLs make init() throw");
assert(pageErrors.length === 0, `no page 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); }