master
AdityaAngajala
v0.13.0
12542ed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
// Camera control a host drives: getCameraState(), moveCamera() to a named view
// or a state, orbit(), and the loadTimeoutMs option. Named face views put the
// camera on that side of the model in both Z-up and Y-up scenes; moves ease
// the short way round, end where asked even without animation frames, and a
// new move cancels the one in flight. A URL load past its timeout fails with
// MODEL_LOAD_TIMEOUT and does not show up later.
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-4) => Math.abs(a - b) < eps;
/** A GLB of one 2 cm cube named `<prefix>_cube`. */
function makeGlb(prefix) {
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: [0.8, 0.5, 0.2, 1] } }],
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("Part");
const LATE = makeGlb("Late");
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.__make = async (opts) => {
if (window.__v) window.__v.destroy();
window.__v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: true, showHelp: false, ...opts });
await window.__v.whenReady();
};
// Camera position relative to its target, in units of the radius.
window.__side = () => { const c = window.__v.getCamera(); c.getViewMatrix(true); const p = c.position, t = c.target; return [(p.x - t.x) / c.radius, (p.y - t.y) / c.radius, (p.z - t.z) / c.radius]; };
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); }
// Answers after 1.5 s: slower than the 500 ms timeout the test sets.
if (url.pathname === "/late.glb") { setTimeout(() => { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); res.end(LATE); }, 1500); 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);
// Which way each named view looks from, in a Z-up and a Y-up scene.
const SIDES = {
true: { front: [1, -1], back: [1, 1], right: [0, 1], left: [0, -1], top: [2, 1], bottom: [2, -1] },
false: { top: [1, 1], bottom: [1, -1] },
};
for (const zUp of [true, false]) {
section(`named views put the camera on that side (zUp ${zUp})`);
await run((z) => window.__make({ zUp: z }), zUp);
await run(async () => { await window.__v.loadModel("/cube.glb"); });
for (const [view, [axis, sign]] of Object.entries(SIDES[zUp])) {
const st = await run(async (v) => { const s = await window.__v.moveCamera(v); return { s, side: window.__side() }; }, view);
assert(st.side[axis] * sign > 0.99, `${view}: the camera sits on the ${sign > 0 ? "+" : "-"}${"XYZ"[axis]} side of its target (${st.side.map(v => v.toFixed(3)).join(", ")})`);
}
}
section("state, easing, the short way round");
await run(() => window.__make({}));
await run(async () => { await window.__v.loadModel("/cube.glb"); });
const st0 = await run(() => window.__v.getCameraState());
assert(st0 && ["alpha", "beta", "radius"].every(k => Number.isFinite(st0[k])) && st0.target.length === 3, `getCameraState() reports alpha, beta, radius and target (${JSON.stringify(st0)})`);
// Halfway is read by driving one animation frame by hand with the clock
// set to the middle of the move: under software GL a frame takes so long
// that a real timer would only fire after the move is over.
const eased = await run(async () => {
const v = window.__v;
await v.moveCamera({ alpha: 0.1, beta: 1 });
const realNow = performance.now, realRaf = window.requestAnimationFrame;
let now = realNow.call(performance), mid;
const frames = [];
performance.now = () => now;
window.requestAnimationFrame = (cb) => { frames.push(cb); return frames.length; };
let p;
try {
p = v.moveCamera({ alpha: 2 * Math.PI - 0.1, radius: v.getCameraState().radius * 2 }, { ms: 600 });
now += 300;
frames.shift()(now);
mid = v.getCameraState();
} finally {
performance.now = realNow;
window.requestAnimationFrame = realRaf;
}
const end = await p;
return { mid, end };
});
assert(near(eased.mid.alpha, 0), `a move from alpha 0.1 to 2pi - 0.1 is at 0 halfway, not round the long way (mid ${eased.mid.alpha.toFixed(4)})`);
assert(near(Math.cos(eased.end.alpha), Math.cos(-0.1)) && near(Math.sin(eased.end.alpha), Math.sin(-0.1)), `it ends at the asked angle (${eased.end.alpha.toFixed(4)})`);
assert(eased.mid.radius > st0.radius && eased.mid.radius < eased.end.radius, "the radius is in between halfway through");
const target = await run(async () => (await window.__v.moveCamera({ target: [0.01, 0.02, 0.03] })).target);
assert(target.every((v, i) => near(v, [0.01, 0.02, 0.03][i])), "moveCamera() sets the target");
section("home, fit and orbit");
const homes = await run(async () => {
const v = window.__v;
await v.moveCamera({ alpha: 0.3, beta: 1.2 });
const viaMove = await v.moveCamera("home", { ms: 200 });
await v.moveCamera({ alpha: 0.3, beta: 1.2 });
v.goHome();
return { viaMove, viaGoHome: v.getCameraState() };
});
assert(["alpha", "beta", "radius"].every(k => near(homes.viaMove[k], homes.viaGoHome[k], 1e-6)), "moveCamera('home') ends where goHome() does");
const fit = await run(async () => {
const v = window.__v;
await v.moveCamera({ radius: 5 });
const before = v.getCameraState();
const p = v.moveCamera("fit", { ms: 200 });
const during = v.getCameraState();
const end = await p;
return { before, during, end };
});
assert(near(fit.during.radius, fit.before.radius, 1e-6), "a 'fit' move does not jump the camera before it starts");
assert(fit.end.radius < 1, `'fit' brings a far camera back to the model (radius ${fit.end.radius.toFixed(4)})`);
const unclamped = await run(async () => {
const v = window.__v, c = v.getCamera();
const frames = (n) => new Promise(r => { const f = () => (--n > 0 ? requestAnimationFrame(f) : r()); requestAnimationFrame(f); });
c.upperRadiusLimit = null;
await v.moveCamera({ radius: 5 });
await frames(2);
const start = c.radius;
const p = v.moveCamera("fit", { ms: 3000 });
await frames(2);
const early = c.radius;
await p;
return { start, early, end: c.radius, upper: c.upperRadiusLimit };
});
assert(unclamped.start > 4.9 && unclamped.early > unclamped.start * 0.8, `a 'fit' move eases from a view its own limits would clamp, without a jump (radius ${unclamped.start.toFixed(3)} -> ${unclamped.early.toFixed(3)})`);
assert(Number.isFinite(unclamped.upper) && unclamped.end <= unclamped.upper, `and sets fit's limits when it lands (radius ${unclamped.end.toFixed(4)}, limit ${unclamped.upper})`);
const orb = await run(async () => { const v = window.__v; const a = v.getCameraState().alpha; const s = await v.orbit({ degrees: 90, ms: 300 }); return s.alpha - a; });
assert(near(orb, Math.PI / 2), `orbit({ degrees: 90 }) turns a quarter round (${orb.toFixed(4)})`);
section("moves end where asked without animation frames, and the latest move wins");
const noFrames = await run(async () => {
const v = window.__v, raf = window.requestAnimationFrame;
window.requestAnimationFrame = () => 0;
try { return await v.moveCamera({ alpha: 1.234 }, { ms: 200 }); } finally { window.requestAnimationFrame = raf; }
});
assert(near(noFrames.alpha, 1.234), "with no animation frames, the move still ends at its goal on its timer");
const latest = await run(async () => {
const v = window.__v;
const slow = v.moveCamera({ alpha: 2 }, { ms: 1000 });
await new Promise(r => setTimeout(r, 100));
const fast = await v.moveCamera({ alpha: -1 });
await slow;
await new Promise(r => setTimeout(r, 1300));
return { fast: fast.alpha, after: v.getCameraState().alpha };
});
assert(near(latest.fast, -1) && near(latest.after, -1), `a new move cancels the one in flight (camera stays at ${latest.after.toFixed(4)})`);
const bad = await run(async () => { try { await window.__v.moveCamera("sideways"); return "resolved"; } catch (e) { return String(e.message); } });
assert(/unknown view/.test(bad), `an unknown view name rejects (${bad})`);
section("loadTimeoutMs");
await run(() => window.__make({ loadTimeoutMs: 500 }));
const timedOut = await run(async () => {
const t0 = performance.now();
try { await window.__v.loadModel("/late.glb"); return { ok: true }; }
catch (e) { return { ok: false, ms: performance.now() - t0, msg: String(e.message) }; }
});
assert(!timedOut.ok && timedOut.ms < 1200, `a load slower than loadTimeoutMs rejects at the timeout (${Math.round(timedOut.ms || 0)} ms: ${timedOut.msg})`);
const hint = await run(() => window.__v.getReadyReport().hints.map(h => h.code));
assert(hint.includes("MODEL_LOAD_TIMEOUT") && !hint.includes("MODEL_LOAD_FAILED"), `the ready report says MODEL_LOAD_TIMEOUT (${hint.join(", ")})`);
await new Promise(r => setTimeout(r, 2500));
const lateMeshes = await run(() => window.__v.getScene().meshes.filter(m => /^Late_/.test(m.name)).length);
assert(lateMeshes === 0, "the model that arrives after its timeout is not left in the scene");
const recovered = await run(async () => { await window.__v.loadModel("/cube.glb"); return window.__v.getReadyReport().hints.map(h => h.code); });
assert(!recovered.includes("MODEL_LOAD_TIMEOUT"), "a later successful load clears the hint");
await run(() => window.__make({}));
const noLimit = await run(async () => { await window.__v.loadModel("/late.glb"); return window.__v.getScene().meshes.filter(m => /^Late_/.test(m.name)).length; });
assert(noLimit > 0, "without loadTimeoutMs the slow load still finishes");
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); }