master
AdityaAngajala v0.12.8 160fd3c
// adom/adom-3d-viewer#6 (Ray): orbiting through the underside stopped dead
// near a flat bottom view and felt inverted, because the camera carried a
// numeric lower beta limit (-100) with Babylon's default upper limit
// (PI - 0.01): over the top was free, through the bottom was clamped. This
// test drives the built bundle in headless Chrome with real pointer drags
// and checks that the orbit passes both poles in both frames (Y-up, Z-up),
// that beta keeps moving in the drag's direction after the pole, and that
// the limits are unset. Bounded at 120 s.
import http from "node:http";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");
const require = createRequire(import.meta.url);
const deadline = Date.now() + 120_000;
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 + "]"); }
function left() { return Math.max(1000, deadline - Date.now()); }

function makeBoxGlb() {
  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 posBuf = Buffer.from(new Float32Array(pos).buffer);
  const 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: [{ mesh: 0, name: "chip_body" }],
    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.9, 0.55, 0.1, 1], metallicFactor: 0.2, roughnessFactor: 0.5 } }],
    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 GLB = makeBoxGlb();

const HARNESS = (zUp) => `<!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: ${zUp}, showViewCube: false, showGround: false, modelUrl: '/chip.glb' });
  await v.whenReady();
  window.__viewer = v;
  window.__cam = () => { const c = v.getCamera(); return { alpha: c.alpha, beta: c.beta, lower: c.lowerBetaLimit, upper: c.upperBetaLimit, upsideDown: c.allowUpsideDown }; };
  window.__setBeta = (b) => { const c = v.getCamera(); c.beta = b; c.inertialBetaOffset = 0; };
  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 === "/y.html" || url.pathname === "/z.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS(url.pathname === "/z.html")); }
  if (url.pathname === "/chip.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(GLB); }
  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 readdirSyncSafe(d) { try { return require("node:fs").readdirSync(d); } catch { return []; } }
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 readdirSyncSafe(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }
  for (const p of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) 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"],
});

// Drag vertically on the canvas center in steps; returns beta before and after.
async function dragVertical(page, dy, steps = 12) {
  const box = await (await page.$("#wrap canvas")).boundingBox();
  const x = box.x + box.width / 2, y = box.y + box.height / 2;
  await page.mouse.move(x, y);
  await page.mouse.down();
  for (let i = 1; i <= steps; i++) { await page.mouse.move(x, y + (dy * i) / steps); await new Promise(r => setTimeout(r, 25)); }
  await page.mouse.up();
  await new Promise(r => setTimeout(r, 400)); // let inertia settle
  return page.evaluate(() => window.__cam());
}

try {
  for (const frame of ["y", "z"]) {
    section(`${frame.toUpperCase()}-up frame: the orbit passes both poles`);
    const page = await browser.newPage();
    const errors = [];
    page.on("pageerror", e => errors.push(String(e && e.message || e)));
    await page.goto(`http://127.0.0.1:${port}/${frame}.html`, { waitUntil: "load", timeout: left() });
    await page.waitForFunction(() => window.__ready === true, { timeout: left() });
    const cam0 = await page.evaluate(() => window.__cam());
    assert(cam0.lower === null && cam0.upper === null, `beta limits are unset (${cam0.lower}, ${cam0.upper})`);
    assert(cam0.upsideDown === true, "upside-down orbit allowed");

    // Underside: start just above the bottom pole and drag on through it.
    await page.evaluate(() => window.__setBeta(Math.PI - 0.15));
    const before = await page.evaluate(() => window.__cam());
    const first = await dragVertical(page, 40);
    const dir = Math.sign(first.beta - before.beta);   // which way this drag moves beta
    assert(dir !== 0, `a small drag moves beta (${before.beta.toFixed(3)} -> ${first.beta.toFixed(3)})`);
    // Now drag far in the direction that reaches the bottom pole.
    const towardPole = dir > 0 ? 260 : -260;
    const after = await dragVertical(page, towardPole);
    const clampedAtBottom = Math.abs(after.beta - (Math.PI - 0.01)) < 1e-3;
    assert(!clampedAtBottom, `beta is not pinned at PI - 0.01 after dragging through the underside (beta ${after.beta.toFixed(3)})`);
    // Passing the pole wraps beta to the negative side (Babylon's own wrap); the
    // camera is now looking from below the far side. Keep dragging the same way:
    // beta must keep moving the same way, not bounce.
    // The drag toward the pole raised beta past PI, so Babylon wrapped it to
    // the negative side; the same screen drag must keep raising it from there.
    const more = await dragVertical(page, towardPole / 2);
    assert(after.beta < 0, `beta wrapped past the pole rather than stopping (${after.beta.toFixed(3)})`);
    assert(more.beta > after.beta, `the orbit keeps going in the drag's direction after the pole (${after.beta.toFixed(3)} -> ${more.beta.toFixed(3)})`);

    // Top pole, the other way round.
    await page.evaluate(() => window.__setBeta(0.15));
    const top = await dragVertical(page, -towardPole);
    const clampedAtTop = Math.abs(top.beta - 0.01) < 1e-3;
    assert(!clampedAtTop, `the top pole is passable too (beta ${top.beta.toFixed(3)})`);
    assert(errors.length === 0, `no page errors during the drags (${errors.join("; ")})`);
    await page.close();
  }
} finally {
  await browser.close();
  server.close();
}
console.log(`\n=== orbit ===\n${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  - " + f); process.exit(1); }