master
AdityaAngajala v0.12.9 1c94345
// Board Look 0.6's approved machine-gold finish. Geometry/rim rounding and
// roughness are already in the GLB; grain and the reflected studio are viewer
// effects, separate from ADOM_board_layers' copper/mask/silk shader.
import { MaterialPluginBase } from '@babylonjs/core/Materials/materialPluginBase';
import { CubeTexture } from '@babylonjs/core/Materials/Textures/cubeTexture';
import { SceneLoader } from '@babylonjs/core/Loading/sceneLoader';
import { PIN_STUDIO_ENV_BASE64 } from './adom-babylon/assets/pinStudioEnv';

// Exact grain function/settings from board-look/studio/modules/metal.js.
class PinGrainPlugin extends MaterialPluginBase {
  constructor(material) {
    super(material, 'AdomPinGrain', 190, { ADOMPINGRAIN: false });
    this._on = false;
  }
  get on() { return this._on; }
  set on(v) { if (this._on === v) return; this._on = v; this.markAllDefinesAsDirty(); this._enable(v); }
  getClassName() { return 'AdomPinGrainPlugin'; }
  isCompatible(lang) { return lang === 0; }
  prepareDefines(defines) { defines.ADOMPINGRAIN = this._on; }
  getCustomCode(type) {
    if (type !== 'fragment') return null;
    return {
      CUSTOM_FRAGMENT_DEFINITIONS: `
#ifdef ADOMPINGRAIN
float adomPinHash(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); }
float adomPinNoise(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
  return mix(mix(mix(adomPinHash(i), adomPinHash(i + vec3(1, 0, 0)), f.x), mix(adomPinHash(i + vec3(0, 1, 0)), adomPinHash(i + vec3(1, 1, 0)), f.x), f.y),
    mix(mix(adomPinHash(i + vec3(0, 0, 1)), adomPinHash(i + vec3(1, 0, 1)), f.x), mix(adomPinHash(i + vec3(0, 1, 1)), adomPinHash(i + vec3(1, 1, 1)), f.x), f.y), f.z); }
vec3 adomPinNormal(vec3 n, vec3 pw) {
  vec3 p = pw / 0.00002;
  float fade = 1.0 - smoothstep(0.5, 2.0, max(length(dFdx(p)), length(dFdy(p))));
  if (fade <= 0.0) return n;
  vec3 g = (vec3(adomPinNoise(p), adomPinNoise(p + vec3(31.7, 13.1, 7.9)), adomPinNoise(p + vec3(8.2, 47.6, 19.3))) * 2.0 - 1.0) * 0.04 * fade;
  return normalize(n + g - n * dot(g, n));
}
#endif
`,
      CUSTOM_FRAGMENT_BEFORE_LIGHTS: '#ifdef ADOMPINGRAIN\nnormalW = adomPinNormal(normalW, vPositionW);\n#endif\n',
    };
  }
}

export function installPinFinish(scene, { reflections = true } = {}) {
  let disposed = false, failed = false, studio = null, studioReady = null, cancelLoad = null;
  const pending = new Set(), handled = new WeakSet(), dead = new WeakSet();
  const plugins = new Set(), materialTextures = new Map();
  const engine = scene.getEngine();
  const grainSupported = !engine.isWebGPU && (engine.webGLVersion || 1) >= 2;

  const loadStudio = () => {
    if (studioReady) return studioReady;
    // Read the same baked 128px map as the reference, from bundled bytes.
    // No external/blob URL is needed under the wiki's strict sandbox CSP.
    const bytes = Uint8Array.from(atob(PIN_STUDIO_ENV_BASE64), c => c.charCodeAt(0));
    studioReady = new Promise(resolve => {
      let settled = false, texture;
      const finish = error => {
        if (settled) return;
        settled = true; clearTimeout(timer); cancelLoad = null;
        if (error || disposed) {
          texture?.dispose(); studio = null;
          if (error && !disposed) console.warn('[pin finish] studio:', error);
          resolve(null);
        } else resolve(texture);
      };
      const timer = setTimeout(() => finish('environment load timed out'), 10000);
      cancelLoad = () => finish(null);
      texture = new CubeTexture('adom-pin-studio.env', scene, {
        buffer: bytes, prefiltered: true, forcedExtension: '.env',
        onLoad: () => finish(null),
        onError: message => finish(message || 'environment load failed'),
      });
      studio = texture;
      texture.name = 'AdomPinStudio';
      texture.gammaSpace = false;
    });
    return studioReady;
  };

  const attach = material => {
    if (disposed || handled.has(material) || material?.getScene() !== scene ||
        material.getClassName() !== 'PBRMaterial' || material.name !== 'AdomMachineGold') return;
    handled.add(material);
    let grain = null;
    if (grainSupported && !failed) {
      grain = new PinGrainPlugin(material); plugins.add(grain); grain.on = true;
      const onError = material.onError;
      material.onError = (effect, errors) => {
        if (!failed) console.warn('[pin finish] shader:', errors);
        failed = true;
        for (const p of plugins) p.on = false;
        setTimeout(() => { if (effect && !effect.isReady()) effect.dispose(true); }, 0);
        onError?.(effect, errors);
      };
    }
    material.onDisposeObservable.addOnce(() => {
      dead.add(material);
      if (grain) plugins.delete(grain);
      materialTextures.get(material)?.dispose(); materialTextures.delete(material);
    });
    if (!reflections || material.reflectionTexture) return;
    const work = loadStudio().then(texture => {
      if (!texture || disposed || dead.has(material) || material.reflectionTexture) return;
      // Each material owns a texture wrapper. Babylon reference-counts the
      // underlying cube map, so replacing one model cannot dispose another
      // model's reflections or the scene-owned source texture.
      const copy = texture.clone();
      copy.name = 'AdomPinStudio.material';
      materialTextures.set(material, copy); material.reflectionTexture = copy;
    }).catch(error => console.warn('[pin finish]', error));
    pending.add(work); work.finally(() => pending.delete(work));
  };

  // Attach before the first material compilation, scoped to this viewer's
  // glTF loads. Other viewers and ordinary metals keep their own materials.
  const observer = SceneLoader.OnPluginActivatedObservable.add(loader => {
    if (disposed || loader?.name !== 'gltf' || !loader.onMaterialLoadedObservable) return;
    loader.onMaterialLoadedObservable.add(attach);
  });
  const dispose = () => {
    if (disposed) return;
    disposed = true;
    SceneLoader.OnPluginActivatedObservable.remove(observer);
    cancelLoad?.();
    for (const [material, texture] of materialTextures) {
      if (material.reflectionTexture === texture) material.reflectionTexture = null;
      texture.dispose();
    }
    materialTextures.clear(); plugins.clear(); studio?.dispose(); studio = null;
  };
  scene.onDisposeObservable.addOnce(dispose);
  return {
    async waitReady() { while (pending.size && !disposed) await Promise.allSettled([...pending]); },
    dispose,
  };
}