master
AdityaAngajala v0.12.8 160fd3c
// The shadow map is sized to the device: 8192 px on a desktop, 2048 on a
// phone or tablet (a coarse pointer on a screen up to 1400 px) or a device
// reporting 4 GB of memory or less. At 8192 the map is several hundred MB, and
// on iOS that killed the tab and reloaded it, over and over (wiki component
// pages, 2026-10-23).
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 2 mm cube, enough for a scene with a shadow caster.
function cubeGlb() {
  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 json = {
    asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ name: "cube", mesh: 0 }],
    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)]);
}
const HARNESS = `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;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, showHelp: false, modelUrl: '/cube.glb' });
  await v.whenReady(); 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 CUBE = cubeGlb();
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"] });
async function shadowSize(device) {
  const page = await browser.newPage();
  await page.evaluateOnNewDocument((d) => {
    if (d.coarse) { const mm = window.matchMedia.bind(window); window.matchMedia = (q) => (/pointer:\s*coarse/.test(q) ? { matches: true, media: q, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {} } : mm(q)); }
    if (d.screen) { Object.defineProperty(screen, "width", { get: () => d.screen[0] }); Object.defineProperty(screen, "height", { get: () => d.screen[1] }); }
    if (d.memory) Object.defineProperty(navigator, "deviceMemory", { get: () => d.memory });
  }, device);
  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 size = await page.evaluate(() => { const g = window.__viewer.getShadowGenerator(); const m = g && g.getShadowMap(); return m ? m.getSize().width : null; });
  await page.close();
  return size;
}

try {
  section("a desktop keeps the 8192 px shadow map");
  eq(await shadowSize({}), 8192, "desktop");
  section("a phone, a tablet or a low-memory device gets 2048 px");
  eq(await shadowSize({ coarse: true, screen: [390, 844] }), 2048, "phone (coarse pointer, 390 x 844)");
  eq(await shadowSize({ coarse: true, screen: [1024, 1366] }), 2048, "tablet (coarse pointer, 1024 x 1366)");
  eq(await shadowSize({ memory: 2 }), 2048, "a desktop reporting 2 GB");
  eq(await shadowSize({ coarse: true, screen: [2560, 1440] }), 8192, "a large touch screen keeps 8192");
} finally {
  await browser.close(); server.close();
  console.log(`\n=== shadow-size ===\n${passed} passed, ${failed} failed`);
  if (failed) { console.log("\nFailures:"); failures.forEach(f => console.log("  - " + f)); }
  process.exitCode = failed ? 1 : 0;
}