← Commit history
0.11.0: a page downloads the viewer, not the whole Babylon engine (12.4 MB -> 4 MB)
12 files changed
+310−24
README.md+21−6SKILL.md+2−1VERSION+1−1package.json+4−3src/ThreeDViewer.svelte+5−1src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+7−1src/lib/adom-babylon/AdomStatics.ts+1−1src/lib/babylon-namespace.ts+87src/lib/babylon-side-effects.ts+16standalone.ts+15−9test/bundle.test.mjs+138vite.standalone.config.mts+13−1README.md+21−6@@ -71,8 +71,9 @@ 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.5.0", // this build, injected from package.json- BABYLON: <full @babylonjs/core namespace>, // re-exported for consumers+ 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 }; ``` @@ -211,10 +212,24 @@ 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. -The full `@babylonjs/core` namespace is exposed at-`Adom3DViewerBabylon9.BABYLON` so consumers do not need their own import side.-chiplinter uses `V.BABYLON.MeshBuilder.CreateDisc`, `V.BABYLON.PBRMaterial`,-`V.BABYLON.Tools.CreateScreenshotUsingRenderTarget`, and friends directly.+`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, StandardMaterial,+PBRMaterial, PBRMetallicRoughnessMaterial, Texture, DynamicTexture, CubeTexture,+RenderTargetTexture, SceneLoader, DracoCompression, Animation, AnimationGroup,+ArcRotateCamera, the four light types, ShadowGenerator, Tools, Observable,+PointerEventTypes, KeyboardEventTypes, Ray, Engine 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). ## Build from source
SKILL.md+2−1@@ -47,7 +47,8 @@ To show a different model in the same viewer, call `replaceModel(url)`: releases everything the old model brought. Full API (loadModel, frameModel, toggleAxes, layers toolbar, laser etch,-BABYLON namespace re-export) is documented in the README on this page. Source+BABYLON namespace: the common classes, plus `await loadBabylon()` for the+whole engine) is documented in the README on this page. Source lives on the Files tab; `adom-wiki repo clone adom/adom-3d-viewer` gets you a working checkout.
VERSION+1−1@@ -1 +1 @@-0.10.0+0.11.0
package.json+4−3@@ -1,6 +1,6 @@ { "name": "adom-3d-viewer-babylon9",- "version": "0.10.0",+ "version": "0.11.0", "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,11 +25,12 @@ "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 && node test/viewcube.test.mjs && node test/help.test.mjs && node test/lights.test.mjs && node test/replace.test.mjs",+ "test": "node test/wiki-sandbox.test.mjs && node test/orbit.test.mjs && node test/viewcube.test.mjs && node test/help.test.mjs && node test/lights.test.mjs && node test/replace.test.mjs && node test/bundle.test.mjs", "test:viewcube": "node test/viewcube.test.mjs", "test:help": "node test/help.test.mjs", "test:lights": "node test/lights.test.mjs",- "test:replace": "node test/replace.test.mjs"+ "test:replace": "node test/replace.test.mjs",+ "test:bundle": "node test/bundle.test.mjs" }, "dependencies": {}, "devDependencies": {
src/ThreeDViewer.svelte+5−1@@ -19,7 +19,9 @@ import type { ViewCubeUICallbacks } from './lib/adom-babylon/3DViewer/ViewCubeBuilder'; import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; import type { TransformNode } from '@babylonjs/core/Meshes/transformNode';- import { type Scene, type Engine, type Camera, type ShadowGenerator, PBRMetallicRoughnessMaterial } from '@babylonjs/core';+ import type { Scene, Engine, Camera, ShadowGenerator } from '@babylonjs/core';+ import { PBRMetallicRoughnessMaterial } from '@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial';+ import { loadBabylon } from './lib/babylon-namespace'; export let zUp: boolean = true; export let modelUrl: string | undefined = undefined;@@ -1678,6 +1680,8 @@ export async function showDebugLayer(): Promise<void> { const scene = AdomStatics.scene; if (!scene) return;+ // The inspector expects the whole engine on window.BABYLON.+ await loadBabylon(); await import('@babylonjs/inspector'); suppressInspectorTeachingPopovers(); await scene.debugLayer.show({ embedMode: true, overlay: true });
src/lib/adom-babylon/3DViewer/ViewCubeBuilder.ts+7−1@@ -9,7 +9,13 @@ import { Viewport } from "@babylonjs/core/Maths/math.viewport"; import { Mesh } from "@babylonjs/core/Meshes/mesh"; import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder"; import { Scene } from "@babylonjs/core/scene";-import { Animation, Effect, EngineStore, PickingInfo, Ray, SolidParticle, VertexBuffer } from '@babylonjs/core'+import { Animation } from '@babylonjs/core/Animations/animation';+import { Effect } from '@babylonjs/core/Materials/effect';+import { EngineStore } from '@babylonjs/core/Engines/engineStore';+import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';+import { Ray } from '@babylonjs/core/Culling/ray';+import { SolidParticle } from '@babylonjs/core/Particles/solidParticle';+import { VertexBuffer } from '@babylonjs/core/Buffers/buffer'; import { SolidParticleSystem } from "@babylonjs/core/Particles/solidParticleSystem"; import { AdomStatics } from "../AdomStatics"; import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight';
src/lib/adom-babylon/AdomStatics.ts+1−1@@ -5,7 +5,7 @@ import type { Nullable } from '@babylonjs/core/types'; import type { ShadowGenerator, ISceneLoaderAsyncResult } from '@babylonjs/core'; import type { SpotLight } from '@babylonjs/core/Lights/spotLight'; import type { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight';-import { RenderTargetTexture } from '@babylonjs/core';+import { RenderTargetTexture } from '@babylonjs/core/Materials/Textures/renderTargetTexture'; export class AdomStatics { public static engine: Nullable<Engine> = null;
src/lib/babylon-namespace.tsadded+87@@ -0,0 +1,87 @@+// The BABYLON namespace the viewer hands to host pages (window.BABYLON and+// Adom3DViewerBabylon9.BABYLON).+//+// It used to be `import * as BABYLON from '@babylonjs/core'`, which pulls the+// ENTIRE engine into the bundle every page downloads (the core index registers+// every module as a side effect, so nothing can be tree-shaken): 12.4 MB of+// script at startup for a viewer that uses a fraction of it. Now the+// namespace starts with the classes host pages commonly reach for, bundled+// with the viewer, and loadBabylon() brings in the rest on demand as its own+// chunk. A name outside the starting set reads as undefined (so feature+// checks like `if (BABYLON.X)` keep working) and warns once with the fix.++import { Vector2, Vector3, Vector4, Quaternion, Matrix } from '@babylonjs/core/Maths/math.vector';+import { Color3, Color4 } from '@babylonjs/core/Maths/math.color';+import { Axis, Space } from '@babylonjs/core/Maths/math.axis';+import { Scalar } from '@babylonjs/core/Maths/math.scalar';+import { Mesh } from '@babylonjs/core/Meshes/mesh';+import { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh';+import { TransformNode } from '@babylonjs/core/Meshes/transformNode';+import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';+import { VertexData } from '@babylonjs/core/Meshes/mesh.vertexData';+import { VertexBuffer } from '@babylonjs/core/Buffers/buffer';+import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';+import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';+import { PBRMetallicRoughnessMaterial } from '@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial';+import { Texture } from '@babylonjs/core/Materials/Textures/texture';+import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';+import { CubeTexture } from '@babylonjs/core/Materials/Textures/cubeTexture';+import { RenderTargetTexture } from '@babylonjs/core/Materials/Textures/renderTargetTexture';+import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';+import { DracoCompression } from '@babylonjs/core/Meshes/Compression/dracoCompression';+import { Animation } from '@babylonjs/core/Animations/animation';+import { AnimationGroup } from '@babylonjs/core/Animations/animationGroup';+import { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera';+import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight';+import { DirectionalLight } from '@babylonjs/core/Lights/directionalLight';+import { PointLight } from '@babylonjs/core/Lights/pointLight';+import { SpotLight } from '@babylonjs/core/Lights/spotLight';+import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';+import { Tools } from '@babylonjs/core/Misc/tools';+import { Observable } from '@babylonjs/core/Misc/observable';+import { PointerEventTypes } from '@babylonjs/core/Events/pointerEvents';+import { KeyboardEventTypes } from '@babylonjs/core/Events/keyboardEvents';+import { Ray } from '@babylonjs/core/Culling/ray';+import { Engine } from '@babylonjs/core/Engines/engine';+import { Scene } from '@babylonjs/core/scene';++const base: Record<string, unknown> = {+ Vector2, Vector3, Vector4, Quaternion, Matrix, Color3, Color4, Axis, Space, Scalar,+ Mesh, AbstractMesh, TransformNode, MeshBuilder, VertexData, VertexBuffer,+ StandardMaterial, PBRMaterial, PBRMetallicRoughnessMaterial,+ Texture, DynamicTexture, CubeTexture, RenderTargetTexture,+ SceneLoader, DracoCompression, Animation, AnimationGroup,+ ArcRotateCamera, HemisphericLight, DirectionalLight, PointLight, SpotLight, ShadowGenerator,+ Tools, Observable, PointerEventTypes, KeyboardEventTypes, Ray, Engine, Scene,+};++let full: Record<string, unknown> | null = null;+let loading: Promise<Record<string, unknown>> | null = null;+const warned = new Set<string>();++/** The whole @babylonjs/core namespace, loaded once on first call. */+export function loadBabylon(): Promise<Record<string, unknown>> {+ if (full) return Promise.resolve(full);+ if (!loading) {+ loading = import('@babylonjs/core').then((m) => {+ full = m as unknown as Record<string, unknown>;+ for (const k of Object.keys(full)) if (!(k in base)) base[k] = full[k];+ return full;+ });+ }+ return loading;+}++/** window.BABYLON / Adom3DViewerBabylon9.BABYLON. */+export const BABYLON_NAMESPACE: Record<string, unknown> = new Proxy(base, {+ get(target, prop) {+ if (typeof prop !== 'string' || prop in target) return (target as any)[prop];+ if (prop === 'then' || prop === 'toJSON' || prop.startsWith('__')) return undefined;+ if (!full && !warned.has(prop)) {+ warned.add(prop);+ console.warn(`[adom-3d-viewer] BABYLON.${prop} is not in the viewer's bundle. ` ++ 'Load the full engine first: await Adom3DViewerBabylon9.loadBabylon() (or viewer.loadBabylon()), then use BABYLON.' + prop + '.');+ }+ return undefined;+ },+});
src/lib/babylon-side-effects.tsadded+16@@ -0,0 +1,16 @@+// Babylon features that register themselves on import. The viewer loads+// @babylonjs/core module by module (not the index, which drags in the whole+// engine), so the scene components and loaders it relies on are imported+// here by name. Babylon names a missing one in its error: "X needs to be+// imported before as it contains a side-effect required by your code."+import '@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent';+import '@babylonjs/core/Misc/screenshotTools';+import '@babylonjs/core/Animations/animatable';+import '@babylonjs/core/Layers/layerSceneComponent';+import '@babylonjs/core/Layers/effectLayerSceneComponent';+import '@babylonjs/core/Rendering/utilityLayerRenderer';+import '@babylonjs/core/Rendering/boundingBoxRenderer';+import '@babylonjs/core/Materials/Textures/Loaders/envTextureLoader';+import '@babylonjs/core/Culling/ray';+import '@babylonjs/core/Collisions/pickingInfo';+import '@babylonjs/core/Engines/Extensions/engine.renderTarget';
standalone.ts+15−9@@ -24,10 +24,12 @@ import { getPref, setPref } from './src/lib/adom-babylon/util/prefs'; // Side-effect: registers the debugLayer getter on Scene. import '@babylonjs/core/Debug/debugLayer';+// Scene components and loaders the viewer relies on (see the file).+import './src/lib/babylon-side-effects'; -// Bring in the entire @babylonjs/core namespace so apps poking at the scene-// from the outside (chiplinter, scene-graph utility scripts) can use it.-import * as BABYLON_CORE from '@babylonjs/core';+// The BABYLON namespace for host pages: the common classes up front, the+// whole engine on demand (loadBabylon). See src/lib/babylon-namespace.ts.+import { BABYLON_NAMESPACE as BABYLON_CORE, loadBabylon } from './src/lib/babylon-namespace'; // Babylon.js classes (used directly inside this bundle for laser etch etc.) import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture';@@ -47,6 +49,8 @@ interface ViewerInstance { * (meshes, materials, textures, animations, layers); controls and content roots stay. */ replaceModel: (url: string) => Promise<void>; replaceModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>;+ /** The whole @babylonjs/core namespace (loaded once, on first call); also fills in BABYLON. */+ loadBabylon: () => Promise<Record<string, unknown>>; /** Explicitly additive load (what loadModel does). */ addModel: (url: string) => Promise<void>; addModelBytes: (bytes: ArrayBufferView, options?: { extension?: string }) => Promise<void>;@@ -182,6 +186,7 @@ function init(container: HTMLElement, options?: { replaceModel: (url: string) => component.replaceModel(url), replaceModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.replaceModelBytes(bytes, o), addModel: (url: string) => component.addModel(url),+ loadBabylon: () => loadBabylon(), addModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.addModelBytes(bytes, o), whenReady: () => component.whenReady().then(withVersion), getReadyReport: () => { const r = component.getReadyReport(); return r ? withVersion(r) : null; },@@ -438,17 +443,17 @@ function addLaserEtch(scene: Scene | null, options: LaserEtchOptions): any { return plane; } -// Required by the CDN-loaded Babylon Inspector — it expects to bind to-// `window.BABYLON`. We expose the full @babylonjs/core namespace.+// Host pages that script the scene find Babylon here: the common classes+// up front; await loadBabylon() for the rest. if (!(window as any).BABYLON) { (window as any).BABYLON = BABYLON_CORE; } // Expose on window. Distinct global from window.Adom3DViewer (Colby's bundle)-// so apps can have both loaded side-by-side during migration. The BABYLON-// sub-namespace re-exports the FULL @babylonjs/core surface so consumers-// can use any Babylon class (TransformNode, PBRMaterial, Quaternion, Matrix,-// CSG, Mesh, ...) without each app needing its own import side.+// so apps can have both loaded side-by-side during migration. BABYLON holds+// the common classes (Vector3, Color3, Mesh, MeshBuilder, TransformNode,+// materials, textures, lights, cameras, SceneLoader, DracoCompression, ...);+// loadBabylon() resolves with the whole @babylonjs/core and fills BABYLON in. (window as any).Adom3DViewerBabylon9 = { init, rotateYUpToZUp,@@ -459,4 +464,5 @@ if (!(window as any).BABYLON) { // engine builds can branch on this instead of feature-sniffing. version: __VIEWER_VERSION__, BABYLON: BABYLON_CORE,+ loadBabylon, };
test/bundle.test.mjsadded+138@@ -0,0 +1,138 @@+// 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, "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"].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 before = await run(() => typeof window.BABYLON.GlowLayer);+ eq(before, "undefined", "a class outside the set reads as undefined (feature checks keep working)");+ assert(warns.some(w => /BABYLON\.GlowLayer/.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.GlowLayer, ns: typeof window.BABYLON.GlowLayer, 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.GlowLayer }; } 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);
vite.standalone.config.mts+13−1@@ -1,6 +1,18 @@ import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import { readFileSync } from 'fs';+import { transform } from 'esbuild';++// Vite's library mode leaves whitespace in ES output (to keep pure+// annotations for consumers' tree-shaking); this bundle is the end product,+// so every chunk is fully minified after the build: about 30% smaller.+const minifyChunks = () => ({+ name: 'adom-minify-chunks',+ async renderChunk(code: string) {+ const out = await transform(code, { minify: true, format: 'esm', target: 'es2020', legalComments: 'none' });+ return { code: out.code, map: null };+ },+}); // Babylon 9's @babylonjs/inspector module has circular imports that resolve // to TDZ when collapsed into a single IIFE scope (regardless of minifier).@@ -8,7 +20,7 @@ import { readFileSync } from 'fs'; // so the inspector initializes cleanly. Consumers load via // `<script type="module" src="adom-3d-viewer-babylon9.esm.js"></script>`. export default defineConfig({- plugins: [svelte({ compilerOptions: { css: 'injected' } })],+ plugins: [svelte({ compilerOptions: { css: 'injected' } }), minifyChunks()], // @babylonjs/inspector v9 pulls in React, which references the Node-only // `process.env.NODE_ENV` global at runtime. Vite injects this automatically // in `serve` and standard `build` modes but NOT in `lib` mode, so without