← Commit history
v0.12.8
21 files changed
+578−21
package-lock.json+2−2package.json+55−5scripts/release.shsrc/ThreeDViewer.svelte+6src/lib/board-layers.d.ts+2src/lib/board-layers.js+374test/board-layers.test.mjs+125test/bundle.test.mjs+1−1test/help.test.mjs+1−1test/home-target.test.mjs+1−1test/intro.test.mjs+1−1test/layers.test.mjs+1−1test/lights.test.mjs+1−1test/orbit.test.mjs+1−1test/replace.test.mjs+1−1test/shadow-size.test.mjs+1−1test/state-scope.test.mjs+1−1test/viewcube.test.mjs+1−1test/visibility.test.mjs+1−1test/wiki-sandbox.test.mjs+1−1vite.standalone.config.mts+1−1package-lock.json+2−2@@ -1,12 +1,12 @@ { "name": "adom-3d-viewer-babylon9",- "version": "0.12.7",+ "version": "0.12.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "adom-3d-viewer-babylon9",- "version": "0.12.4",+ "version": "0.12.8", "license": "MIT", "devDependencies": { "@babylonjs/addons": "9.5.0",
package.json+55−5@@ -3,7 +3,61 @@ "version": "0.12.8", "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",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts"+ }+ },+ "files": [+ "dist",+ "dist-standalone",+ "src",+ "standalone.ts"+ ],+ "scripts": {+ "build": "vite build",+ "build:standalone": "vite build --config vite.standalone.config.mts",+ "dev": "vite build --watch",+ "prepare": "npm run build",+ "test:sandbox": "node test/wiki-sandbox.test.mjs",+ "test:orbit": "node test/orbit.test.mjs",+ "test": "node test/run-all.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:layers": "node test/layers.test.mjs",+ "test:bundle": "node test/bundle.test.mjs",+ "test:home": "node test/home-target.test.mjs",+ "test:intro": "node test/intro.test.mjs",+ "test:visibility": "node test/visibility.test.mjs"+ }, "dependencies": {},+ "devDependencies": {+ "@babylonjs/addons": "9.5.0",+ "@babylonjs/core": "9.5.0",+ "@babylonjs/gui": "9.5.0",+ "@babylonjs/gui-editor": "9.5.0",+ "@babylonjs/inspector": "9.5.0",+ "@babylonjs/loaders": "9.5.0",+ "@babylonjs/materials": "9.5.0",+ "@babylonjs/serializers": "9.5.0",+ "@sveltejs/vite-plugin-svelte": "^3.1.2",+ "babylonjs-gltf2interface": "9.5.0",+ "puppeteer-core": "25.15.0",+ "svelte": "4.2.20",+ "svelte-check": "^3.8.6",+ "terser": "^5.46.2",+ "typescript": "^5.5.4",+ "vite": "^5.4.1"+ },+ "peerDependencies": {+ "svelte": "^4.0.0 || ^5.0.0"+ }, "slug": "adom-3d-viewer", "license": "MIT", "tags": [@@ -37,9 +91,5 @@ "prompt": "Download the 0.4.3 viewer bundle so my tool vendors a fixed build" } ],- "title": "Adom 3D Viewer",- "scripts": {- "install": "./install.sh",- "uninstall": "./uninstall.sh"- }+ "title": "Adom 3D Viewer" }
scripts/release.shsrc/ThreeDViewer.svelte+6@@ -1,4 +1,5 @@ <script lang="ts">+ import { installBoardLayers } from "./lib/board-layers"; import { onMount, onDestroy } from 'svelte'; import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader'; import '@babylonjs/loaders/glTF';@@ -878,11 +879,13 @@ // Visible scenes retain continuous rendering for camera inertia and GLB states. let renderVisibilityCleanup: (() => void) | undefined; let destroyed = false;+ let boardLayers: ReturnType<typeof installBoardLayers> | undefined; async function initViewer() { if (!canvas || !container) return; await AdomStatics.init(canvas, zUp); const engine = AdomStatics.engine!; const scene = AdomStatics.scene!;+ boardLayers = installBoardLayers(scene); // The engine sizes the backing store from the canvas's CSS box at the // display's pixel density; setting canvas.width by hand would pin it@@ -1072,6 +1075,7 @@ lastModelError = e instanceof Error ? e.message : String(e); throw e; }+ await boardLayers?.waitReady(); lastModelError = null; return result; }@@ -1088,6 +1092,7 @@ lastModelError = e instanceof Error ? e.message : String(e); throw e; }+ await boardLayers?.waitReady(); lastModelError = null; return result; }@@ -1838,6 +1843,7 @@ resizeObserver?.disconnect(); deviceRatioQuery?.removeEventListener('change', onDeviceRatioChange); AdomStatics.engine?.stopRenderLoop();+ boardLayers?.dispose(); AdomStatics.dispose(); }); </script>
src/lib/board-layers.d.tsadded+2@@ -0,0 +1,2 @@+import type { Scene } from '@babylonjs/core/scene';+export declare function installBoardLayers(scene: Scene): { waitReady(): Promise<void>; dispose(): void };
src/lib/board-layers.jsadded+374@@ -0,0 +1,374 @@+// Board layers from signed distance fields (ADOM_board_layers), viewer code for the wiki's Babylon viewer.+// Installed once per scene, before loading models. The shader is the selected Round 3 implementation.+//+// Same data and same picture as sdf/viewer-sdf.js (sdf-k2), drawn with less GPU time (sdf-lite round 3).+// A normalized board GLB can carry, on its Adom.Board.Top and Adom.Board.Bottom materials, the optional+// glTF extension ADOM_board_layers: the signed distance (positive inside) to the copper, mask-opening+// and silk edges on the same UV mapping as the base colour map, either as one RGB texture ("dense") or+// as an atlas of tiles plus a tile map ("sparse": tiles far from every edge are a flag, not texels),+// and the colours, roughness and metallic values the board look composes them with. Close up, a shader+// step paints the board from the distance fields: edges stay sharp at any zoom, anti-aliased from the+// pixel's own footprint, and composed like normalize's texture (surface.py compose(), mixed in sRGB).+// Farther away, where a base colour texel covers about a pixel or more, it hands over smoothly to the+// base colour and metallic-roughness maps, so whole-board views are today's mip-mapped texture.+//+// Where the time goes: almost every board pixel is far from every edge, relative to its footprint. There+// each layer's coverage is exactly 0 or 1, so such a pixel reads one texel of the field, takes its region's+// colours (already linear) from a table of eight, and skips the gradient taps, the coverage arithmetic,+// the sRGB curve, and the PBR shader's own base colour and metallic-roughness samples, which the field+// fully replaces there. Only pixels near an edge run the full path.+//+// Models without the extension, other materials, WebGPU and WebGL 1 are left alone; if anything fails,+// a shader that does not compile included, the material keeps today's texture. waitReady() settles the+// extension loads before the viewer reports model readiness.+import { MaterialPluginBase } from '@babylonjs/core/Materials/materialPluginBase';+import { Texture } from '@babylonjs/core/Materials/Textures/texture';+import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';++export function installBoardLayers(scene) {+ const EXT = 'ADOM_board_layers';+ const B = { MaterialPluginBase, Texture, SceneLoader };+ let disposed = false;+ const pending = new Set();+ const textures = new Set();+ const deadMaterials = new WeakSet();+ const engine = scene.getEngine();+ const usable = !engine.isWebGPU && (engine.webGLVersion || 1) >= 2 && !!B.MaterialPluginBase && !!B.SceneLoader && !!B.SceneLoader.OnPluginActivatedObservable;+ const state = { plugins: [], failed: 0 };+ // Hand-over from the distance fields to the texture, in base colour texels per pixel along the longer+ // axis of the pixel's footprint: all distance field below LO, all texture above HI.+ const LO = 0.55, HI = 0.9;+ let uid = 0;++ const GLSL_DEFS = `+#ifdef ADOMBOARDLAYERS+uniform sampler2D adomLayersSampler;+#ifdef ADOMSPARSE+uniform sampler2D adomTilesSampler;+#endif+vec3 adomAlbedo;+vec2 adomMR;+float adomW;+vec3 adomToLinear(vec3 c) {+#ifdef GAMMAALBEDO+ return toLinearSpace(c);+#else+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c));+#endif+}+// Coverage of one layer from its signed distance d (texels of the field) and its change per texel step+// in x and y (gx, gy): the anti-aliasing width is how much d changes across one pixel along the edge+// normal (jx, jy: the field's texels per pixel step in screen x and y).+float adomCover(float d, float gx, float gy, vec2 jx, vec2 jy, float wIso) {+ vec2 g = vec2(gx, gy);+ float len = length(g);+ float w = len > 0.25 ? length(vec2(dot(g, jx), dot(g, jy))) / len : wIso;+ return clamp(0.5 + d / max(w, 1e-4), 0.0, 1.0);+}+void adomLayersEval(vec2 uv) {+ adomAlbedo = vec3(0.0);+ adomMR = vec2(0.0);+ adomW = 0.0;+ vec2 st = uv * adomLayersInfo.xy;+ vec2 jx = dFdx(st), jy = dFdy(st);+ float xx = dot(jx, jx), yy = dot(jy, jy);+ // Weight: 1 - smoothstep(LO, HI, footprint in base texels), compared squared in field texels+ // (adomFast.x and .y) so that the common cases need no square root.+ float f2 = max(xx, yy);+ if (f2 >= adomFast.y) return;+ if (f2 <= adomFast.x) adomW = 1.0;+ else adomW = 1.0 - smoothstep(adomBlend.x, adomBlend.y, sqrt(f2) / adomLayersInfo.w);+ // Every coverage width w is at most the footprint's diagonal sqrt(xx + yy), so a layer whose |d|+ // exceeds half of it has coverage exactly 0 or 1. Compared on the stored value t = byte / 255 - 0.5:+ // |d| = |t| * 2 * band, h2 = (xx + yy) / 4 / (2 * band)^2.+ float h2 = (xx + yy) * adomFast.z;+ vec3 t = vec3(0.0);+ float idx;+ bool edge;+#ifdef ADOMSPARSE+ float T = adomBlend.z;+ vec2 tile = clamp(floor(st * adomFast.w), vec2(0.0), adomAtlas.zw - 1.0);+ vec4 ind = texelFetch(adomTilesSampler, ivec2(tile), 0);+ vec2 p = vec2(0.0), local = vec2(0.0);+ if (ind.a < 0.99) {+ // A tile with no edge near it: its alpha holds the three inside bits.+ idx = floor(ind.a * 255.0 + 0.5);+ edge = false;+ } else {+ vec3 c = floor(ind.rgb * 255.0 + 0.5);+ vec2 at = vec2(c.r + 256.0 * mod(c.b, 16.0), c.g + 256.0 * floor(c.b / 16.0));+ local = clamp(st - tile * T, vec2(0.0), vec2(T));+ p = at * (T + 2.0) + 1.0 + local;+ t = textureLod(adomLayersSampler, p * adomAtlas.xy, 0.0).rgb - 0.5;+ vec3 t2 = t * t;+ edge = min(min(t2.r, t2.g), t2.b) <= h2;+ idx = dot(step(vec3(0.0), t), vec3(1.0, 2.0, 4.0));+ }+#else+ t = textureLod(adomLayersSampler, uv, 0.0).rgb - 0.5;+ vec3 t2 = t * t;+ edge = min(min(t2.r, t2.g), t2.b) <= h2;+ idx = dot(step(vec3(0.0), t), vec3(1.0, 2.0, 4.0));+#endif+ if (!edge) {+ // adomPal: entry i = (linear rgb, roughness), entry 8 + i = (metallic, 0, 0, 0), for the inside+ // bits i = copper + 2 mask + 4 silk.+ int i = int(idx);+ vec4 a = adomPal[i];+ adomAlbedo = a.rgb;+ adomMR = vec2(adomPal[i + 8].x, a.a);+ return;+ }+ float b2 = 2.0 * adomLayersInfo.z;+ vec3 d0 = t * b2, dx, dy;+#ifdef ADOMSPARSE+ vec2 ainv = adomAtlas.xy;+ // Half-texel steps toward the tile's middle, so every tap stays inside the tile and its ring.+ vec2 o = vec2(local.x < 0.5 * T ? 0.5 : -0.5, local.y < 0.5 * T ? 0.5 : -0.5);+ dx = ((textureLod(adomLayersSampler, (p + vec2(o.x, 0.0)) * ainv, 0.0).rgb - 0.5) * b2 - d0) / o.x;+ dy = ((textureLod(adomLayersSampler, (p + vec2(0.0, o.y)) * ainv, 0.0).rgb - 0.5) * b2 - d0) / o.y;+#else+ vec2 ts = 1.0 / adomLayersInfo.xy;+ dx = ((textureLod(adomLayersSampler, uv + vec2(0.5 * ts.x, 0.0), 0.0).rgb - 0.5) * b2 - d0) * 2.0;+ dy = ((textureLod(adomLayersSampler, uv + vec2(0.0, 0.5 * ts.y), 0.0).rgb - 0.5) * b2 - d0) * 2.0;+#endif+ float wIso = sqrt(0.5 * (xx + yy));+ float c = adomCover(d0.r, dx.r, dy.r, jx, jy, wIso);+ float m = adomCover(d0.g, dx.g, dy.g, jx, jy, wIso);+ float s = adomCover(d0.b, dx.b, dy.b, jx, jy, wIso);+ // surface.py compose(): exposed copper gets the finish, copper under the mask tints it, bare laminate+ // shows in openings without copper, silk is never printed on exposed copper.+ float ae = c * m, ao = c * (1.0 - m), al = (1.0 - c) * m, asl = s * (1.0 - ae);+ vec3 rgb = adomMask.rgb;+ rgb = mix(rgb, adomOver.rgb, ao);+ rgb = mix(rgb, adomLam.rgb, al);+ rgb = mix(rgb, adomFin.rgb, ae);+ rgb = mix(rgb, adomSilk.rgb, asl);+ float rough = adomMask.a;+ rough = mix(rough, adomLam.a, al);+ rough = mix(rough, adomFin.a, ae);+ rough = mix(rough, adomSilk.a, asl);+ float metal = adomMetal.x;+ metal = mix(metal, adomMetal.y, al);+ metal = mix(metal, adomMetal.z, ae);+ metal = mix(metal, adomMetal.w, asl);+ adomAlbedo = adomToLinear(clamp(rgb, 0.0, 1.0));+ adomMR = vec2(metal, rough);+}+#endif+`;+ // The PBR shader's base colour and metallic-roughness samples, replaced where the field carries the+ // whole look (weight 1). A quad on the border of that region can sample with derivatives from its+ // neighbours; those pixels' texture weight there is close to 0 (the smoothstep starts flat).+ const ALBEDO_SAMPLE = `#ifdef ADOMBOARDLAYERS+vec4 albedoTexture=vec4(1.0);+if (adomW < 1.0) albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);+#else+vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);+#endif+`;+ const MR_SAMPLE = `#ifdef ADOMBOARDLAYERS+vec4 surfaceMetallicOrReflectivityColorMap=vec4(1.0);+if (adomW < 1.0) surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);+#else+vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);+#endif+`;+ const UNIFORMS = ['adomLayersInfo', 'adomBlend', 'adomMask', 'adomOver', 'adomLam', 'adomFin', 'adomSilk', 'adomMetal', 'adomAtlas', 'adomFast'];+ const srgbToLinear = (c) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));+ const clamp01 = (x) => Math.min(1, Math.max(0, x));++ class BoardLayersPlugin extends B.MaterialPluginBase {+ constructor(material, ext, tex, tiles) {+ super(material, 'AdomBoardLayers', 300, { ADOMBOARDLAYERS: false, ADOMSPARSE: false });+ this._tex = tex; this._tiles = tiles; this._on = false;+ const e = ext, c = e.colors, r = e.roughness, mt = e.metallic;+ const ts = tex.getSize(), ms = tiles ? tiles.getSize() : { width: 1, height: 1 };+ const fw = e.size[0] / e.baseColorTexels[0], b2 = 2 * e.band;+ this._vals = {+ adomLayersInfo: [e.size[0], e.size[1], e.band, fw],+ adomBlend: [LO, HI, tiles ? e.tileSize : 0, 0],+ adomMask: [...c.mask, r.mask], adomOver: [...c.copperUnderMask, r.mask], adomLam: [...c.laminate, r.laminate],+ adomFin: [...c.finish, r.finish], adomSilk: [...c.silk, r.silk], adomMetal: [mt.mask, mt.laminate, mt.finish, mt.silk],+ adomAtlas: [1 / ts.width, 1 / ts.height, ms.width, ms.height],+ adomFast: [(LO * fw) ** 2, (HI * fw) ** 2, 0.25 / (b2 * b2), tiles ? 1 / e.tileSize : 0],+ };+ this._pal = {};+ }+ get on() { return this._on; }+ set on(v) { if (this._on === v) return; this._on = v; this.markAllDefinesAsDirty(); this._enable(v); }+ get ready() { return this._tex.isReady() && (!this._tiles || this._tiles.isReady()); }+ getClassName() { return 'AdomBoardLayersPlugin'; }+ isCompatible(lang) { return lang === (B.ShaderLanguage ? B.ShaderLanguage.GLSL : 0); }+ isReadyForSubMesh() { return !this._on || this.ready; }+ prepareDefines(defines) { defines.ADOMBOARDLAYERS = this._on; defines.ADOMSPARSE = this._on && !!this._tiles; }+ getSamplers(samplers) { samplers.push('adomLayersSampler', 'adomTilesSampler'); }+ getActiveTextures(list) { if (this._on) { list.push(this._tex); if (this._tiles) list.push(this._tiles); } }+ hasTexture(t) { return t === this._tex || (!!this._tiles && t === this._tiles); }+ getUniforms() {+ return { ubo: [...UNIFORMS.map((name) => ({ name, size: 4, type: 'vec4' })), { name: 'adomPal', size: 4, type: 'vec4', arraySize: 16 }],+ fragment: '#ifdef ADOMBOARDLAYERS\n' + UNIFORMS.map((n) => `uniform vec4 ${n};`).join('\n') + '\nuniform vec4 adomPal[16];\n#endif\n' };+ }+ // The look of each region where all three coverages are 0 or 1 (surface.py compose() with 0/1+ // weights), its colour in the shader's linear space: toLinearSpace() when the base colour map is+ // decoded in the shader (GAMMAALBEDO), the sRGB curve otherwise, as adomToLinear() does.+ _palette(gamma) {+ const key = gamma ? (engine.useExactSrgbConversions ? 'x' : 'p') : 's';+ if (!this._pal[key]) {+ const f = key === 'p' ? (x) => Math.pow(x, 2.2) : srgbToLinear;+ const V = this._vals, out = new Float32Array(64);+ for (let i = 0; i < 8; i++) {+ const c = i & 1, m = (i >> 1) & 1, s = (i >> 2) & 1;+ const ae = c * m, ao = c * (1 - m), al = (1 - c) * m, asl = s * (1 - ae);+ let rgb = V.adomMask.slice(0, 3), rough = V.adomMask[3], metal = V.adomMetal[0];+ if (ao) rgb = V.adomOver.slice(0, 3);+ if (al) { rgb = V.adomLam.slice(0, 3); rough = V.adomLam[3]; metal = V.adomMetal[1]; }+ if (ae) { rgb = V.adomFin.slice(0, 3); rough = V.adomFin[3]; metal = V.adomMetal[2]; }+ if (asl) { rgb = V.adomSilk.slice(0, 3); rough = V.adomSilk[3]; metal = V.adomMetal[3]; }+ out.set([...rgb.map((x) => f(clamp01(x))), rough], 4 * i);+ out.set([metal, 0, 0, 0], 4 * (8 + i));+ }+ this._pal[key] = out;+ }+ return this._pal[key];+ }+ bindForSubMesh(ubo, sc, eng, subMesh) {+ if (!this._on) return;+ for (const n of UNIFORMS) { const v = this._vals[n]; ubo.updateFloat4(n, v[0], v[1], v[2], v[3]); }+ const defs = subMesh && (subMesh.materialDefines || subMesh._materialDefines);+ ubo.updateFloatArray('adomPal', this._palette(!!(defs && defs.GAMMAALBEDO)));+ ubo.setTexture('adomLayersSampler', this._tex);+ if (this._tiles) ubo.setTexture('adomTilesSampler', this._tiles);+ }+ getCustomCode(type) {+ if (type !== 'fragment') return null;+ return {+ CUSTOM_FRAGMENT_DEFINITIONS: GLSL_DEFS,+ CUSTOM_FRAGMENT_MAIN_BEGIN: '#ifdef ADOMBOARDLAYERS\nadomLayersEval(vAlbedoUV);\n#endif\n',+ CUSTOM_FRAGMENT_UPDATE_ALBEDO: '#ifdef ADOMBOARDLAYERS\nsurfaceAlbedo = mix(surfaceAlbedo, vAlbedoColor.rgb * adomAlbedo, adomW);\n#endif\n',+ CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS: '#ifdef ADOMBOARDLAYERS\nmetallicRoughness = mix(metallicRoughness, reflectivityColor.rg * adomMR, adomW);\n#endif\n',+ // Keys starting with "!" are regular expressions over the PBR fragment shader (Babylon's plugin code injection).+ '!vec4 albedoTexture=texture2D\\(albedoSampler,vAlbedoUV\\+uvOffset\\);': ALBEDO_SAMPLE,+ '!vec4 surfaceMetallicOrReflectivityColorMap=texture2D\\(reflectivitySampler,vReflectivityUV\\+uvOffset\\);': MR_SAMPLE,+ };+ }+ // The textures belong to this plugin alone: they go with it, whatever the material's dispose asks.+ dispose() { this._release(); }+ _release() {+ if (this._tex) this._tex.dispose();+ if (this._tiles) this._tiles.dispose();+ textures.delete(this._tex); textures.delete(this._tiles);+ const i = state.plugins.indexOf(this); if (i >= 0) state.plugins.splice(i, 1);+ }+ }++ const isVec3 = (v) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite);+ const valid = (e) => e && (e.layout === 'dense' || e.layout === 'sparse') && e.texture && Number.isInteger(e.texture.index) && e.texture.index >= 0 &&+ (e.layout === 'dense' || (e.indirection && Number.isInteger(e.indirection.index) && e.tileSize > 0)) &&+ [e.size, e.baseColorTexels].every(v => Array.isArray(v) && v.length === 2 && v.every(n => Number.isSafeInteger(n) && n > 0)) && Number.isFinite(e.band) && e.band > 0 &&+ e.colors && e.roughness && e.metallic && ['mask', 'copperUnderMask', 'laminate', 'finish', 'silk'].every(k => isVec3(e.colors[k]) && e.colors[k].every(n => n >= 0 && n <= 1)) &&+ ['mask', 'laminate', 'finish', 'silk'].every(k => [e.roughness[k], e.metallic[k]].every(n => Number.isFinite(n) && n >= 0 && n <= 1));++ // The bytes of a texture's PNG image from the GLB's BIN chunk, or null.+ const imageBytes = (data, index) => {+ const json = data.json;+ const tx = json.textures && json.textures[index];+ const img = tx && json.images && json.images[tx.source];+ const bv = img && img.bufferView != null && json.bufferViews && json.bufferViews[img.bufferView];+ if (!bv || bv.buffer !== 0 || !data.bin || !Number.isSafeInteger(bv.byteLength) || bv.byteLength < 24 || bv.byteLength > 128 * 1024 * 1024 || !Number.isSafeInteger(bv.byteOffset || 0) || (bv.byteOffset || 0) < 0) return null;+ return data.bin.readAsync(bv.byteOffset || 0, bv.byteLength).then((b) => ({ bytes: new Uint8Array(b.buffer, b.byteOffset, b.byteLength), mime: img.mimeType || 'image/png' }));+ };+ const makeTexture = (img, name, mode) => new Promise((ok, no) => {+ if (disposed) return no(new Error('scene disposed'));+ const bytes = img.bytes;+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const cap = engine.getCaps().maxTextureSize;+ if (bytes.length < 24 || header.getUint32(0) !== 0x89504e47 || header.getUint32(4) !== 0x0d0a1a0a ||+ !header.getUint32(16) || !header.getUint32(20) || header.getUint32(16) > cap || header.getUint32(20) > cap) {+ return no(new Error('board layer PNG exceeds texture limits or has an invalid header'));+ }+ let settled = false;+ const done = (error) => {+ if (settled) return;+ settled = true; clearTimeout(timer);+ if (error || disposed) { t.dispose(); textures.delete(t); no(error || new Error('scene disposed')); }+ else ok(t);+ };+ const t = new B.Texture(null, scene, { noMipmap: true, invertY: false, samplingMode: mode, mimeType: 'image/png',+ onLoad: () => done(), onError: (m, e) => done(e instanceof Error ? e : new Error(name + ': ' + (m || 'failed to load'))) });+ const timer = setTimeout(() => done(new Error('board layer texture load timed out')), 10000);+ textures.add(t);+ t.name = name;+ t.wrapU = t.wrapV = B.Texture.CLAMP_ADDRESSMODE;+ t.anisotropicFilteringLevel = 1;+ t.gammaSpace = false;+ t.updateURL('data:adom-board-layers-' + (++uid) + '-' + name, bytes);+ });++ const attach = async (mat, ext, data) => {+ const reads = [imageBytes(data, ext.texture.index), ext.layout === 'sparse' ? imageBytes(data, ext.indirection.index) : null];+ if (!reads[0] || (ext.layout === 'sparse' && !reads[1])) return;+ const [main, tilesImg] = await Promise.all(reads);+ const made = await Promise.allSettled([makeTexture(main, `${mat.name}.layers`, B.Texture.BILINEAR_SAMPLINGMODE),+ tilesImg ? makeTexture(tilesImg, `${mat.name}.layers.tiles`, B.Texture.NEAREST_SAMPLINGMODE) : null]);+ const [tex, tiles] = made.map((r) => (r.status === 'fulfilled' ? r.value : null));+ if (!tex || (tilesImg && !tiles) || (disposed || deadMaterials.has(mat))) {+ if (tex) tex.dispose(); if (tiles) tiles.dispose();+ throw made.find((r) => r.status === 'rejected')?.reason || new Error('material gone');+ }+ const plugin = new BoardLayersPlugin(mat, ext, tex, tiles);+ state.plugins.push(plugin);+ mat.onDisposeObservable.addOnce(() => plugin._release());+ // A shader that does not compile on this GPU must not keep the board from drawing, or the scene from becoming+ // ready: every board material drops back to today's texture, and the failed effect leaves the engine's cache+ // (it never becomes ready, and while it is cached engine.areAllEffectsReady() and so scene.isReady() stay+ // false). The board materials share one compiled effect, so only one of them may hear of it.+ const onError = mat.onError;+ mat.onError = (effect, errors) => {+ if (state.plugins.some((q) => q.on)) { console.warn('[board layers] shader:', errors); state.failed++; }+ for (const q of state.plugins) q.on = false;+ setTimeout(() => { try { if (effect && !effect.isReady()) effect.dispose(true); } catch (e) { console.warn('[board layers]', e); } }, 0);+ if (onError) onError(effect, errors);+ };+ plugin.on = true;+ };++ const observer = usable ? B.SceneLoader.OnPluginActivatedObservable.add((loader) => {+ if (disposed || !loader || loader.name !== 'gltf' || !loader.onParsedObservable || !loader.onMaterialLoadedObservable) return;+ let data = null;+ loader.onParsedObservable.add((d) => { data = d?.json?.extensionsUsed?.includes(EXT) ? d : null; });+ loader.onMaterialLoadedObservable.add((mat) => {+ if (disposed || !data || mat?.getScene() !== scene || mat.getClassName() !== 'PBRMaterial') return;+ const ptr = mat._internalMetadata?.gltf?.pointers?.find(p => /^\/materials\/\d+$/.test(p));+ const ext = ptr && data.json.materials?.[+ptr.split('/')[2]]?.extensions?.[EXT];+ if (!valid(ext)) return;+ const d = data;+ mat.onDisposeObservable.addOnce(() => deadMaterials.add(mat));+ const work = new Promise(resolve => {+ const tryAttach = n => {+ if (disposed || deadMaterials.has(mat) || n <= 0) return resolve();+ const at = mat.albedoTexture;+ if (!at) { setTimeout(() => tryAttach(n - 1), 20); return; }+ if ((at.coordinatesIndex || 0) !== 0) return resolve();+ attach(mat, ext, d).catch(e => { state.failed++; console.warn('[board layers]', mat.name, e); }).finally(resolve);+ };+ Promise.resolve().then(() => tryAttach(500));+ });+ pending.add(work);+ work.finally(() => pending.delete(work));+ });+ }) : null;+ const dispose = () => {+ if (disposed) return;+ disposed = true;+ if (observer) B.SceneLoader.OnPluginActivatedObservable.remove(observer);+ for (const plugin of [...state.plugins]) plugin._release();+ for (const texture of textures) texture.dispose();+ textures.clear();+ };+ scene.onDisposeObservable.addOnce(dispose);+ return {+ async waitReady() { while (pending.size && !disposed) await Promise.allSettled([...pending]); },+ dispose,+ };+}
test/board-layers.test.mjsadded+125@@ -0,0 +1,125 @@+import http from 'node:http';+import assert from 'node:assert/strict';+import { existsSync, readFileSync, readdirSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import puppeteer from 'puppeteer-core';+const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');+const DIST=join(ROOT,process.env.VIEWER_DIST || 'dist-standalone');+const fixture=process.env.BOARD_LAYERS_FIXTURE;+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]);+}++function layerFixture() {+ const base=makeGlb('Adom.Board',['Top','Bottom'],{textured:true}); const n=base.readUInt32LE(12), j=JSON.parse(base.subarray(20,20+n));+ const ext={layout:'dense',texture:{index:0},size:[1,1],baseColorTexels:[1,1],band:2,+ colors:{mask:[0.1,0.2,0.1],copperUnderMask:[0.2,0.3,0.1],laminate:[0.1,0.1,0.1],finish:[0.9,0.7,0.2],silk:[1,1,1]},+ roughness:{mask:0.5,laminate:0.8,finish:0.3,silk:0.6},metallic:{mask:0,laminate:0,finish:1,silk:0}};+ j.materials[0].name='Adom.Board.Top';j.materials[0].extensions={ADOM_board_layers:ext};+ j.materials.push({...j.materials[0],name:'Adom.Board.Bottom'});+ j.meshes.push({...j.meshes[0],primitives:[{...j.meshes[0].primitives[0],material:1}]});j.nodes[1].mesh=1;+ j.extensionsUsed=['ADOM_board_layers'];let buf=Buffer.from(JSON.stringify(j));buf=Buffer.concat([buf,Buffer.alloc((4-buf.length%4)%4,32)]);+ const h=Buffer.from(base.subarray(0,20));h.writeUInt32LE(20+buf.length+base.length-(20+n),8);h.writeUInt32LE(buf.length,12);+ return Buffer.concat([h,buf,base.subarray(20+n)]);+}++const glb=fixture?readFileSync(fixture):layerFixture();+const bytesVariant=(kind)=>{+ const n=glb.readUInt32LE(12), d=JSON.parse(glb.subarray(20,20+n));+ for(const m of d.materials||[]) if(m.extensions?.ADOM_board_layers) {+ if(kind==='legacy') delete m.extensions.ADOM_board_layers;+ else if(kind==='invalid') m.extensions.ADOM_board_layers.texture.index=999999;+ }+ let json=Buffer.from(JSON.stringify(d));json=Buffer.concat([json,Buffer.alloc((4-json.length%4)%4,32)]);+ const head=Buffer.from(glb.subarray(0,20));head.writeUInt32LE(20+json.length+glb.length-(20+n),8);head.writeUInt32LE(json.length,12);+ return Buffer.concat([head,json,glb.subarray(20+n)]);+};+const html=`<html><body style="margin:0"><div id="wrap" style="width:800px;height:600px"></div><script type="module">+await import('/adom-3d-viewer-babylon9.esm.js');+window.v=window.Adom3DViewerBabylon9.init(document.getElementById('wrap'),{zUp:true,showViewCube:false,showGround:false,showHelp:false});+await v.whenReady();window.ready=true;+</script></body></html>`;+const server=http.createServer((req,res)=>{+ const p=new URL(req.url,'http://x').pathname;+ if(p==='/') { res.setHeader('Content-Type','text/html');return res.end(html); }+ if(p.endsWith('.glb')) {res.setHeader('Content-Type','model/gltf-binary');return res.end(p==='/round3.glb'?glb:bytesVariant(p.includes('invalid')?'invalid':'legacy'));}+ const f=resolve(DIST,'.'+p);+ if(f.startsWith(DIST+'/')&&existsSync(f)) {res.setHeader('Content-Type',f.endsWith('.js')?'text/javascript':'application/octet-stream');return res.end(readFileSync(f));}+ res.writeHead(404);res.end();+});+await new Promise(r=>server.listen(0,'127.0.0.1',r));+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();await page.setViewport({width:800,height:600});+ const errors=[];page.on('pageerror',e=>errors.push(String(e)));+ await page.goto('http://127.0.0.1:'+server.address().port+'/');await page.waitForFunction('window.ready===true',{timeout:90000});+ const load=async url=>{+ await page.evaluate(async u=>{await v.replaceModel(u);await Promise.race([v.getScene().whenReadyAsync(),new Promise((_,reject)=>setTimeout(()=>reject(new Error('scene readiness timed out')),60000))]);v.getScene().render();},url);+ return page.evaluate(()=>{+ const s=v.getScene(); const ps=s.materials.map(m=>m.pluginManager?.getPlugin('AdomBoardLayers')).filter(Boolean);+ return {plugins:ps.length,active:ps.filter(p=>p.on).length,ready:s.isReady(),textures:s.textures.length,layerTextures:s.textures.filter(t=>t.name?.includes('.layers')).length,compiled:s.meshes.filter(m=>m.material?.pluginManager?.getPlugin('AdomBoardLayers')).every(m=>m.subMeshes?.every(sm=>sm.effect?.isReady()))};+ });+ };+ const first=await load('/round3.glb');assert.equal(first.plugins,2);assert.equal(first.active,2);assert.equal(first.compiled,true);assert.equal(first.ready,true);+ for(let i=0;i<3;i++){const next=await load('/round3.glb');assert.equal(next.textures,first.textures);assert.equal(next.layerTextures,first.layerTextures);}+ const legacy=await load('/legacy.glb');assert.equal(legacy.plugins,0);assert.equal(legacy.layerTextures,0);assert.equal(legacy.ready,true);+ const invalid=await load('/invalid.glb');assert.equal(invalid.active,0);assert.equal(invalid.layerTextures,0);assert.equal(invalid.ready,true);+ await load('/round3.glb');+ const fallback=await page.evaluate(async()=>{+ const s=v.getScene(),m=s.materials.find(m=>m.pluginManager?.getPlugin('AdomBoardLayers'));+ let removed=false;m.onError({isReady:()=>false,dispose:()=>{removed=true;}},'deliberate regression-test compile failure');+ await new Promise(r=>setTimeout(r,25));await s.whenReadyAsync();s.render();+ return {removed,ready:s.isReady(),active:s.materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length};+ });+ assert.deepEqual(fallback,{removed:true,ready:true,active:0});assert.deepEqual(errors,[]);+ console.log('Round 3: both shaders compiled; replacement releases textures; legacy, invalid-data and shader-error fallbacks pass.');+ console.log(JSON.stringify({first,legacy,invalid,fallback}));+} finally {await browser.close();server.close();}
test/bundle.test.mjs+1−1@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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(JSON.stringify(a) === JSON.stringify(b), `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);
test/help.test.mjs+1−1@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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); } } function section(t) { console.log("\n [" + t + "]"); }
test/home-target.test.mjs+1−1@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone"); const deadline = Date.now() + 120_000; let passed = 0, failed = 0; const failures = [];
test/intro.test.mjs+1−1@@ -9,7 +9,7 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");-const DIST = join(ROOT, "dist-standalone");+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)})`);
test/layers.test.mjs+1−1@@ -13,7 +13,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone"); const SHOTS = process.env.SHOTS || ""; 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); } }
test/lights.test.mjs+1−1@@ -11,7 +11,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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)})`);
test/orbit.test.mjs+1−1@@ -14,7 +14,7 @@ import { createRequire } from "node:module"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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;
test/replace.test.mjs+1−1@@ -12,7 +12,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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(JSON.stringify(a) === JSON.stringify(b), `${msg} (got ${JSON.stringify(a)}, want ${JSON.stringify(b)})`);
test/shadow-size.test.mjs+1−1@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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)})`);
test/state-scope.test.mjs+1−1@@ -13,7 +13,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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)})`);
test/viewcube.test.mjs+1−1@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone"); const deadline = Date.now() + 240_000; let passed = 0, failed = 0; const failures = [];
test/visibility.test.mjs+1−1@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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); } } function section(t) { console.log("\n [" + t + "]"); }
test/wiki-sandbox.test.mjs+1−1@@ -22,7 +22,7 @@ import { createRequire } from "node:module"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, "..");-const DIST = join(ROOT, "dist-standalone");+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;
vite.standalone.config.mts+1−1@@ -55,7 +55,7 @@ export default defineConfig({ chunkFileNames: 'chunk-[hash].js', }, },- outDir: 'dist-standalone',+ outDir: process.env.VIEWER_DIST || 'dist-standalone', minify: 'esbuild', // Hidden: the maps are written for turning a reported position // (chunk-x.js:1:23456) back into a source line, never referenced or served.