master
AdityaAngajala v0.13.0 12542ed
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 { deflateSync } from 'node:zlib';
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");
let passed=0;const ok=m=>{passed++;console.log('    ok '+m);};

/** 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}};
 // A metallic-roughness map as normalized boards have, so both sample replacements compile.
 j.materials[0].pbrMetallicRoughness.metallicRoughnessTexture={index: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)]);
}

// An RGBA8 PNG (no filtering), for the synthetic layer textures.
const CRC=new Uint32Array(256).map((_,n)=>{let c=n;for(let k=0;k<8;k++)c=c&1?0xedb88320^(c>>>1):c>>>1;return c>>>0;});
const crc32=b=>{let c=~0;for(const x of b)c=CRC[(c^x)&255]^(c>>>8);return ~c>>>0;};
function png(w,h,rgba){
 const chunk=(type,data)=>{const len=Buffer.alloc(4),crc=Buffer.alloc(4),td=Buffer.concat([Buffer.from(type),data]);len.writeUInt32BE(data.length);crc.writeUInt32BE(crc32(td));return Buffer.concat([len,td,crc]);};
 const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(w,0);ihdr.writeUInt32BE(h,4);ihdr[8]=8;ihdr[9]=6;
 const raw=Buffer.alloc(h*(1+4*w));for(let y=0;y<h;y++)Buffer.from(rgba.subarray(y*4*w,(y+1)*4*w)).copy(raw,y*(1+4*w)+1);
 return Buffer.concat([Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]),chunk('IHDR',ihdr),chunk('IDAT',deflateSync(raw)),chunk('IEND',Buffer.alloc(0))]);
}

// The sparse layout production boards use on both faces: a 16x16 field in 8x8 tiles, read through a 2x2
// tile map. Three tiles are flat (no edge near them; the map's alpha holds the inside bits): exposed copper
// (finish), bare mask, silk. The fourth points at atlas tile (1, 0), whose copper edge runs down its
// middle: finish on the left, laminate in the mask opening on the right. Atlas tile (0, 0) holds copper
// under mask, a colour no correct read shows. Seen face-on, a quarter of each face is mask and silk, 3/8
// finish, 1/8 laminate. The base colour map is magenta, so a face drawn without the field is obvious.
const SPARSE_COLORS={mask:[0.05,0.1,0.85],copperUnderMask:[0.85,0.8,0.05],laminate:[0.05,0.75,0.1],finish:[0.85,0.08,0.05],silk:[0.95,0.95,0.95]};
function sparseFixture() {
 const T=8,band=4,enc=d=>Math.round((Math.max(-band,Math.min(band,d))/(2*band)+0.5)*255);
 const tiles=new Uint8Array([0,0,0,3, 0,0,0,0, 0,0,0,4, 1,0,0,255]);
 const AW=2*(T+2),AH=T+2,atlas=new Uint8Array(AW*AH*4);
 for(let y=0;y<AH;y++) for(let x=0;x<AW;x++){
  const i=4*(y*AW+x),tile=Math.floor(x/(T+2)),lx=x-tile*(T+2)-1; // lx: the tile-local texel, -1 and T are its ring
  const rgb=tile===0?[enc(band),enc(-band),enc(-band)]:[enc(T/2-(lx+0.5)),enc(band),enc(-band)];
  atlas.set([...rgb,255],i);
 }
 const images=[png(1,1,new Uint8Array([255,0,255,255])),png(AW,AH,atlas),png(2,2,tiles)];
 const s=0.01,h=0.0008;
 const pos=new Float32Array([-s,-s,h, s,-s,h, s,s,h, -s,s,h, -s,-s,-h, s,-s,-h, s,s,-h, -s,s,-h]);
 const nrm=new Float32Array([0,0,1, 0,0,1, 0,0,1, 0,0,1, 0,0,-1, 0,0,-1, 0,0,-1, 0,0,-1]);
 const uv=new Float32Array([0,0, 1,0, 1,1, 0,1, 0,0, 1,0, 1,1, 0,1]);
 const top=new Uint16Array([0,1,2, 0,2,3]),bottom=new Uint16Array([4,6,5, 4,7,6]);
 const pad=b=>Buffer.concat([b,Buffer.alloc((4-b.length%4)%4)]);
 const parts=[pos,nrm,uv,top,bottom].map(a=>Buffer.from(a.buffer)).concat(images);
 const views=[];let off=0,bin=Buffer.alloc(0);
 for(const p of parts){views.push({buffer:0,byteOffset:off,byteLength:p.length});const q=pad(p);bin=Buffer.concat([bin,q]);off+=q.length;}
 const ext={layout:'sparse',texture:{index:1},indirection:{index:2},tileSize:T,size:[16,16],baseColorTexels:[1,1],band,colors:SPARSE_COLORS,
  roughness:{mask:0.9,laminate:0.9,finish:0.9,silk:0.9},metallic:{mask:0,laminate:0,finish:0,silk:0}};
 const mat=name=>({name,doubleSided:true,pbrMetallicRoughness:{baseColorTexture:{index:0},metallicRoughnessTexture:{index:0}},extensions:{ADOM_board_layers:ext}});
 const json={asset:{version:'2.0'},scene:0,scenes:[{nodes:[0,1]}],extensionsUsed:['ADOM_board_layers'],
  nodes:[{name:'Board_top',mesh:0},{name:'Board_bottom',mesh:1}],
  meshes:[3,4].map((indices,material)=>({primitives:[{attributes:{POSITION:0,NORMAL:1,TEXCOORD_0:2},indices,material}]})),
  materials:[mat('Adom.Board.Top'),mat('Adom.Board.Bottom')],
  textures:[0,1,2].map(source=>({source})),images:[5,6,7].map(bufferView=>({bufferView,mimeType:'image/png'})),
  buffers:[{byteLength:bin.length}],bufferViews:views,
  accessors:[{bufferView:0,componentType:5126,count:8,type:'VEC3',min:[-s,-s,-h],max:[s,s,h]},{bufferView:1,componentType:5126,count:8,type:'VEC3'},
   {bufferView:2,componentType:5126,count:8,type:'VEC2'},{bufferView:3,componentType:5123,count:6,type:'SCALAR'},{bufferView:4,componentType:5123,count:6,type:'SCALAR'}]};
 let text=Buffer.from(JSON.stringify(json));text=Buffer.concat([text,Buffer.alloc((4-text.length%4)%4,32)]);
 const head=Buffer.alloc(20);head.write('glTF');head.writeUInt32LE(2,4);head.writeUInt32LE(28+text.length+bin.length,8);head.writeUInt32LE(text.length,12);head.write('JSON',16);
 const chunk=Buffer.alloc(8);chunk.writeUInt32LE(bin.length);chunk.write('BIN\0',4);
 return {glb:Buffer.concat([head,text,chunk,bin]),baseBytes:images[0].length};
}

const glb=fixture?readFileSync(fixture):layerFixture();
const sparse=sparseFixture();
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)]);
};
// window.__slowDecode (ms) holds back the decode of every image except the sparse fixture's base colour
// map, so a test can catch the layer textures mid-load.
const html=`<html><body style="margin:0"><div id="wrap" style="width:800px;height:600px"></div><div id="wrap2" style="position:absolute;left:0;top:0;width:400px;height:300px"></div><div id="wrap3" style="position:absolute;left:400px;top:0;width:400px;height:300px"></div><script type="module">
const decode=window.createImageBitmap.bind(window);window.__slowDecode=0;
window.createImageBitmap=async(src,...rest)=>{if(window.__slowDecode&&src instanceof Blob&&src.size!==${sparse.baseBytes})await new Promise(r=>setTimeout(r,window.__slowDecode));return decode(src,...rest);};
// Ready, rendered, and still ready after that frame (a frame can start a shader compile, which a loaded
// CI runner makes slow). A scene that never gets there gives up after 60 s and fails the check that follows.
window.__settle=async s=>{const end=performance.now()+60000;do{await Promise.race([s.whenReadyAsync(true),new Promise(r=>setTimeout(r,1000))]);s.render();}while(!s.isReady()&&performance.now()<end);};
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.loadModel('/round3.glb');
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:p==='/sparse.glb'?sparse.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 immediate=await page.evaluate(()=>v.getScene().materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length);
 assert.equal(immediate,2,'loading immediately after init keeps both board shaders');ok('a load right after init gets both board shaders');
 const load=async url=>{
  await page.evaluate(async u=>{await v.replaceModel(u);await __settle(v.getScene());},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()))};
  });
 };
 // The compiled board effects: whether the sparse path is in, and whether the PBR shader's base colour and
 // metallic-roughness samples were replaced. The replacements match Babylon's shader text by regular
 // expression, so a Babylon update that rewrites those lines drops them without an error.
 const effects=()=>page.evaluate(()=>v.getScene().meshes.filter(m=>m.material?.pluginManager?.getPlugin('AdomBoardLayers')?.on).flatMap(m=>m.subMeshes.map(sm=>{
  const fs=sm.effect?.fragmentSourceCode||'';
  return {sparse:/#define ADOMSPARSE\b/.test(sm.effect?.defines||''),albedo:fs.includes('if (adomW < 1.0) albedoTexture='),mr:fs.includes('if (adomW < 1.0) surfaceMetallicOrReflectivityColorMap='),eval:fs.includes('adomLayersEval(vAlbedoUV)')};
 })));
 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);ok('dense: both shaders compile and the scene is ready');
 const dense=await effects();assert.ok(dense.length>=2);
 for(const e of dense) assert.deepEqual(e,{sparse:false,albedo:true,mr:true,eval:true},'dense effect carries the field and both sample replacements');
 ok('dense: the compiled fragment source has the field and both sample replacements');
 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);}ok('replacing the model three times releases its layer textures');
 const legacy=await load('/legacy.glb');assert.equal(legacy.plugins,0);assert.equal(legacy.layerTextures,0);assert.equal(legacy.ready,true);ok('a GLB without the extension keeps its textures');
 const invalid=await load('/invalid.glb');assert.equal(invalid.active,0);assert.equal(invalid.layerTextures,0);assert.equal(invalid.ready,true);ok('invalid extension data falls back');

 const sparseLoad=await load('/sparse.glb');assert.equal(sparseLoad.plugins,2);assert.equal(sparseLoad.active,2);assert.equal(sparseLoad.layerTextures,4);assert.equal(sparseLoad.compiled,true);assert.equal(sparseLoad.ready,true);
 ok('sparse: both faces get the shader with their atlas and tile map, and it compiles');
 const sparseFx=await effects();assert.ok(sparseFx.length>=2);
 for(const e of sparseFx) assert.deepEqual(e,{sparse:true,albedo:true,mr:true,eval:true},'sparse effect is the ADOMSPARSE variant with both sample replacements');
 ok('sparse: the compiled fragment source is the ADOMSPARSE variant with both sample replacements');
 // Face-on from above, black background, no axes: count pixels by colour.
 const colours=await page.evaluate(async()=>{
  v.toggleAxes('world',false);v.getScene().clearColor.set(0,0,0,1);
  await v.moveCamera('top',{ms:0});v.frameModel(0.8);
  const s=v.getScene();await __settle(s);s.render();
  const src=v.getEngine().getRenderingCanvas(),c=document.createElement('canvas');c.width=src.width;c.height=src.height;
  const g=c.getContext('2d');g.drawImage(src,0,0);const d=g.getImageData(0,0,c.width,c.height).data;
  const n={finish:0,mask:0,silk:0,laminate:0,copperUnderMask:0,base:0};
  for(let i=0;i<d.length;i+=4){
   const r=d[i],gr=d[i+1],b=d[i+2],hi=Math.max(r,gr,b),lo=Math.min(r,gr,b);
   if(hi<40) continue;
   if(hi-lo<40&&lo>90) n.silk++;
   else if(r>gr+60&&b>gr+60) n.base++;
   else if(r>gr+60&&r>b+60) n.finish++;
   else if(gr>r+60&&gr>b+60) n.laminate++;
   else if(b>r+60&&b>gr+60) n.mask++;
   else if(r>b+60&&gr>b+60) n.copperUnderMask++;
  }
  return n;
 });
 console.log('    sparse face pixels: '+JSON.stringify(colours));
 const near=(x,want,tol)=>Math.abs(x-want)<=tol*want;
 const q=colours.mask;
 assert.ok(q>2000,'the mask quarter is on screen');
 assert.ok(near(colours.silk/q,1,0.25),'silk covers a quarter, as the mask does');
 assert.ok(near(colours.finish/q,1.5,0.25),'finish covers 3/8: one flat tile and half the atlas tile');
 assert.ok(near(colours.laminate/q,0.5,0.3),'laminate covers 1/8: the other half of the atlas tile');
 assert.ok(colours.copperUnderMask<q*0.02,'nothing reads atlas tile (0, 0)');
 assert.ok(colours.base<q*0.02,'no pixel shows the base colour map');
 ok('sparse: face-on, the tile map and atlas paint mask, silk, finish and laminate in the right shares');

 // Two viewers at once, each with its own scene: the loader hook is global, the materials are not.
 const two=await page.evaluate(async()=>{
  const V=window.Adom3DViewerBabylon9,opts={zUp:true,showViewCube:false,showGround:false,showHelp:false};
  const a=V.init(document.getElementById('wrap2'),opts),b=V.init(document.getElementById('wrap3'),opts);
  await Promise.all([a.loadModel('/sparse.glb'),b.loadModel('/round3.glb')]);
  await Promise.all([a.whenReady(),b.whenReady()]);
  const look=x=>{const s=x.getScene(),ps=s.materials.map(m=>m.pluginManager?.getPlugin('AdomBoardLayers')).filter(p=>p?.on);
   return {on:ps.length,own:ps.every(p=>p._tex.getScene()===s&&(!p._tiles||p._tiles.getScene()===s)),layerTextures:s.textures.filter(t=>t.name?.includes('.layers')).length};};
  const before={a:look(a),b:look(b)};
  const bTextures=b.getScene().textures.filter(t=>t.name?.includes('.layers'));
  a.destroy();
  await new Promise(r=>setTimeout(r,1000));
  const s=b.getScene();await __settle(s);
  const after={b:look(b),kept:bTextures.every(t=>s.textures.includes(t)&&t.getInternalTexture()&&t.isReady()),ready:s.isReady()};
  b.destroy();
  return {before,after};
 });
 assert.deepEqual(two.before,{a:{on:2,own:true,layerTextures:4},b:{on:2,own:true,layerTextures:2}},'two viewers each get their own board shaders and textures');
 assert.deepEqual(two.after,{b:{on:2,own:true,layerTextures:2},kept:true,ready:true},'destroying one leaves the other its shaders and textures');
 ok('two viewers: each has its own board materials; destroying one leaves the other drawing');

 // Click to load: a load asked for behind a closed gate waits for the viewer, then gets the shader.
 const gated=await page.evaluate(async()=>{
  const g=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false,gate:{bytes:1}});
  let loaded=false;const loading=g.loadModel('/round3.glb').then(()=>{loaded=true;});
  await new Promise(r=>setTimeout(r,300));
  const waiting={gated:g.isGated(),scene:!!g.getScene(),loaded};
  await g.openGate();await loading;
  const on=g.getScene().materials.filter(m=>m.pluginManager?.getPlugin('AdomBoardLayers')?.on).length;
  g.destroy();
  return {waiting,on};
 });
 assert.deepEqual(gated,{waiting:{gated:true,scene:false,loaded:false},on:2},'a load behind the gate waits, then gets both board shaders');
 ok('gate: a load asked for before openGate() gets both board shaders');

 // destroy() with layer textures still loading: the load settles, the scene is released, and nothing
 // throws, whether the destroy comes while the field images decode or 0 to 400 ms after a board load,
 // while its shaders may still compile.
 const beforeDestroy=errors.length;
 const midDecode=await page.evaluate(async()=>{
  const d=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false});
  await d.whenReady();
  window.__slowDecode=1500;
  let settled=null;d.loadModel('/sparse.glb').then(()=>{settled='resolved';},e=>{settled='rejected: '+e.message;});
  const s=d.getScene(),t0=performance.now();
  let caught=false;
  while(performance.now()-t0<5000){
   if(s.textures.some(t=>t.name?.includes('.layers')&&!t.isReady())){caught=true;break;}
   await new Promise(r=>setTimeout(r,5));
  }
  d.destroy();
  const t1=performance.now();
  while(!s.isDisposed&&performance.now()-t1<20000) await new Promise(r=>setTimeout(r,50));
  await new Promise(r=>setTimeout(r,2000));
  window.__slowDecode=0;
  return {caught,settled,disposed:s.isDisposed};
 });
 assert.deepEqual(midDecode,{caught:true,settled:'resolved',disposed:true},'a destroy while the field images decode settles the load and releases the scene');
 await page.evaluate(async()=>{
  for(const ms of [0,20,50,100,200,400]){
   const d=window.Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{zUp:true,showViewCube:false,showGround:false,showHelp:false});
   await d.whenReady();
   await d.loadModel('/sparse.glb');
   await new Promise(r=>setTimeout(r,ms));
   d.destroy();
  }
  await new Promise(r=>setTimeout(r,2500));
 });
 assert.deepEqual(errors.slice(beforeDestroy),[],'no page errors from destroys during layer texture loads');
 ok('destroy: while the field images decode and 0 to 400 ms after a board load, the load settles, the scene is released and nothing throws');

 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 __settle(s);
  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,[]);ok('a shader that does not compile drops every board material back to its textures');
 console.log('Round 3: dense and sparse shaders compiled with both sample replacements; replacement releases textures; two viewers, the gate, destroy during loads, and the legacy, invalid-data and shader-error fallbacks pass.');
 console.log(JSON.stringify({first,legacy,invalid,sparse:sparseLoad,colours,fallback}));
 console.log(`${passed} passed, 0 failed`);
} finally {await browser.close();server.close();}