Adom 3D Viewer

Install?

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.

adom-wiki pkg install adom/adom-3d-viewer

Latest: v0.13.0, published

Download for your machine · v0.13.0?

Adom 3D Viewer

All downloads (1 file)
FilePlatformArchKindSizesha256
adom-3d-viewer-babylon9-0.13.0.tar.gz any tar.gz 13 MB f3cb4edfcf46736ba347830630115f75ad802977be7f3e622364fa911ddcdbde
Contents

README

markdown

Adom 3D Viewer

The Babylon 9.5 viewer engine behind every component page's 3D tab on wiki.adom.inc. A fork of adom-inc/3d-viewer (Babylon 7.54) upgraded to Babylon 9.5 with the redesigned Inspector v9, built as a versioned ESM bundle that downstream tools vendor (the wiki's native component viewer, chiplinter, and the next wave of Adom 3D apps).

The source lives on GitHub (adom-inc/adom-3d-viewer-babylon9). This page holds the releases: each version's source on the Files tab, and its built bundle attached as a release asset you can pin.

What is in 0.4.x

  • Layers toolbar: slide-out per-layer visibility panel driven by the node naming convention (fr4_board, pad_top, silk, barrel, pin1_marker, ...).
  • Z-fighting fixes for PCB models: 10x depth precision, polygon-offset tie-breaking for nested shells, near plane at radius/50, XY-area container ordering.
  • Skybox mesh replaced by a screen-space background layer (tight far plane, faded ground rim): frameModel no longer fits a 5000-unit skybox.
  • Sandbox storage guard: localStorage/sessionStorage access is wrapped, so the viewer initializes fully (lights, IBL, shadows) inside sandboxed iframes.
  • Transparent radial-fade ground, hover tooltips, orbit-center UX, world-origin and mesh-local axis helpers, laser-etch text overlays.

Get the bundle (pin a version)

Every release attaches the built bundle as a tarball asset:

adom-wiki release download adom/adom-3d-viewer <version> adom-3d-viewer-babylon9-<version>.tar.gz
tar -xzf adom-3d-viewer-babylon9-<version>.tar.gz -C ./vendor/3d-viewer/

The extracted VERSION file records exactly which build you have. The bundle code-splits into ~60 chunks; serve them all from the same directory as the entry (adom-3d-viewer-babylon9.esm.js) and browsers fetch chunks on demand.

Embed it

<!-- Browser shim for Node-style globals that @babylonjs/inspector's React
     (Fluent UI) deps assume. Add BEFORE loading the bundle. -->
<script>
  window.process = window.process || { env: { NODE_ENV: "production" } };
  window.global = window.global || window;
</script>

<script type="module">
  await import("./vendor/3d-viewer/adom-3d-viewer-babylon9.esm.js");
  const v = window.Adom3DViewerBabylon9;
  const viewer = v.init(host, { zUp: true, showViewCube: true });
  await viewer.loadModel("chip.glb");
  viewer.frameModel();
</script>

Why ESM (not IIFE)

Babylon 9's @babylonjs/inspector has circular imports that resolve to TDZ when collapsed into a single IIFE scope, regardless of minifier. Vite's ESM output preserves module boundaries so the inspector initializes cleanly. The global is window.Adom3DViewerBabylon9 (distinct from the legacy window.Adom3DViewer), so both bundles can coexist during a migration.

API

window.Adom3DViewerBabylon9 = {
  init(host, options),         // mounts the viewer, returns ViewerInstance
  rotateYUpToZUp(scene),       // kicad-cli GLBs (Y-up) -> adom viewer (Z-up)
  addLaserEtch(scene, opts),   // bake a laser-etched chip-marking text overlay
  version: "0.11.0",           // this build, injected from package.json
  BABYLON: <common @babylonjs/core classes>,  // also window.BABYLON
  loadBabylon(),               // Promise of the whole @babylonjs/core; fills BABYLON in
  babylonVersion: "9.5.0",     // the Babylon.js release BABYLON and loadBabylon() come from
};

