master
AdityaAngajala v0.12.8 160fd3c
// What a page downloads to show a model, and the BABYLON namespace hosts use.
// The bundle used to import ALL of @babylonjs/core (12.4 MB at startup); the
// viewer now loads only what it uses, BABYLON holds the common classes, and
// loadBabylon() brings the whole engine on demand. A name outside the set is
// undefined (feature checks keep working) and warns once.
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(JSON.stringify(a) === JSON.stringify(b), `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);
function section(t) { console.log("\n  [" + t + "]"); }

// A 1x1 PNG, for a textured material.
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");

/** A GLB of named cubes; `textured` gives them a textured material, `animated` a translation animation. */
function makeGlb(prefix, names, { textured = false, animated = false } = {}) {
  const pos = [], uv = [], 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); }); uv.push(0, 0, 1, 0, 1, 1, 0, 1); 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 uvBuf = pad(Buffer.from(new Float32Array(uv).buffer));
  const idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));
  const times = pad(Buffer.from(new Float32Array([0, 1]).buffer));
  const trans = pad(Buffer.from(new Float32Array([0, 0, 0, 0.02, 0, 0]).buffer));
  const png = pad(PNG);
  const parts = [posBuf, uvBuf, idxBuf, times, trans, png];
  const views = []; let off = 0;
  for (const p of parts) { views.push({ buffer: 0, byteOffset: off, byteLength: p.length }); off += p.length; }
  views[5].byteLength = PNG.length;
  const bin = Buffer.concat(parts);
  const json = {
    asset: { version: "2.0" }, scene: 0,
    scenes: [{ nodes: names.map((_, i) => i) }],
    nodes: names.map((n, i) => ({ name: `${prefix}_${n}`, mesh: 0, translation: [i * 0.03, 0, 0] })),
    meshes: [{ name: `${prefix}_mesh`, primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0 }] }],
    materials: [{ name: `${prefix}_mat`, pbrMetallicRoughness: textured ? { baseColorTexture: { index: 0 } } : { baseColorFactor: [0.8, 0.5, 0.2, 1] } }],
    ...(textured ? { textures: [{ source: 0, name: `${prefix}_tex` }], images: [{ name: `${prefix}_img`, bufferView: 5, mimeType: "image/png" }] } : {}),
    ...(animated ? { animations: [{ name: `${prefix}_anim`, samplers: [{ input: 3, output: 4, interpolation: "LINEAR" }], channels: [{ sampler: 0, target: { node: 0, path: "translation" } }] }] } : {}),
    buffers: [{ byteLength: bin.length }],
    bufferViews: views,
    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: 5126, count: uv.length / 2, type: "VEC2" },
      { bufferView: 2, componentType: 5123, count: idx.length, type: "SCALAR" },
      { bufferView: 3, componentType: 5126, count: 2, type: "SCALAR", min: [0], max: [1] },
      { bufferView: 4, componentType: 5126, count: 2, type: "VEC3" },
    ],
  };
  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 = { "/part.glb": makeGlb("Part", ["body"]) };
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;inset:0;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: true, showHelp: false });
  await v.whenReady(); window.__viewer = v;
  // What the scene holds that a model brought (names carry the model prefix).
  window.__unused = () => {
    const s = v.getScene();
    const pick = (list) => list.map(x => x.name).filter(n => /^(OldWire|NewPart)/.test(n)).sort();
    return { meshes: pick(s.meshes), materials: pick(s.materials), textures: s.textures.filter(t => /OldWire|NewPart/.test(t.name || "")).length,
      animationGroups: s.animationGroups.filter(g => /OldWire|NewPart/.test(g.name)).length, totalMeshes: s.meshes.length, totalMaterials: s.materials.length,
      totalTextures: s.textures.length, camera: !!v.getCamera() };
  };
  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)) { const buf = readFileSync(file); res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream", "Content-Length": buf.length }); return res.end(buf); }
  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 scripts = [];
  const warns = [];
  page.on("console", m => { if (m.type() === "warning" || m.type() === "warn") warns.push(m.text()); });
  page.on("response", r => { const u = r.url(); if (u.endsWith(".js")) scripts.push({ u, len: Number(r.headers()["content-length"] || 0) }); });
  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);

  section("a page downloads the viewer, not the whole engine");
  await run(async () => { await window.__viewer.replaceModel("/part.glb"); });
  const startup = scripts.reduce((a, s) => a + s.len, 0);
  console.log(`    (startup scripts: ${scripts.length} files, ${(startup / 1e6).toFixed(2)} MB)`);
  assert(startup > 0 && startup < 6e6, `startup script bytes under 6 MB (${(startup / 1e6).toFixed(2)} MB; the whole-engine bundle was 12.4 MB)`);
  const meshes = await run(() => window.__viewer.getScene().meshes.filter(m => m.name === "Part_body").length);
  eq(meshes, 1, "and it renders a model");

  section("BABYLON: the common classes are there, the rest load on demand");
  const common = await run(() => ["Vector3", "Color3", "Quaternion", "Matrix", "Mesh", "MeshBuilder", "TransformNode", "StandardMaterial", "PBRMaterial", "Texture", "DynamicTexture", "SceneLoader", "DracoCompression", "ArcRotateCamera", "ShadowGenerator", "Animation", "Material", "ImageProcessingConfiguration", "LoadAssetContainerAsync", "DracoDecoder", "PickingInfo", "Layer", "HighlightLayer", "GlowLayer", "EngineStore"].filter(k => typeof window.BABYLON[k] !== "function" && typeof window.BABYLON[k] !== "object"));
  eq(common, [], "every common class is on window.BABYLON");
  const same = await run(() => window.Adom3DViewerBabylon9.BABYLON === window.BABYLON);
  assert(same, "Adom3DViewerBabylon9.BABYLON is window.BABYLON");
  const layers = await run(async () => {
    const B = window.BABYLON, scene = window.__viewer.getScene(), mesh = scene.getMeshByName("Part_body");
    try {
      const hl = new B.HighlightLayer("t_hl", scene); hl.addMesh(mesh, B.Color3.Red());
      const gl = new B.GlowLayer("t_gl", scene);
      const bg = new B.Layer("t_bg", null, scene, true);
      let ready = false;
      for (let i = 0; i < 120 && !ready; i++) { await new Promise(r => requestAnimationFrame(r)); ready = hl.isReady(mesh.subMeshes[0], false) && gl.isReady(mesh.subMeshes[0], false); }
      const out = { highlight: hl.hasMesh(mesh), effectLayers: scene.effectLayers.length, background: scene.layers.includes(bg), ready };
      hl.dispose(); gl.dispose(); bg.dispose();
      return out;
    } catch (e) { return { err: String(e && e.message || e) }; }
  });
  eq(layers, { highlight: true, effectLayers: 2, background: true, ready: true }, "HighlightLayer, GlowLayer and Layer work before loadBabylon");
  const before = await run(() => typeof window.BABYLON.ParticleSystem);
  eq(before, "undefined", "a class outside the set reads as undefined (feature checks keep working)");
  assert(warns.some(w => /BABYLON\.ParticleSystem/.test(w) && /loadBabylon/.test(w)), "and warns once with the fix");
  const loaded = await run(async () => { const full = await window.Adom3DViewerBabylon9.loadBabylon(); return { full: typeof full.ParticleSystem, ns: typeof window.BABYLON.ParticleSystem, again: (await window.__viewer.loadBabylon()) === full }; });
  eq(loaded, { full: "function", ns: "function", again: true }, "loadBabylon brings the whole engine and fills BABYLON in, once");
  section("the Inspector still opens (it loads the full engine first)");
  const insp = await run(async () => { try { await window.__viewer.showDebugLayer(); await new Promise(r => setTimeout(r, 1500)); return { ok: !!window.__viewer.getScene().debugLayer.isVisible(), full: typeof window.BABYLON.ParticleSystem }; } catch (e) { return { err: String(e && e.message || e) }; } });
  eq(insp, { ok: true, full: "function" }, "the Inspector opens");
} finally {
  await browser.close();
  server.close();
}
console.log(`\n=== bundle ===\n${passed} passed, ${failed} failed`);
if (failures.length) for (const f of failures) console.log("  - " + f);
process.exit(failed ? 1 : 0);