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 puppeteer from 'puppeteer-core';

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const DIST = join(ROOT, process.env.VIEWER_DIST || 'dist-standalone');
let passed = 0; const ok = m => { passed++; console.log('    ok ' + m); };
const positions = new Float32Array([-0.001,-0.001,0, 0.001,-0.001,0, 0,0.001,0]);
const normals = new Float32Array([0,0,1, 0,0,1, 0,0,1]);
const bin = Buffer.concat([Buffer.from(positions.buffer), Buffer.from(normals.buffer)]);
const json = {
  asset: { version:'2.0' }, scene:0, scenes:[{nodes:[0,1]}],
  nodes:[{name:'MP1',mesh:0},{name:'plastic',mesh:1,translation:[0.003,0,0]}],
  meshes:[0,1].map(material=>({primitives:[{attributes:{POSITION:0,NORMAL:1},material}]})),
  materials:[{name:'AdomMachineGold',pbrMetallicRoughness:{baseColorFactor:[0.871,0.578,0.156,1],metallicFactor:1,roughnessFactor:0.16},doubleSided:true},
    {name:'UnrelatedMetal',pbrMetallicRoughness:{metallicFactor:1,roughnessFactor:0.3},doubleSided:true}],
  buffers:[{byteLength:bin.length}],bufferViews:[{buffer:0,byteOffset:0,byteLength:positions.byteLength},{buffer:0,byteOffset:positions.byteLength,byteLength:normals.byteLength}],
  accessors:[{bufferView:0,componentType:5126,count:3,type:'VEC3',min:[-0.001,-0.001,0],max:[0.001,0.001,0]},
    {bufferView:1,componentType:5126,count:3,type:'VEC3'}],
};
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);
const glb = Buffer.concat([head,text,chunk,bin]);
// window.__slowDecode (ms) holds back every image decode, so a test can catch the pin studio map mid-load.
const html = `<div id="wrap" style="width:640px;height:480px"></div><div id="wrap2" style="position:absolute;left:0;top:0;width:320px;height:240px"></div><script type="module">
const decode=window.createImageBitmap.bind(window);window.__slowDecode=0;
window.createImageBitmap=async(src,...rest)=>{if(window.__slowDecode)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 = Adom3DViewerBabylon9.init(document.getElementById('wrap'),{showGround:false,showViewCube:false,showHelp:false,environment:new URLSearchParams(location.search).has('none')?'none':'studio'});
const early = new URLSearchParams(location.search).get('early');
if (early === 'url') await v.loadModel('/pins');
if (early === 'bytes') await v.loadModelBytes(Uint8Array.from(atob('${glb.toString('base64')}'),c=>c.charCodeAt(0)));
await v.whenReady(); window.ready = true;
</script>`;
const server = http.createServer((req,res)=>{
  const path = new URL(req.url,'http://x').pathname;
  if(path==='/') {res.setHeader('Content-Type','text/html');res.setHeader('Content-Security-Policy',"default-src 'self' data:; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self' data:");return res.end(html);}
  if(path==='/pins.glb'||path==='/pins') {res.setHeader('Content-Type','model/gltf-binary');return res.end(glb);}
  const file=resolve(DIST,'.'+path);
  if(file.startsWith(DIST+'/')&&existsSync(file)) {res.setHeader('Content-Type',file.endsWith('.js')?'text/javascript':'application/octet-stream');return res.end(readFileSync(file));}
  res.writeHead(404);res.end();
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
function chromePath() {
  if(process.env.PUPPETEER_EXECUTABLE_PATH) return process.env.PUPPETEER_EXECUTABLE_PATH;
  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');
}
const browser=await puppeteer.launch({executablePath:chromePath(),headless:true,args:['--no-sandbox','--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--disable-gpu-sandbox']});
try {
  const page=await browser.newPage(), errors=[], violations=[];
  page.on('pageerror',e=>errors.push(String(e)));
  page.on('console',m=>{if(m.text().includes('Content Security Policy')) violations.push(m.text());});
  const url='http://127.0.0.1:'+server.address().port;
  // The wiki calls loadModel immediately after init, before whenReady.
  // Cover that order for both extensionless URLs and already-available bytes.
  for (const early of ['url','bytes']) {
    await page.goto(url+'/?early='+early);await page.waitForFunction('window.ready===true',{timeout:90000});
    const applied=await page.evaluate(async()=>{
      const s=v.getScene();await __settle(s);
      const gold=s.materials.find(m=>m.name==='AdomMachineGold');
      return {grain:!!gold?.pluginManager?.getPlugin('AdomPinGrain')?.on,reflections:!!gold?.reflectionTexture?.isReady()};
    });
    assert.deepEqual(applied,{grain:true,reflections:true},'immediate '+early+' load keeps the pin finish');ok('a '+early+' load right after init gets the grain and reflections');
  }
  await page.goto(url);await page.waitForFunction('window.ready===true',{timeout:90000});
  const load=async(add=false)=>page.evaluate(async additive=>{
    await (additive?v.addModel('/pins.glb'):v.replaceModel('/pins.glb'));
    const s=v.getScene();await __settle(s);
    const gold=s.materials.filter(m=>m.name==='AdomMachineGold');
    return {gold:gold.length,active:gold.filter(m=>m.pluginManager?.getPlugin('AdomPinGrain')?.on).length,
      reflected:gold.filter(m=>m.reflectionTexture?.isReady()).length, textures:s.textures.length,
      unrelated:s.materials.filter(m=>m.name==='UnrelatedMetal').every(m=>!m.reflectionTexture&&!m.pluginManager?.getPlugin('AdomPinGrain')),
      compiled:s.meshes.filter(m=>gold.includes(m.material)).every(m=>m.subMeshes.every(sm=>sm.effect?.isReady())),
      ready:s.isReady(),intensity:s.environmentIntensity,tone:s.imageProcessingConfiguration.toneMappingEnabled};
  },add);
  const first=await load();assert.equal(first.active,1);assert.equal(first.reflected,1);assert.equal(first.compiled,true);assert.equal(first.unrelated,true);assert.equal(first.intensity,0.5);assert.equal(first.tone,true);ok('grain and reflections on the pin only; intensity 0.5 and tone mapping on');
  for(let i=0;i<3;i++) assert.deepEqual(await load(),first);ok('replacing the model three times leaves the same textures');
  const added=await load(true);assert.equal(added.active,2);assert.equal(added.reflected,2);assert.equal(added.ready,true);
  assert.deepEqual(await load(),first);ok('an added model gets its own reflections; replacing it goes back to one');
  const fallback=await page.evaluate(async()=>{
    const s=v.getScene(), m=s.materials.find(m=>m.name==='AdomMachineGold');let removed=false;
    m.onError({isReady:()=>false,dispose:()=>{removed=true;}},'deliberate test compile failure');
    await new Promise(r=>setTimeout(r,30));await __settle(s);
    return {removed,ready:s.isReady(),active:m.pluginManager.getPlugin('AdomPinGrain').on};
  });
  assert.deepEqual(fallback,{removed:true,ready:true,active:false});ok('a grain shader that does not compile falls back');
  // destroy() with the pin studio map still decoding, and 0 to 400 ms after a pin load: the load
  // settles, the scene is released, and nothing throws.
  const midDecode=await page.evaluate(async()=>{
    const d=Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{showGround:false,showViewCube:false,showHelp:false});
    await d.whenReady();
    window.__slowDecode=1500;
    let settled=null;d.loadModel('/pins.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==='AdomPinStudio'&&!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 pin studio map decodes settles the load and releases the scene');ok('a destroy while the studio map decodes settles the load and releases the scene');
  await page.evaluate(async()=>{
    for(const ms of [0,20,50,100,200,400]){
      const d=Adom3DViewerBabylon9.init(document.getElementById('wrap2'),{showGround:false,showViewCube:false,showHelp:false});
      await d.whenReady();
      await d.loadModel('/pins.glb');
      await new Promise(r=>setTimeout(r,ms));
      d.destroy();
    }
    await new Promise(r=>setTimeout(r,2500));
  });
  assert.deepEqual(errors,[],'no page errors from destroys while the pin finish loads');ok('destroys during and 0 to 400 ms after a pin load throw nothing');
  await page.goto(url+'/?none');await page.waitForFunction('window.ready===true',{timeout:90000});
  const none=await load();assert.equal(none.active,1);assert.equal(none.reflected,0);assert.equal(none.ready,true);ok("environment: 'none' keeps the grain and drops the reflections");
  assert.deepEqual(errors,[]);assert.deepEqual(violations,[]);ok('no page errors and no CSP violations');
  console.log(JSON.stringify({first,added,fallback,midDecode,none}));
  console.log('Pin grain compiles; bundled reflections obey CSP; non-pin materials, replacement, additive loads, destroy during loads, no-environment and compile fallback pass.');
  console.log(`${passed} passed, 0 failed`);
} finally {await browser.close();server.close();}