ViewerInstance exposes:

  • replaceModel(url) / replaceModelBytes(bytes, { extension? }): show this model INSTEAD of what is loaded. The new model loads first; then every earlier model and all it brought (meshes, materials, textures, animation groups, skeletons, content lights, layer and state-group inventory) is disposed. Camera, controls, ground, environment and anything added with addContentRoot stay. A failed load keeps the current model; of two overlapping calls the later wins. Use this to swap models in one viewer.
  • loadModel(url) / loadModelBytes(bytes, { extension? }): ADD a model to what is shown (a second call shows both, for scenes composed from several files). addModel / addModelBytes are the same, named for what they do.
  • clearScene() (removes every loaded model with its materials, textures and animations) / frameModel(fillFraction?)
  • whenReady() / getReadyReport(): the ready report (see "Sandboxed frames" below): resolves once the first scene is up and reflects the current state on every later call; never rejects
  • getScene() / getEngine() / getCamera() / getShadowGenerator()
  • addContentRoot(node, opts?) / removeContentRoot(node)
  • toggleDebugLayer() / showDebugLayer() / hideDebugLayer()
  • setGroundVisible(visible) / goHome() / setHomeView({ alpha, beta, radiusScale?, target? } | null): Home (the view cube and goHome()) goes to the host's view when one is set, else the top-front-right corner (0.9.2, adom/adom-3d-viewer#9). target: [x, y, z] is the point that view orbits, in the model's own frame (a GLB's coordinates, Z up, as the viewer shows them); without it the view aims at the model's bounding-box center (0.12.3, adom/wiki#237)
  • setBottomLight(on) / getBottomLightState(): underside fill light, default off
  • setProjectionMode(ortho) / getProjectionMode()
  • getCameraState(): { alpha, beta, radius, target: [x, y, z] }, angles in radians
  • moveCamera(to, { ms? }): to is a view ("home", "fit", or a view cube face: "front", "back", "left", "right", "top", "bottom") or any part of a camera state. With ms it eases there the short way round. A face view lands where clicking that cube face does. Resolves with the final state; a new move cancels the one in flight, and a move ends where it was asked to even when the browser throttles animation frames
  • orbit({ degrees?, ms? }): turn around the target, 360 degrees over 4000 ms by default
  • openGate() / isGated(): start a viewer created with gate, as its Load button does; resolves with the ready report
  • on(event, listener), findNodes(query), highlight(target, options?), clearHighlight(), isolate(target, options?), clearIsolate(), focus(target, { ms? }): see "Events, highlight and isolate" below
  • toggleAxes("world" | "mesh-local", force?) / getAxesState()
  • getLayers() / setLayerVisible(name, visible): layers, either declared by the content via extras.adomLayer or matched against the built-in board vocabulary (docs/CONTENT-CONVENTIONS.md). Each entry carries group for sectioning and declared to say which source it came from. Empty for GLBs with fewer than two layers
  • captureScreenshot({ width?, height? }): resolves to a PNG data URL. Renders through an offscreen target, so the result does not depend on the on-screen canvas size
  • setShadowRefreshRate(rate | null): pin the shadow map refresh rate; null restores automatic behavior. Needed for content animated from outside the viewer, which scene.animationGroups cannot see
  • destroy(): releases this viewer's engine, scene and listeners

Each init() returns an independent viewer with its own canvas, WebGL context, engine, scene, camera, lights and view cube, so a page can hold several. Each one costs a WebGL context and, unless shadows is false, a shadow map: 8192 x 8192 (about 256 MB of GPU memory) while it is the only viewer with shadows, 4096 with up to four, 2048 beyond that. Live viewers' maps resize as viewers come and go. Browsers cap the live contexts per page, so destroy viewers a page no longer shows.

init() options: zUp, modelUrl, showViewCube, showGround, environmentUrl, environmentBytes, environment ("studio" | "none"), initialViewMode, onReady(report), onMeshHover(mesh, tip), onGroundCreated(ground), onContextLost(), onContextRestored(), showHelp, lightBudget, intros, gate, and these scene options:

Option Default Effect
animate true false holds every animation group at its first frame after each load
repeat 0 an animation the model starts with plays this many times, then rests on its last frame; 0 loops
tooltips "all" "authored" shows only extras.tooltip labels; "off" shows none. onMeshHover still runs
axes true world axes at startup
bottomLight false bottom fill light at startup
shadows true false turns shadows off and skips the shadow map; getShadowGenerator() then returns null
homeView none { alpha, beta, radiusScale?, target? }, the view Home goes to (as setHomeView)
homeOnLoad false the first model load opens at Home instead of the starting top-down view
loadTimeoutMs 0 a URL load that has not finished in this time rejects and the ready report says MODEL_LOAD_TIMEOUT; a model that arrives later is discarded. 0 waits forever
background "studio" "transparent" clears to alpha 0 so the page shows through (screenshots keep the alpha); "#rrggbb" is a flat color. Anything else throws

replayAnimations() plays the model's animations again from their first frame, repeat times (looping when repeat is 0 and animate is on), and returns false when there are none. Layer intros replay with replayIntros().

Events, highlight and isolate

on(event, listener) adds a listener and returns a function that removes it. An unknown event name throws. A listener that throws is logged and does not stop the others.

Event Fires Carries
"pick" a click that did not drag { mesh, path, point, x, y, button, shiftKey, ctrlKey, altKey, metaKey }
"hover" the content mesh under the pointer changes { mesh, path, point, x, y }
"load" a model was added or replaced, by any load call or modelUrl { url, root, meshes }; url is null for bytes
"error" a model load failed or timed out { url, message, code }, code "MODEL_LOAD_FAILED" or "MODEL_LOAD_TIMEOUT"
"camera" the view changed; at most once per rendered frame the camera state, as getCameraState()
"layer" a layer was shown or hidden, from the panel or setLayerVisible { name, visible }
"contextlost", "contextrestored" as onContextLost and onContextRestored {}

Pick and hover in detail:

  • "pick" fires on a click that did not drag (an orbit or pan is not a pick). mesh is the content mesh under the pointer, or null on empty space. A double-click is two picks and then the viewer's own focus move; Shift+Alt+click places the orbit pivot and is not a pick.
  • "hover" fires when the content mesh under the pointer changes, and once with mesh: null when the pointer leaves content.

Both carry { mesh, path, point, x, y }: path is the node names from the model root down to the mesh, point the world position hit, x and y the pointer in CSS pixels from the canvas's top left. A pick adds button and the modifier keys. Only loaded models and content roots are reported, never the ground, axes or view cube, and the view cube's corner fires no pick.

findNodes(query) returns the content nodes, meshes and transform nodes, whose name equals a string, matches a RegExp, or passes a function.

highlight(target, { color?, alpha?, mode? }) lights a node, an array of nodes, or whatever a findNodes query matches; a node lights every mesh under it. color is "#rrggbb" or [r, g, b] from 0 to 1 (default blue), alpha the overlay strength (default 0.75), and mode is "overlay" (the default: a tint that stays readable on gold and metal) or "outline" (a glow around the mesh). It returns { meshes, clear() }. Highlights stack: where two share a mesh the later one shows, and clearing it brings back the one beneath. clearHighlight() removes them all.

let selected = null;
viewer.on("pick", (e) => {
  selected?.clear();
  selected = e.mesh ? viewer.highlight(e.mesh) : null;
});
viewer.highlight(/^(lead|pin|pad)_?0*7$/i, { color: "#ffaa00" });

isolate(target, { mode?, alpha? }) shows only the target. Every other content mesh is hidden (mode: "hide", the default) or drawn at alpha ("ghost", default 0.15), and stops taking picks. One isolation holds at a time: a new isolate() replaces the last, and clearIsolate() or the returned clear() ends it. When the target matches no mesh nothing changes and meshes is empty. Layers and state groups keep working underneath, and models loaded afterwards are not affected.

focus(target, { ms? }) turns the camera to the target so it fills about 80% of the view, keeping the current angles (the move double-click makes), and eases over ms like moveCamera. It resolves with the camera state, or null when nothing matches.

const part = viewer.isolate("U3", { mode: "ghost" });
await viewer.focus("U3", { ms: 600 });
// later
part.clear();

Large models and lost WebGL contexts

gate: { bytes?, vertices?, downloadUrl? } makes the viewer click to load. downloadUrl must be an http(s) or relative URL; init() throws on any other, such as javascript:. It shows a card with the model's size (from bytes and vertices), a Load button and, with downloadUrl, a Download link, and creates no engine, scene or WebGL context until the reader presses Load or the host calls openGate(). Model loads asked for before then wait for it, and whenReady() resolves after it. Where to draw the line is the host's call: pass gate only for models it judges too large to open unasked.

The browser can take a viewer's WebGL context away, when a page holds more live contexts than it allows or the GPU resets. Nothing paints until the context is back; the engine then rebuilds its GPU state by itself. onContextLost and onContextRestored report both moments. A host that would rather start over keeps the view and rebuilds:

const view = viewer.getCameraState();
viewer.destroy();
viewer = Adom3DViewerBabylon9.init(host, options);
await viewer.loadModel(url);
await viewer.moveCamera(view);

The hover hook is called on the pick the viewer already performs: return a string to override the tooltip, null to suppress it, or nothing to leave the viewer's own text alone. It is called with (null, null) when the pointer leaves content, so a consumer-driven highlight can clear itself.

onGroundCreated is called with the ground mesh after every rebuild. The ground's geometry belongs to the viewer, because it is sized from content bounds and rebuilt whenever the model is reframed; its appearance does not, so this is where a consumer applies its own ground material. Setting the material once from outside will not survive the next reframe.

Sandboxed frames (wiki widgets and readmes)

The wiki's widget and readme frames are opaque origins under a strict CSP (connect-src 'self' data:, img-src data: https:, no blob:), and every localStorage access there throws. Since 0.7.0 the viewer is built for that (adom/adom-3d-viewer#5):

Orbit

The camera orbits freely through both poles (0.7.1). Dragging through a flat top or bottom view keeps rotating in the same direction; there is no stop 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.

The ? button: controls card and the Shift+Alt tip

Every viewer draws a small ? in its bottom-right corner (0.7.3). The card it opens leads with the move that makes large boards and scaffolds navigable: Shift+Alt+click a point on the model to set the center of rotation (a glowing dot marks it; orbit and zoom then work around that spot). The rest of the controls follow: drag to orbit, right-drag or Ctrl+drag to pan, scroll to zoom toward the cursor, the cube faces with Home and Fit, hold Space to spin. The ? key and Escape toggle the card; with several viewers on a page, only the one the pointer or focus was in last answers. The first time a model is ready in a browser, a tip bubble says the Shift+Alt line once and is then remembered (ephemeral storage in sandboxed frames). init(host, { showHelp: false }) hides all of it for hosts that draw their own help (0.7.4: a host container that is already positioned, such as position: absolute; inset: 0, keeps its positioning; 0.7.3 forced it to relative, and the canvas collapsed to 150 px after the host hid and re-showed the viewer); viewer.showHelp() and viewer.hideHelp() drive the card. npm run test:help covers it.

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 your own .env bytes the same way; environment: "none" skips the map.
  • Preferences fall back to document-local memory when storage is denied; the report says storage: "ephemeral".
  • loadModelBytes(bytes) takes a model the host already fetched or verified, so the frame's CSP never sees a model URL.
  • The loading overlay always comes down, model failure included, and whenReady() resolves with a report:
const viewer = Adom3DViewerBabylon9.init(host, { modelUrl: "/adom/part/render/part.glb" });
const report = await viewer.whenReady();
// { ok, destroyed, engine: { webglVersion, contextLost }, environment: { source, ready, error },
//   camera: { ready, mode }, storage: "persistent" | "ephemeral",
//   loadingOverlay: "hidden" | "visible", model: { requested, loaded, meshes, vertices, error },
//   cspViolations: [{ directive, blocked }], hints: [{ code, level, message, action }], version }

ok is true only when the scene rendered, the overlay is gone, the environment is ready (or deliberately absent), no CSP violation was recorded and any requested model loaded with geometry. Otherwise the hints name the fix: CSP_BLOCKED, MODEL_LOAD_FAILED, MODEL_EMPTY, ENVIRONMENT_FAILED, ENVIRONMENT_PENDING, STORAGE_EPHEMERAL (info), LOADING_OVERLAY_STUCK, WEBGL_CONTEXT_LOST, VIEWER_DESTROYED (info). A viewer destroyed before its scene was ready, gated and never opened or still starting, resolves whenReady() with destroyed: true and ok: false; onReady is not called for it.

One thing the frame's host must do: an opaque origin fetches module scripts in CORS mode, so the bundle must be served with Access-Control-Allow-Origin (the wiki's /static/vendor/ route does).

npm run test:sandbox proves all of it in headless Chrome: an https server carrying the wiki's exact widget CSP, an sandbox="allow-scripts" iframe, a ready report that says ok, painted chip pixels, then three destroy/recreate rounds alternating URL and bytes transport. Uses the puppeteer-core dev dependency and a Chrome from PUPPETEER_EXECUTABLE_PATH or ~/.cache/puppeteer.

Scale

Millimeter-scale models are supported. The near plane is radius/50 recomputed per frame, and light height, intensity, panning speed and radius limits are all derived from model size, so a 5 mm part and a 500 mm assembly both frame and light correctly without a unit setting.

Babylon classes and loadBabylon()

getScene(), getEngine(), getCamera() and getShadowGenerator() return the viewer's live Babylon objects, and addContentRoot(node) brings host-built meshes into framing, shadows, hover and picks. To build those meshes a host needs Babylon's classes, and it must use the viewer's copy, not one of its own: two copies of Babylon on a page do not share instanceof, scene components or the engine store.

Adom3DViewerBabylon9.BABYLON (also window.BABYLON) holds the Babylon classes host pages commonly use, bundled with the viewer: Vector2/3/4, Quaternion, Matrix, Color3/4, Axis, Space, Scalar, Mesh, AbstractMesh, TransformNode, MeshBuilder, VertexData, VertexBuffer, Material, StandardMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, ImageProcessingConfiguration, Texture, DynamicTexture, CubeTexture, RenderTargetTexture, SceneLoader, LoadAssetContainerAsync, DracoCompression, DracoDecoder, Animation, AnimationGroup, ArcRotateCamera, the four light types, ShadowGenerator, Layer, HighlightLayer, GlowLayer, Tools, Observable, PointerEventTypes, KeyboardEventTypes, Ray, PickingInfo, Engine, EngineStore and Scene. chiplinter's V.BABYLON.MeshBuilder.CreateDisc, V.BABYLON.PBRMaterial and V.BABYLON.Tools.CreateScreenshotUsingRenderTarget work as before.

For anything else, await Adom3DViewerBabylon9.loadBabylon() (or viewer.loadBabylon()) loads the whole @babylonjs/core once, as its own chunk, resolves with it and fills BABYLON in. Before that, a class outside the set reads as undefined (so if (BABYLON.X) checks keep working) and logs a one-time warning naming the fix. Until 0.11.0 the bundle imported the whole engine for this namespace: a page downloaded 12.4 MB of script to show one model; it is about 4 MB now (1.4 MB compressed).

What a host can rely on:

  • loadBabylon() resolves with the same module the viewer runs on, so a class from it is the class of the viewer's own objects (viewer.getScene() instanceof (await loadBabylon()).Scene). Calling it again returns the same object.
  • babylonVersion names that Babylon.js release. A host written against Babylon's API checks it, not the viewer's own version.
  • The classes listed above stay in BABYLON without loadBabylon(). Taking one out breaks pages that use it, as 0.11.0 did, so it is a breaking change and the release notes say so.
  • Pass the viewer's scene (viewer.getScene()) when creating Babylon objects. Babylon puts an object created without one in the last scene created, which on a page with several viewers is whichever viewer started last. Each viewer's internal view cube scene never becomes that default.

Board layers and pin finish

Shipped on the release line in 0.12.8 to 0.12.10; here since 0.13.0.

  • Board layers. A GLB whose Adom.Board.Top and Adom.Board.Bottom materials carry the optional ADOM_board_layers glTF extension (dense or sparse layout) is drawn with the Round 3 shader: signed-distance copper, mask-opening and silk edges stay sharp close up, with a smooth handover to the base colour and metallic-roughness textures at normal viewing distances. Models without the extension, WebGPU and WebGL 1 engines, and failed data or shader loads keep those textures.
  • Pin finish. Materials named AdomMachineGold get the approved machine-pin grain and a reflection map of their own, embedded in the bundle so no URL reaches the frame's CSP. environment: 'none' keeps the grain and drops the reflections.
  • Lighting. Every scene uses environment intensity 0.5 and KHR PBR Neutral tone mapping (Board Look 0.6).

Both hook only this viewer's own glTF loads, so several viewers on one page keep their materials apart. A model load resolves, and load fires, once the board-layer and pin textures are ready, including a load called right after init() or behind a closed gate. loadTimeoutMs covers the import, not that wait: each of those textures gives up on its own after 10 s and leaves the model's own textures, so a slow one never fails or discards a model that loaded. destroy() releases them with the viewer.

Build from source

git clone https://github.com/adom-inc/adom-3d-viewer-babylon9
cd adom-3d-viewer-babylon9
npm ci
npm run build:standalone   # -> dist-standalone/
npm test                   # every test file, in headless Chrome

Every build dependency is a pinned dev dependency (Babylon 9.5.0 throughout), so a fresh clone builds with nothing else installed. The tests need a Chrome: set PUPPETEER_EXECUTABLE_PATH, or install one into ~/.cache/puppeteer with npx @puppeteer/browsers install chrome@stable. npm test runs every test/*.test.mjs and reports each file; npm run test:<name> runs one.

npm run build (plain vite build) produces the npm-consumable dist/ library instead; dist-standalone/ is the self-contained browser bundle the wiki and release assets ship.

VIEWER_DIST=<dir> moves the standalone build's output, and the directory the tests read, away from dist-standalone/. On a Windows/WSL live mirror, set VIEWER_DIST=dist/standalone for both build:standalone and the tests so the generated output stays in the mirror's excluded dist/ folder.

Consumers

  • wiki.adom.inc component pages: git-wiki vendors dist-standalone/ into static/vendor/adom-3d-viewer-babylon9 and pins it via VIEWER_BUNDLE_VER.
  • adom-chiplinter: vendors the release tarball into vendor/3d-viewer/.
  • Downstream viewer work is tracked on adom/wiki issues (#48, #53, #60).

Development

Source of record is GitHub adom-inc/adom-3d-viewer-babylon9: commits and pull requests go there, and CI builds and tests every pull request. A vX.Y.Z tag publishes that version here (package, source push, bundle release asset) through scripts/release.sh; see publish-skills/release/SKILL.md.