← Commit history

0.7.2: view cube faces navigate on release; press-and-drag on the cube orbits (#4)

Colby Knox ·594c8436c1 · ·parent 4a186ec
5 files changed +197−4
README.md+10
@@ -132,6 +132,16 @@ near the underside and no beta limit. Presets (`front`, `back`, the view cube) still land upright. `npm run test:orbit` drives real pointer drags across both poles in the Y-up and Z-up frames. +### View cube: click on release, drag to orbit++A view-cube face navigates on mouse RELEASE (0.7.2, adom/adom-3d-viewer#4),+not on press: pressing on the cube and dragging orbits the model exactly like+dragging on the model, the way Fusion's cube behaves. A release within 4 px+of the press, still over the same face, is the click that animates the camera+to that face. `npm run test:viewcube` checks all three cases (drag on the cube+matches a drag on the model, a clean click snaps on release, a wander does+not snap).+ - The studio environment map loads from memory (Babylon's buffer option), and   images (environment mip levels, GLB-embedded textures) decode as   ImageBitmaps, so no `blob:` URL is ever fetched. `environmentBytes` injects
VERSION+1−1
@@ -1 +1 @@-0.7.1+0.7.2
package.json+3−2
@@ -1,6 +1,6 @@ {   "name": "adom-3d-viewer-babylon9",-  "version": "0.7.1",+  "version": "0.7.2",   "description": "The Babylon 9.5 engine behind every component page's 3D tab on wiki.adom.inc. Versioned ESM bundle with GLB loading, view cube, layers toolbar, ground shadows, and Z-up CAD framing.",   "type": "app",   "main": "./dist/index.js",@@ -25,7 +25,8 @@     "prepare": "npm run build",     "test:sandbox": "node test/wiki-sandbox.test.mjs",     "test:orbit": "node test/orbit.test.mjs",-    "test": "node test/wiki-sandbox.test.mjs && node test/orbit.test.mjs"+    "test": "node test/wiki-sandbox.test.mjs && node test/orbit.test.mjs && node test/viewcube.test.mjs",+    "test:viewcube": "node test/viewcube.test.mjs"   },   "dependencies": {},   "devDependencies": {
src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+20−1
@@ -466,7 +466,16 @@ export class ViewCubeBuilder {         viewModeMat.backFaceCulling = false         viewModeButtonMesh.material = viewModeMat +        // A face navigates on RELEASE, not on press (adom/adom-3d-viewer#4):+        // pressing on the cube and dragging must orbit the model, the way+        // Fusion's cube does, so the press only remembers which face was+        // under the pointer and a release within CLICK_SLOP_PX of it, still+        // over that face, is the click that animates the camera there.+        const CLICK_SLOP_PX = 4+        let pendingFace: { id: number; x: number; y: number } | null = null+         scene2.onPointerDown = function (evt, pickResult) {+            pendingFace = null             if (pickResult.pickedMesh === homeButtonMesh) {                 uiCallbacks?.onTooltip(null, 0, 0)                 if (uiCallbacks) {@@ -500,7 +509,17 @@ export class ViewCubeBuilder {                 return             }             const id = cubeRayCollision(pickResult)-            if (id) rotateToParticle(id);+            if (id) pendingFace = { id, x: evt.clientX, y: evt.clientY }+        }++        scene2.onPointerUp = function (evt, pickResult) {+            const pending = pendingFace+            pendingFace = null+            if (!pending || !pickResult) return+            const moved = Math.hypot(evt.clientX - pending.x, evt.clientY - pending.y)+            if (moved > CLICK_SLOP_PX) return+            const id = cubeRayCollision(pickResult)+            if (id === pending.id) rotateToParticle(id)         }          camera2.onViewMatrixChangedObservable.add(() => {
test/viewcube.test.mjsadded+163
@@ -0,0 +1,163 @@+// adom/adom-3d-viewer#4 (Colby): pressing a view-cube face used to start the+// camera animation on mouse DOWN, so a press-and-drag on the cube fought the+// orbit. Now the face navigates on RELEASE within a few pixels of the press;+// a drag that starts on the cube orbits the model exactly like a drag that+// starts on the model. Headless Chrome, real pointer events, bounded 120 s.+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, "dist-standalone");+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()); }+const sleep = (ms) => new Promise(r => setTimeout(r, ms));++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();++// 640x400: the cube viewport is 120x120 px in the top-right corner (the+// builder's 120 px minimum), so its centre is 60 px in from the right edge+// and 60 px down. Every pointer test uses that point.+const W = 640, H = 400, CUBE = { x: W - 60, y: 60 };+const HARNESS = `<!doctype html><html><head><meta charset="utf-8">+<style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;width:${W}px;height:${H}px}</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: true, showGround: false, modelUrl: '/chip.glb' });+  await v.whenReady();+  window.__viewer = v;+  window.__cam = () => { const c = v.getCamera(); return { alpha: c.alpha, beta: c.beta, radius: c.radius }; };+  window.__setPose = (a, b) => { const c = v.getCamera(); c.alpha = a; c.beta = b; c.inertialAlphaOffset = 0; 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 === "/cube.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS); }+  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 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; }+  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"],+});++// Press at (x, y), move by dx in steps, release; then let inertia settle.+async function drag(page, x, y, dx, steps = 10) {+  await page.mouse.move(x, y);+  await page.mouse.down();+  for (let i = 1; i <= steps; i++) { await page.mouse.move(x + (dx * i) / steps, y); await sleep(25); }+  await page.mouse.up();+  await sleep(900);+  return page.evaluate(() => window.__cam());+}+const START = { alpha: 0.7, beta: 1.2 };+const wrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));++try {+  const page = await browser.newPage();+  const errors = [];+  page.on("pageerror", e => errors.push(String(e && e.message || e)));+  await page.setViewport({ width: W, height: H });+  await page.goto(`http://127.0.0.1:${port}/cube.html`, { waitUntil: "load", timeout: left() });+  await page.waitForFunction(() => window.__ready === true, { timeout: left() });+  const box = await (await page.$("#wrap canvas")).boundingBox();+  const model = { x: box.x + box.width / 2, y: box.y + box.height / 2 };+  const cube = { x: box.x + CUBE.x, y: box.y + CUBE.y };++  section("a press-and-drag that starts on the cube orbits the model, it does not snap to a face");+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(200);+  const onModel = await drag(page, model.x, model.y, 80);+  const dModel = wrap(onModel.alpha - START.alpha);+  assert(Math.abs(dModel) > 0.05, `a drag on the model orbits (alpha ${START.alpha} -> ${onModel.alpha.toFixed(3)})`);+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(200);+  const onCube = await drag(page, cube.x, cube.y, 80);+  const dCube = wrap(onCube.alpha - START.alpha);+  assert(Math.abs(dCube - dModel) < 0.08, `the same drag on the cube orbits by the same amount (model ${dModel.toFixed(3)}, cube ${dCube.toFixed(3)})`);+  assert(Math.abs(onCube.beta - onModel.beta) < 0.08, `and lands at the same beta (${onModel.beta.toFixed(3)} vs ${onCube.beta.toFixed(3)})`);++  section("a clean click on a face still navigates there, on release");+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(200);+  await page.mouse.move(cube.x, cube.y);+  await page.mouse.down();+  await sleep(120);+  const held = await page.evaluate(() => window.__cam());+  assert(Math.abs(wrap(held.alpha - START.alpha)) < 0.02 && Math.abs(held.beta - START.beta) < 0.02, `nothing moves while the button is held (${held.alpha.toFixed(3)}, ${held.beta.toFixed(3)})`);+  await page.mouse.up();+  await sleep(900);+  const clicked = await page.evaluate(() => window.__cam());+  const movedBy = Math.abs(wrap(clicked.alpha - START.alpha)) + Math.abs(clicked.beta - START.beta);+  assert(movedBy > 0.15, `the release animates the camera to the face (moved ${movedBy.toFixed(3)} rad)`);+  // Face poses are axis-aligned in beta (0, PI/2, PI) or on a 45-degree edge/corner.+  const b = clicked.beta;+  const onGrid = [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI].some(g => Math.abs(b - g) < 0.05);+  assert(onGrid, `the landing beta is a cube pose (${b.toFixed(3)})`);++  section("a press that wanders off the face before release is not a click");+  await page.evaluate((s) => window.__setPose(s.alpha, s.beta), START);+  await sleep(200);+  const wandered = await drag(page, cube.x, cube.y, 12, 3);+  const dW = wrap(wandered.alpha - START.alpha);+  assert(Math.abs(dW) < Math.abs(dModel) && Math.abs(dW) > 0.0, `a 12 px wander orbits a little (${dW.toFixed(3)}) instead of snapping`);+  const wbOnGrid = [0, Math.PI / 4, Math.PI / 2, 3 * Math.PI / 4, Math.PI].some(g => Math.abs(wandered.beta - g) < 0.01);+  assert(!wbOnGrid || Math.abs(wandered.beta - START.beta) < 0.1, `no snap animation ran (beta ${wandered.beta.toFixed(3)})`);++  assert(errors.length === 0, `no page errors (${errors.join("; ").slice(0, 200)})`);+  await page.close();+} finally {+  await browser.close();+  server.close();+}+console.log(`\nview cube: ${passed} passed, ${failed} failed`);+if (failed) { for (const f of failures) console.log("  - " + f); process.exit(1); }