rayzee 9.3.1 → 9.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -712,7 +712,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
712
712
  let p = o + xu * x + yv * y + z0 * z;
713
713
  return vec4f( p, 1.0f / S );
714
714
  }
715
- `);jt();var lp=vt(`shader`),up=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),lp.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode;oa(e.uniforms.get(`enableAlphaShadows`));let c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d=e.goboMaps?(0,n.texture)(e.goboMaps):u();$f(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();rp(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},dp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new fp;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new fp;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},fp=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},pp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}},mp=1073741824,hp=1073741824,gp=15,_p=16,vp=2147483648,yp=(e,t)=>~(e<<4|t)>>>0,bp=e=>e>=vp,xp=e=>~e>>>0>>>4,Sp=e=>~e&15;function Cp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/_p,r=e=>{let n=e*_p;return t[n+3]===mp&&t[n+1]>0&&t[n+1]<=gp},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*_p;t[n+3]>=hp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*_p),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*_p,s=n*_p;c.set(e.subarray(o,o+_p),s),!(t[o+3]>=hp)&&(l[s+3]=wp(t,t[o+3],r,i),l[s+7]=wp(t,t[o+7],r,i))}return c}function wp(e,t,n,r){let i=t*_p;return n(t)?yp(e[i],e[i+1]):r[t]}var Tp=(e,t,n)=>e>=vp?yp(xp(e)+n,Sp(e)):e+t;function Ep(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=_p){if(e[a+3]===mp){e[a]+=n;continue}e[a+3]=Tp(e[a+3],t,n),e[a+7]=Tp(e[a+7],t,n)}}jt();var Dp=vt(`bvh`),Op=1073741824,kp=1073741826,Ap=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),jp=1073741824;function Mp(e,t){if(e>=jp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${jp}`);return e}var Np=null;function Pp(e){Np=e}var Fp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Ip=Fp.FLOATS_PER_TRIANGLE,Lp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Rp=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},zp=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Lp(this.triangles),n=Fp.POSITION_A_OFFSET,r=Fp.POSITION_B_OFFSET,i=Fp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Ip,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Ip*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Np&&ri()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;Dp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Ip*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Np())}catch(i){Dp.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?Cp(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Ip*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new dp(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){Dp.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new pp(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){Dp.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Ip);for(let e=0;e<a;e++){let t=this.indices[e]*Ip,n=e*Ip;f.set(d.subarray(t,t+Ip),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return Dp.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Rp;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Rp;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Mp(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Ap(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=Op}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Mp(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Ap(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=kp,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Op}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;Mp(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Ap(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<Op&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Bp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},Vp=Bp.FLOATS_PER_TRIANGLE,Hp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Up=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Wp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):Up(e)}},Gp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Kp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,qp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*Xp,Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Hp(e),u:t?e:Up(e)}};function Yp(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var Xp=16,Zp=1073741824,Qp=1073741825,$p=1e-12;function em(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=$p*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,ee=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}function tm(e,t,n,r,i){let a=Bp.POSITION_A_OFFSET,o=Bp.POSITION_B_OFFSET,s=Bp.POSITION_C_OFFSET,c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let r=0;r<n;r++){let n=t+r,i=e.chunked?e.f.chunkFor(n):e.f,m=e.chunked?e.chunked.baseOf(n):n*Vp;c=Math.min(c,i[m+a],i[m+o],i[m+s]),l=Math.min(l,i[m+a+1],i[m+o+1],i[m+s+1]),u=Math.min(u,i[m+a+2],i[m+o+2],i[m+s+2]),d=Math.max(d,i[m+a],i[m+o],i[m+s]),f=Math.max(f,i[m+a+1],i[m+o+1],i[m+s+1]),p=Math.max(p,i[m+a+2],i[m+o+2],i[m+s+2])}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var nm=new Float32Array(12);function rm(e,t,n,r,i){let a=Gp(e,t),o=Kp(e,t),s=qp(e,t),c=(t-i)*6,l=o[s+3];if(l===Zp){tm(n,o[s],o[s+1],r,c);return}if(l===Qp){em(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;bp(l)&&(tm(n,xp(l),Sp(l),nm,0),d=nm,f=0);let p=r,m=(u-i)*6;bp(u)&&(tm(n,xp(u),Sp(u),nm,6),p=nm,m=6),a[s]=d[f],a[s+1]=d[f+1],a[s+2]=d[f+2],a[s+4]=d[f+3],a[s+5]=d[f+4],a[s+6]=d[f+5],a[s+8]=p[m],a[s+9]=p[m+1],a[s+10]=p[m+2],a[s+12]=p[m+3],a[s+13]=p[m+4],a[s+14]=p[m+5];for(let e=0;e<3;e++)r[c+e]=Math.min(d[f+e],p[m+e]),r[c+3+e]=Math.max(d[f+3+e],p[m+3+e])}var im=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length,i=Jp(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*Vp,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+Bp.POSITION_A_OFFSET]=l,a[s+Bp.POSITION_A_OFFSET+1]=u,a[s+Bp.POSITION_A_OFFSET+2]=d,a[s+Bp.POSITION_B_OFFSET]=f,a[s+Bp.POSITION_B_OFFSET+1]=p,a[s+Bp.POSITION_B_OFFSET+2]=m,a[s+Bp.POSITION_C_OFFSET]=h,a[s+Bp.POSITION_C_OFFSET+1]=g,a[s+Bp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=Yp(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Bp.NORMAL_A_PACKED_OFFSET]=w,o[s+Bp.NORMAL_B_PACKED_OFFSET]=w,o[s+Bp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Jp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Wp(e);for(let e=n+r-1;e>=n;e--)rm(a,e,i,this._bounds,n)}refit(e,t,n){let r=Jp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Wp(e);for(let e=n-1;e>=0;e--)rm(i,e,r,this._bounds,0)}},am="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=1073741824,S=(e,t)=>~(e<<4|t)>>>0;function C(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===1073741824&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=x||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=x)&&(l[s+3]=w(t,t[o+3],r,i),l[s+7]=w(t,t[o+7],r,i))}return c}function w(e,t,n,r){let i=t*16;return n(t)?S(e[i],e[i+1]):r[t]}const T=y(`bvh`),E=1073741824,D=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),O=1073741824;function k(e,t){if(e>=O)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${O}`);return e}const A={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},j=A.FLOATS_PER_TRIANGLE,M=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var N=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},P=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=M(this.triangles),n=A.POSITION_A_OFFSET,r=A.POSITION_B_OFFSET,i=A.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*j,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(j*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?C(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(j*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){T.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){T.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*j);for(let e=0;e<s;e++){let t=this.indices[e]*j,n=e*j;m.set(p.subarray(t,t+j),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return T.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new N;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new N;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=D(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=E}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=D(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=E}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;k(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=D(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<E&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const F=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?I(t):n===`assemble`?L(t):R(t)};function I(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new P;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;F.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){F.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:l}=e;try{let e=performance.now(),u=new P().assembleParallelBVH(t,n,r,i),d=l?C(u):u,f=new Uint32Array(o);if(s){let e=new Uint32Array(a),t=new Uint32Array(s);for(let n=0;n<c;n++){let r=f[n]*20,i=n*20;t.set(e.subarray(r,r+20),i)}}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[f[e]]=e;let m=performance.now()-e;F.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){F.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function R(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,foldLeaves:p}=e,m=new P;l!==void 0&&(m.maxLeafSize=l),u!==void 0&&(m.numBins=u),d!==void 0&&(m.maxBins=d),f!==void 0&&(m.minBins=f);try{o&&m.setTreeletConfig(o),s&&m.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=m.buildSync(l,i,e,u),f=performance.now(),h=m.flattenBVH(d),g=p?C(h):h,v=performance.now()-f;F.debug(`flatten ${_.ms(v)} (${_.mb(g.byteLength)})`);let y=m.originalToBvhMap||null;if(c){let e=[g.buffer];y&&e.push(y.buffer),self.postMessage({bvhData:g,originalToBvh:y,triangleCount:l.length/20,treeletStats:m.splitStats},e)}else{let e=m.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];y&&n.push(y.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:y,triangleCount:t,treeletStats:m.splitStats},n)}}catch(e){F.error(`build failed:`,e),self.postMessage({error:e.message})}}",om=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,am],{type:`text/javascript;charset=utf-8`});function sm(e){let t;try{if(t=om&&(self.URL||self.webkitURL).createObjectURL(om),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(am),{type:`module`,name:e?.name})}}var cm="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=1073741824,x=(e,t)=>~(e<<4|t)>>>0;function S(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===1073741824&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=b||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=b)&&(l[s+3]=C(t,t[o+3],r,i),l[s+7]=C(t,t[o+7],r,i))}return c}function C(e,t,n,r){let i=t*16;return n(t)?x(e[i],e[i+1]):r[t]}const w=y(`bvh`),T=1073741824,E=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),D=1073741824;function O(e,t){if(e>=D)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${D}`);return e}const k={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},A=k.FLOATS_PER_TRIANGLE,j=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var M=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},N=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=j(this.triangles),n=k.POSITION_A_OFFSET,r=k.POSITION_B_OFFSET,i=k.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*A,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(A*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?S(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(A*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){w.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){w.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*A);for(let e=0;e<s;e++){let t=this.indices[e]*A,n=e*A;m.set(p.subarray(t,t+A),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return w.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new M;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new M;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=E(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=T}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=E(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=T}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;O(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=E(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<T&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new N;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",lm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,cm],{type:`text/javascript;charset=utf-8`});function um(e){let t;try{if(t=lm&&(self.URL||self.webkitURL).createObjectURL(lm),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(cm),{type:`module`,name:e?.name})}}jt(),Pp(()=>ii(sm));var dm=vt(`bvh`),fm=20,pm=5e4,mm=8;function hm(e,t,n,r){let i=e.byteLength/(fm*4),a=Math.min(ni(),mm),o=Math.ceil(Math.log2(a*2.5+1));return dm.debug(`parallel build ${J.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let l=e.buffer instanceof SharedArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength,u=l?e.buffer:new SharedArrayBuffer(e.byteLength);l||new Uint32Array(u).set(e),e=null;let d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*3*4),p=new SharedArrayBuffer(i*3*4),m=new SharedArrayBuffer(i*4),h=new SharedArrayBuffer(i*4),g=ii(sm),_=null,v=[g],y={id:null},b=!1,x=()=>{y.id&&=(clearTimeout(y.id),null);for(let e of v)try{e.terminate()}catch{}},S=e=>{if(!b){b=!0,dm.warn(`parallel build failed (${e}), falling back to single worker`),x();try{let e=new ArrayBuffer(u.byteLength);new Uint32Array(e).set(new Uint32Array(u)),s(_m(new Uint32Array(e),t,n,r))}catch(e){c(e)}}};g.onerror=e=>{S(`coordinator error: ${e.message}`)},g.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){S(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){_=t.splitStats,gm(t,a,u,d,f,p,m,null,i,n,g,v,x,S,s,y,r).catch(e=>S(e.message));return}if(t.type===`assembleResult`){b=!0,x(),s({bvhData:t.bvhData,bvhRoot:!0,order:new Uint32Array(m),triangles:new Uint32Array(u),originalToBvh:t.originalToBvh||null,splitStats:_||{}});return}},n&&n(0),g.postMessage({type:`buildPhase1`,sharedTriangleData:u,sharedCentroids:d,sharedBMin:f,sharedBMax:p,sharedIndices:m,sharedMortonCodes:h,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{dm.warn(`parallel build setup failed:`,e),c(e)})})}async function gm(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){dm.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},[_.buffer]);return}dm.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=ii(um);d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function _m(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ii(sm),s=e.byteLength/(fm*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*fm*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{dm.warn(`single worker fallback failed:`,e),a(e)})})}function vm(e){return ri()&&typeof SharedArrayBuffer<`u`&&e>=pm}var ym=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function bm(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function xm(e,t,n){let r=bm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(ym),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function Sm(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function Cm(e){for(let t=0;t<16;t++)if(e[t]!==ym[t])return!1;return!0}function wm(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function Tm(e,t){for(let n=0;n<16;n++)if(e[t+n]!==ym[n])return!1;return!0}var Em=class e{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(ym,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(bm(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return xm(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}wm(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}wm(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e,{owners:t=!0}={}){for(let n=0;t&&n<this.templateCount;n++){if(this.tplOwner[n]<0)continue;let t=this.blasData.get(n);t&&this._readRootAABB(Array.isArray(t)?t[0]:t,n,e,this.tplObjectAABB,n*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(t,n,r,i,a){e.rootAABB(t,r,this.tplTriOffset[n],this.tplTriCount[n],i,a)}static rootAABB(e,t,n,r,i,a){if(!e||Je(e)[3]===Ke.TRIANGLE_LEAF){Dm(t,n,r,i,a);return}i[a]=Math.min(e[0],e[8]),i[a+1]=Math.min(e[1],e[9]),i[a+2]=Math.min(e[2],e[10]),i[a+3]=Math.max(e[4],e[12]),i[a+4]=Math.max(e[5],e[13]),i[a+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){Dm(t,this.tplTriOffset[e],this.tplTriCount[e],n,r)}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,Ye(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function Dm(e,t,n,r,i){let a=W.FLOATS_PER_TRIANGLE,o=e&&e.chunks?e.viewAs(Float32Array):null,s=o?null:e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let e=0;e<n;e++){let n=t+e,r=o?o.chunkFor(n):s,i=o?o.baseOf(n):n*a;for(let e=0;e<=8;e+=4){let t=r[i+e],n=r[i+e+1],a=r[i+e+2];t<c&&(c=t),n<l&&(l=n),a<u&&(u=a),t>d&&(d=t),n>f&&(f=n),a>p&&(p=a)}}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var Om=16,km=32,Am=e=>e<km?e:km,jm=8,Mm=64,Nm=new Float64Array(16),Pm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(km*3),this._binBounds=new Float64Array(km*6*3),this._binSuffix=new Float64Array(km),this._binSuffixCount=new Int32Array(km),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};Ye(r,`TLAS node count`);let i=r*Om;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=Je(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(Mm);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*Om;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=Ke.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*Om;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=Je(t);for(let r=0;r<n;r++){let n=r*Om;if(l[n+3]!==Ke.BLAS_POINTER_LEAF)continue;let u=l[n+1]&Ge;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=Nm;xm(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(Tm(r,i*16)?We:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=jm)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=Am(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Fm=W.FLOATS_PER_TRIANGLE*4,Im=64,Lm=.9,Rm=64,zm=4,Bm=7040*1024*1024,Vm=9216*1024*1024;function Hm(e){if(e>0)return{gb:e,assumed:!1};let t=typeof navigator<`u`?navigator.deviceMemory:void 0;return t>0?{gb:t,assumed:!1}:{gb:4,assumed:!0}}var Um=1.15,Wm=12*1024*1024*1024;function Gm({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Fm,bvh:Math.ceil(e*Lm)*Im,geometry:n,placements:t*Rm,orderMaps:e*zm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Km(e,{chunkBytes:t=hn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Wm),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var qm=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}},Jm="let e,t;const n={MAX_BYTES_PER_TEXTURE:256*1024*1024,MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};self.onmessage=async function(t){let{textures:n,maxTextureSize:a,method:o=`direct-transfer`}=t.data;try{e||r(a);let t=await i(n,a,o);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function r(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function i(e,t,r){let i=h(e,t),o=i.maxWidth*i.maxHeight*e.length*4;if(o>n.MAX_BYTES_PER_TEXTURE)return console.log(`Large texture array detected (${(o/1024/1024).toFixed(2)}MB), using chunked processing`),await a(e,t,r);switch(r){case`direct-transfer`:return await d(e,t);case`offscreen-optimized`:return await p(e,t);case`imageBitmap-batch`:return await m(e,t);default:return await d(e,t)}}async function a(e,t,n){let{maxWidth:r,maxHeight:i}=h(e,t),a=e.length,c=o(r,i,a),l=Math.ceil(a/c);console.log(`Processing ${a} textures in ${l} chunks of up to ${c} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*c*4/1024/1024).toFixed(2)}MB`);let u;try{u=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await f(e,g(e,t),n)}let d=r*i*c*4,p;try{p=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await f(e,g(e,t),n)}for(let t=0;t<l;t++){let n=t*c,o=Math.min(n+c,a),l=o-n,d=await s(e.slice(n,o),r,i,p.subarray(0,r*i*l*4)),f=n*r*i*4,m=l*r*i*4;u.set(new Uint8Array(d.data.slice(0,m)),f),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:u.buffer,width:r,height:i,depth:a}}function o(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function s(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await c(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function c(e,n,r,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function l(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await l(e,i,a)}return await s(e,t,n,r)}async function u(e,t,n,r,i){await c(e,n,r*i*4*t,r,i)}async function d(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await u(t,e,c,i,o)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function f(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await l(e,r,i,n)}async function p(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}t.clearRect(0,0,i,o),t.drawImage(n,0,0);let a=t.getImageData(0,0,i,o),s=i*o*4*e;c.set(a.data,s),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function m(n,r){let{maxWidth:i,maxHeight:s}=h(n,r),c=n.length,l;try{l=new Uint8Array(i*s*c*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`imageBitmap-batch`)}let u=Math.min(o(i,s,n.length),n.length);for(let r=0;r<n.length;r+=u){let a=Math.min(r+u,n.length),o=[];for(let e=r;e<a;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}o.push(r.then(t=>({bitmap:t,index:e})))}let c=await Promise.all(o);e.width=i,e.height=s,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of c){t.clearRect(0,0,i,s),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,s),a=i*s*4*n;l.set(r.data,a),e.close()}}return{data:l.buffer,width:i,height:s,depth:c}}function h(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function g(e,t){let n=h(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",Ym=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Jm],{type:`text/javascript;charset=utf-8`});function Xm(e){let t;try{if(t=Ym&&(self.URL||self.webkitURL).createObjectURL(Ym),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Jm),{type:`module`,name:e?.name})}}var Zm=`function e({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}self.onmessage=function(t){let{layers:n,width:r,height:i}=t.data;try{let t=r*i*4,a=new Uint8Array(t*n.length);n.forEach((n,o)=>e(n,a,o*t,r,i)),self.postMessage({data:a},[a.buffer])}catch(e){self.postMessage({error:e.message})}};`,Qm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Zm],{type:`text/javascript;charset=utf-8`});function $m(e){let t;try{if(t=Qm&&(self.URL||self.webkitURL).createObjectURL(Qm),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Zm),{type:`module`,name:e?.name})}}function eh({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}Dl();var th=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),nh=new Map;function rh(){nh.clear();for(let e of Tl.values())nh.set(e.id,th(e.cpu))}rh(),cl(rh);function ih(e){return ll(e)?.outputEncoded===!0}var ah=1/2.2;function oh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function sh(e,t){let n=ll(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var ch=.2126,lh=.7152,uh=.0722;function dh(e,t){if(t===1)return;let n=e[0]*ch+e[1]*lh+e[2]*uh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function fh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=nh.get(n)??nh.get(r.NoToneMapping),s=sh(t,n),c=ih(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,dh(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=oh(u[0])*255+.5,l[t+1]=oh(u[1])*255+.5,l[t+2]=oh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var ph=vt(`textures`),mh=8*2**20,hh={busy:0,waiting:[]};async function gh(){return hh.busy<Math.max(1,ni()-1)?hh.busy++:await new Promise(e=>hh.waiting.push(e)),()=>{let e=hh.waiting.shift();e?e():hh.busy--}}var _h={toSRGB:null,toLinear:null};function vh(e){if(!_h[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?oh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}_h[e]=t}return _h[e]}var yh=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Xe.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},bh=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||dt.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*dt.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Xe.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},xh=class{constructor(e=Xe.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Sh=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Xe.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Xe.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new yh,this.bufferPool=new bh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new xh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof pn)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||Xe.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Xe.MIN_TEXTURE_WIDTH,Math.min(t,Xe.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new xh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ni()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Eu();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){ph.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,ph.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=vh(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?ph.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):ph.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Eu()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof pn)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>dt.MAX_TEXTURE_MEMORY?{method:`main-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=new Xm;try{let n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(r)}finally{t.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=ri()&&i*t.length>=mh?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>eh(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await gh(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=ii($m),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%dt.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=G.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)dn(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Xe.VEC4_PER_BVH_NODE*Xe.FLOATS_PER_VEC4;Ye(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=Je(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=Ke.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new xh;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Qe(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Ch(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:Ch(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function Ch(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var wh=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Eh(E,Th(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Eh(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Th(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Eh(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}jt();var Dh=Object.freeze({r:0,g:0,b:0});function Oh(e){if(!e)return Dh;if(!Fr())return e;let t=[e.r,e.g,e.b];return Lr(t),{r:t[0],g:t[1],b:t[2]}}var kh=vt(`emissive`),Ah=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=W.FLOATS_PER_TRIANGLE,a=W.MATERIAL_FLAGS_OFFSET,o=W.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&Le,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Oh(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let ne=g.side===2,z=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:te,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:z,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&kh.debug(`${J.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=W.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,kh.debug(`emissive texture ${J.px(t,n)} · ${J.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return kh.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Oh(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new wh().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,kh.debug(`rebuilt sorted emissive data · ${J.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};jt();var jh=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=vt(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Mh=1<<20,Nh=1<<21,Ph=()=>new Promise(e=>setTimeout(e,0)),Fh=[0,1,2,4,5,6,8,9,10];function Ih(e,t,n,r=Fh){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function Lh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Ih(e,i,a)),r+=a,r>=Nh&&(r=0,await Ph());return n}async function Rh(e,t){let n=await e?.area(Wn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function zh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(Wn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,Mh),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=Mh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+Mh*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function Bh(e,t,n,r){for(let i=0;i<r;i+=Mh){let a=Math.min(Mh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Vh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Hh=16,Uh=W.POSITION_A_OFFSET,Wh=W.POSITION_B_OFFSET,Gh=W.POSITION_C_OFFSET;async function Kh(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+Uh]+o[n+Wh]+o[n+Gh],c[r]=o[n+Uh+1]+o[n+Wh+1]+o[n+Gh+1],l[r]=o[n+Uh+2]+o[n+Wh+2]+o[n+Gh+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return Jh(u,o,qh(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Yh(e,t,n,u,i),{order:u,pieces:d,tree:p}}function qh(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function Jh(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function Yh(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function Xh(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Hh;let s=new Float32Array(i*Hh),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];Ep(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*Hh;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var Zh=`9.3.1`,Qh=1e4,$h=15e5;function eg(e,t,n=Qh){return e>=n&&t/$h<e/3}var tg="const e=e=>e>=2147483648,t=e=>~e>>>0>>>4,n=e=>~e&15,r={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},i=r.FLOATS_PER_TRIANGLE,a=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),o=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),s=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):o(e)}},c=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,l=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,u=(e,t)=>e.chunked?e.chunked.baseOf(t):t*p,d=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):a(e),u:t?e:o(e)}};function f(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const p=16;function m(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function h(e,t,n,a,o){let s=r.POSITION_A_OFFSET,c=r.POSITION_B_OFFSET,l=r.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let r=0;r<n;r++){let n=t+r,a=e.chunked?e.f.chunkFor(n):e.f,o=e.chunked?e.chunked.baseOf(n):n*i;u=Math.min(u,a[o+s],a[o+c],a[o+l]),d=Math.min(d,a[o+s+1],a[o+c+1],a[o+l+1]),f=Math.min(f,a[o+s+2],a[o+c+2],a[o+l+2]),p=Math.max(p,a[o+s],a[o+c],a[o+l]),m=Math.max(m,a[o+s+1],a[o+c+1],a[o+l+1]),h=Math.max(h,a[o+s+2],a[o+c+2],a[o+l+2])}a[o]=u,a[o+1]=d,a[o+2]=f,a[o+3]=p,a[o+4]=m,a[o+5]=h}const g=new Float32Array(12);function _(r,i,a,o,s){let d=c(r,i),f=l(r,i),p=u(r,i),_=(i-s)*6,v=f[p+3];if(v===1073741824){h(a,f[p],f[p+1],o,_);return}if(v===1073741825){m(d,p,o,(f[p]-s)*6,o,_);return}let y=f[p+7],b=o,x=(v-s)*6;e(v)&&(h(a,t(v),n(v),g,0),b=g,x=0);let S=o,C=(y-s)*6;e(y)&&(h(a,t(y),n(y),g,6),S=g,C=6),d[p]=b[x],d[p+1]=b[x+1],d[p+2]=b[x+2],d[p+4]=b[x+3],d[p+5]=b[x+4],d[p+6]=b[x+5],d[p+8]=S[C],d[p+9]=S[C+1],d[p+10]=S[C+2],d[p+12]=S[C+3],d[p+13]=S[C+4],d[p+14]=S[C+5];for(let e=0;e<3;e++)o[_+e]=Math.min(b[x+e],S[C+e]),o[_+3+e]=Math.max(b[x+3+e],S[C+3+e])}var v=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let a=n.length,o=d(e);for(let e=0;e<a;e++){let a=n[e],s=o.chunked?o.f.chunkFor(e):o.f,c=o.chunked?o.u.chunkFor(e):o.u,l=o.chunked?o.chunked.baseOf(e):e*i,u=a*9,d=t[u],p=t[u+1],m=t[u+2],h=t[u+3],g=t[u+4],_=t[u+5],v=t[u+6],y=t[u+7],b=t[u+8];s[l+r.POSITION_A_OFFSET]=d,s[l+r.POSITION_A_OFFSET+1]=p,s[l+r.POSITION_A_OFFSET+2]=m,s[l+r.POSITION_B_OFFSET]=h,s[l+r.POSITION_B_OFFSET+1]=g,s[l+r.POSITION_B_OFFSET+2]=_,s[l+r.POSITION_C_OFFSET]=v,s[l+r.POSITION_C_OFFSET+1]=y,s[l+r.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-p,C=_-m,w=v-d,T=y-p,E=b-m,D=f(S*E-C*T,C*w-x*E,x*T-S*w);c[l+r.NORMAL_A_PACKED_OFFSET]=D,c[l+r.NORMAL_B_PACKED_OFFSET]=D,c[l+r.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=d(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=s(e);for(let e=n+r-1;e>=n;e--)_(a,e,i,this._bounds,n)}refit(e,t,n){let r=d(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=s(e);for(let e=n-1;e>=0;e--)_(i,e,r,this._bounds,0)}};const y=64*1024*1024;function b(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var x=class e{constructor(e,t,n,r=y,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(b(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(b(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=y,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=b(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=b(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=b(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const S=new v;let C=null,w=null,T=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){C=x.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),w=x.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),T=C.recordCount;return}if(t===`refit`)try{let e=performance.now();S.refit(C,w,T),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-e})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",ng=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,tg],{type:`text/javascript;charset=utf-8`});function rg(e){let t;try{if(t=ng&&(self.URL||self.webkitURL).createObjectURL(ng),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(tg),{type:`module`,name:e?.name})}}var ig="const e=Math.PI/180;function t(e){let t=2*Math.PI*(e-1)/365;return .006918-.399912*Math.cos(t)+.070257*Math.sin(t)-.006758*Math.cos(2*t)+907e-6*Math.sin(2*t)-.002697*Math.cos(3*t)+.00148*Math.sin(3*t)}function n({hours:n,dayOfYear:r,latitude:i}){let a=t(r),o=(n-12)*15*e,s=i*e,c=Math.sin(s)*Math.sin(a)+Math.cos(s)*Math.cos(a)*Math.cos(o),l=Math.asin(Math.min(1,Math.max(-1,c)))/e;return{azimuth:(Math.atan2(Math.sin(o),Math.cos(o)*Math.sin(s)-Math.tan(a)*Math.cos(s))/e+540)%360,elevation:l}}const r=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,i=Object.freeze({time:10,month:3,latitude:40}),a=n({hours:i.time,dayOfYear:r(i.month),latitude:i.latitude}),o=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})}),s={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:o.viewer.toneMapping,exposure:1,saturation:o.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:o.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-a.azimuth,skySunElevation:a.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:o.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};Object.freeze({perspective:0,equirectangular:1,orthographic:2}),s.fov,s.focusDistance,s.aperture,s.focalLength,180-a.azimuth,a.elevation,c({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function c(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const l={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function u(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function d(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),s.maxSamples,s.bounces,s.renderMode,s.enableAlphaShadows,s.maxSubsurfaceSteps;const f=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function p(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function m(e,t,n){let r=p(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(f),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function h(e,t){for(let n=0;n<16;n++)if(e[t+n]!==f[n])return!1;return!0}const g=e=>e<32?e:32,_=new Float64Array(16);var v=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};d(r,`TLAS node count`);let i=r*16;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=u(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(64);let c=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,s,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let e=f*16;o[e]=0,o[e+1]=s[p],a[e+2]=0,o[e+3]=l.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),l=f*16;a[l]=h[0],a[l+1]=h[1],a[l+2]=h[2],o[l+3]=r,a[l+4]=h[3],a[l+5]=h[4],a[l+6]=h[5],o[l+7]=i,a[l+8]=h[6],a[l+9]=h[7],a[l+10]=h[8],a[l+11]=0,a[l+12]=h[9],a[l+13]=h[10],a[l+14]=h[11],a[l+15]=0;let u=n<=m-e,d=u?0:6,S=u?6:0;c=this._push(c,u?i:r,u?e:p,u?m:e,h,S),f=u?r:i,u?m=e:p=e,g=h[d],_=h[d+1],v=h[d+2],y=h[d+3],b=h[d+4],x=h[d+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,d=u(t);for(let r=0;r<n;r++){let n=r*16;if(d[n+3]!==l.BLAS_POINTER_LEAF)continue;let u=d[n+1]&1073741823;d[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,d,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=_;m(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(h(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=m-d,v[1]=h-f,v[2]=_-p,y[0]=d,y[1]=f,y[2]=p;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=g(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=O-1;e>=1;e--){let u=(t+e)*6;w[u]<i&&(i=w[u]),w[u+1]<a&&(a=w[u+1]),w[u+2]<o&&(o=w[u+2]),w[u+3]>s&&(s=w[u+3]),w[u+4]>c&&(c=w[u+4]),w[u+5]>l&&(l=w[u+5]),d+=C[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/u;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const y={silent:0,error:1,warn:2,info:3,debug:4},b=`info`,x=`rayzeeLogLevel`,S=`rayzeeLogNamespaces`,C=`color:#7c8494`,w=`color:inherit`;let T=null,E=null;function D(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function O(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function k(){if(T!==null)return T;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in y?(T=y[e],T):(T=y[D(x)]??y[b],T)}function A(){if(E!==null)return E;let e=globalThis.__RAYZEE_LOG_NS__??D(S);return E=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],E}function j(e,t){if(t<y.debug)return!0;let n=A();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function M(e,t,n){if(e>k()||!j(t,e))return;let r=e===y.error?console.error:e===y.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,C,w,...n.slice(1)):r(`%c${i}`,C,...n)}const N={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${N.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},P={levels:y,setLevel(e){return e in y?(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e],O(x,e===b?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(y).join(`, `)}`),this.getLevel())},getLevel(){let e=k();return Object.keys(y).find(t=>y[t]===e)},isEnabled(e){return(y[e]??y.debug)<=k()},only(...e){let t=e.flat().filter(Boolean);return E=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),O(S,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return T=null,E=null,this.getLevel()}};function F(e){return{namespace:e,error:(...t)=>M(y.error,e,t),warn:(...t)=>M(y.warn,e,t),info:(...t)=>M(y.info,e,t),debug:(...t)=>M(y.debug,e,t),isEnabled:e=>P.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){M(y.info,e,[t]),r.forEach(t=>M(y.debug,e,[t]));return}y.info>k()||((k()>=y.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,C,w),r.forEach(e=>console.log(e)),console.groupEnd())}}}function I(e){e&&e in y&&(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e])}const L=F(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;I(r);try{let e=performance.now(),{data:r,nodeCount:i}=new v().buildStructure(new Float64Array(t),n);L.debug(`TLAS ${N.n(i)} nodes in ${N.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){L.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",ag=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,ig],{type:`text/javascript;charset=utf-8`});function og(e){let t;try{if(t=ag&&(self.URL||self.webkitURL).createObjectURL(ag),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(ig),{type:`module`,name:e?.name})}}jt(),Ys();var sg=5e4,cg=2e5,lg=2e6,ug=1<<19,dg=4e7,fg=1.5*1024**3,pg=256*1024*1024,mg=vt(`scene`),hg=e=>Array.isArray(e)?e:[e],gg=e=>hg(e).reduce((e,t)=>e+t.byteLength,0),_g=64*1024*1024;async function vg(e,t,n){for(let r of hg(n))await e.writeAt(t,r),t+=r.byteLength}function yg(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var bg=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Xe.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ni(),6),maxSceneBytes:Vm,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:Qh,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new qm,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new jr({issues:this.config.issues}),this.bvhBuilder=new zp,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new Sh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ah,this.tlasBuilder=new Pm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?mg.debug(e):mg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Gm(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=fg+yg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Bm,maxBytes:t,fits:r.total<=Bm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(mg.debug(J.list([`memory preflight: ${J.mb(r.total)} estimated`,`triangles ${J.mb(r.triangles)} · bvh ${J.mb(r.bvh)} · geometry ${J.mb(r.geometry)}`,`${J.n(n.triangles)} tris · ${J.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${J.mb(r.total)} of CPU memory, past the ${J.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${J.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${J.mb(r.total)} of CPU memory, above the ${J.mb(Bm)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Bm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Km(Math.ceil(t*Um),{shared:gn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${J.mb(t)} but only ${J.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?gg(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${J.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;mg.debug(J.list([`memory: peak live ${J.mb(t)}`,`allocated ${J.mb(e)}`,i?`predicted ${J.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,vn(e=>this.memory.alloc(e));let r=new jh(e.name??``,{namespace:`scene`});try{this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(W.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>dg,this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=Tr(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>mg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,mg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),vn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw mg.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry and building BVHs...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=bn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await ur.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await ur.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await gr.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);Em.rootAABB(hg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=gg(r),f.blasAt.set(e,a),n.nodeCount=gg(r)/64,n.bvhData=null,this._queueSpill(f,()=>vg(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`)},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>pg&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>fg&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),mg.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=Ye(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${qe.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new Em,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),v=s?null:await this._restoreBLASes(_,Pm.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,T.treeletsImproved+=i.treeletsImproved??0,T.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??gg(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(Pm.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(bn.lazy(O,16,Float32Array,void 0,gn));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await Bh(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of hg(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;mg.debug(J.list([`${J.n(D.setCount)} BLASes + TLAS`,`${J.n(this.bvh.recordCount)} nodes`,`SAH ${J.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,T.treeletsProcessed?`treelets ${T.treeletsImproved}/${T.treeletsProcessed} improved`:null,J.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw mg.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,treeletOptimization:{enabled:this.config.enableTreeletOptimization!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:bt()}}_isLargeMesh(e){return e.count>=cg&&vm(e.count)}async _buildLargeBLAS(e,t){if(e.count>lg)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await hm(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await Kh(n,e.start,e.count,ug,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ni(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),Em.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...Xh(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${Zh}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Fu(Ks().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Rh(r,this._blasKey);if(!i)return null;let a=e=>(mg.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await Lh(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await Vh(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},mg.debug(`restored ${J.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=Fu(Ks().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await Lh(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await zh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&mg.debug(`stored ${J.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await ur.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await ur.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(hg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=gg(a),e.blasAt.set(t,o),r.nodeCount=gg(a)/64,r.bvhData=null,this._queueSpill(e,()=>vg(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=W.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=_g)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(_g,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await ur.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o);let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);Ep(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count,o=i<=500?{...e.treeletOptimization,enabled:!1}:e.treeletOptimization;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:o,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.treeletStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=ii(sm);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw mg.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Xe.MATERIAL_BUCKET_COUNT,n=Xe.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps],o=it(r(i),e,t),s=it(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=at(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return ot(o,c);if(t[o].length>=n)return mg.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=ot(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){mg.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw mg.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=bn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=ii(rg),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;let t=n(e);if(t&&(this._updateMeshTrianglePositions(e,t),r)){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}}return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new im;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16),i=0;for(let t of e){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?this._ownInstanceMatrices(e):null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;n.isSet[t]&&(s?(Sm(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(Sm(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t),i++)}}return this._refitTLAS(),{refitTimeMs:performance.now()-t,placements:i}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Pm.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=W.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):mg.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(mg.error(`failed to get BVH data`),!1)):(mg.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await ur.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await ur.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.tlasNodeCount??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return mg.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Tr(e),mg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&mg.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}async _buildTLAS(e){let t=e.count;if(t>=sg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Pm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,mg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ii(og);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:bt()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof bn?e:bn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=W.FLOATS_PER_TRIANGLE,n=e?e instanceof bn?e:bn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=W.POSITION_A_OFFSET,r=W.POSITION_B_OFFSET,i=W.POSITION_C_OFFSET,a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=Cm(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=Be(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Cm(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=Be(f,p,m)}}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6));let t=this.instanceTable;for(let n=e-1;n>=0;n--){let e=this.bvhIndexChunks.chunkFor(n),r=this.bvh.chunkFor(n),i=this.bvh.baseOf(n),a=e[i+3];if(a===Ke.BLAS_POINTER_LEAF){let r=e[i+1]&Ge;r<t.count&&t.writeWorldAABB(r,this._tlasBounds,n*6)}else if(a<Ke.TRIANGLE_LEAF){let t=a,o=e[i+7],s=t*6,c=o*6,l=this._tlasBounds;r[i]=l[s],r[i+1]=l[s+1],r[i+2]=l[s+2],r[i+4]=l[s+3],r[i+5]=l[s+4],r[i+6]=l[s+5],r[i+8]=l[c],r[i+9]=l[c+1],r[i+10]=l[c+2],r[i+12]=l[c+3],r[i+13]=l[c+4],r[i+14]=l[c+5];let u=n*6;l[u]=Math.min(l[s],l[c]),l[u+1]=Math.min(l[s+1],l[c+1]),l[u+2]=Math.min(l[s+2],l[c+2]),l[u+3]=Math.max(l[s+3],l[c+3]),l[u+4]=Math.max(l[s+4],l[c+4]),l[u+5]=Math.max(l[s+5],l[c+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){mg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{mg.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,ii(sm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){mg.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},xg=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],Sg=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],Cg=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function wg(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=xg[i],o=Sg[i],s=Cg[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}var Tg=1/(4*Math.PI);function Eg(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=wg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Lr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Dg=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=Eg(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=Eg(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=Eg(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Tg,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=Eg(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*Tg,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}};jt();var Og=1<<18,kg=vt(`pathtracer`),Ag=100,jg=4,Mg=class extends P{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:N.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new bg,this.lightSerializer=new Dg,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ft(0,0),this.uniforms=new nn(a,o),this._defineUniformGetters(),this.materialData=new Yr(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this._triangleFlat,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleShadeAttr&&this._uploadTriangles(0,this._triangleRecordCount,{geo:!1})},this.environment=new Ju(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new up,this._initRenderingState(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.tracedFrames=0,this.resetCount=0,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._bitTrailOffset=0,this._bitTrailLength=0,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new F(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/12)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/16)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/20)):this.numSpotLights.value=0}reset(){this.resetCount++,this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,(this._pinSeedToFrame||this._lockstep)&&(this._seedTick=0)}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Ag}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,t){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount:Math.ceil(i.length/W.FLOATS_PER_TRIANGLE),o=r?._gpuUpload?.triangles?r._gpuUpload:null,{geo:s,shade:c}=o??this._allocateTriangleBuffers(a);this.triangleStorageNode?(this.triangleStorageNode.geo.value=s,this.triangleStorageNode.geo.bufferCount=s.count,this.triangleStorageNode.shade.value=c,this.triangleStorageNode.shade.bufferCount=c.count):this.triangleStorageNode={geo:(0,n.storage)(s,`uvec4`,s.count).toReadOnly(),shade:(0,n.storage)(c,`uvec4`,c.count).toReadOnly()},this.triangleGeoAttr=s,this.triangleShadeAttr=c,this._triangleRecords=r,this._triangleFlat=i,this._triangleRecordCount=a,this.triangleCount=t,this._uploadTriangles(0,a,{skipChunks:o?.uploaded}),kg.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}_allocateTriangleBuffers(e){let t=Math.max(1,e);this._assertFitsGPU(t*3*16);let n=S(t*3,4,Uint32Array),r=S(t*2,4,Uint32Array);return this.renderer.backend.createStorageAttribute(n),this.renderer.backend.createStorageAttribute(r),{geo:n,shade:r}}_uploadTriangles(e,t,{geo:n=!0,shade:r=!0,skipChunks:i=null,source:a=null,sourceStart:o=0,geoAttr:s=this.triangleGeoAttr,shadeAttr:c=this.triangleShadeAttr}={}){if(t<=0||!s)return;let l=this.renderer.backend,u=l.get(s).buffer,d=l.get(c).buffer,f=W.FLOATS_PER_TRIANGLE,p=this._triangleRecords,m=a?t:p?p.recordsPerChunk:this._triangleRecordCount,h=Og;this._triangleStaging??={geo:new Uint32Array(h*12),shade:new Uint32Array(h*8)};let g=this._triangleStaging.geo,_=this._triangleStaging.shade;for(let s=e,c=e+t;s<c;){let t=a?0:Math.floor(s/m),v=a?e:t*m,y=Math.min(c,v+m);if(i?.has(t)){s=y;continue}let b=a??(p?p.chunks[t]:this._triangleFlat);if(!b)throw Error(`triangle chunk ${t} is on disk and was never uploaded`);let x=Math.min(h,y-s),S=(a?s-e+o:s-v)*f;for(let e=0,t=0,i=0;e<x;e++,S+=f){if(n)for(let e=0;e<12;e++)g[t++]=b[S+e];if(r)for(let e=12;e<f;e++)_[i++]=b[S+e]}n&&l.device.queue.writeBuffer(u,s*12*4,g,0,x*12),r&&l.device.queue.writeBuffer(d,s*8*4,_,0,x*8),s+=x}}createChunkUploader(e){this._assertFitsGPU(e.recordCount*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT);let t=S(e.recordCount*e.lanesPerRecord/4,4,e.LaneType),n=this.renderer.backend;n.createStorageAttribute(t);let r=n.get(t).buffer,i=e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,a=new Set;return e._gpuUpload={attr:t,uploaded:a},t=>{let o=e.chunks[t];n.device.queue.writeBuffer(r,t*i,o,0,o.length),a.add(t)}}createTriangleChunkUploader(e){let{geo:t,shade:n}=this._allocateTriangleBuffers(e.recordCount),r=new Set;e._gpuUpload={triangles:!0,geo:t,shade:n,uploaded:r};let i=e.recordsPerChunk;return a=>{let o=a*i,s=Math.min(i,e.recordCount-o);this._uploadTriangles(o,s,{source:e.chunks[a],geoAttr:t,shadeAttr:n}),r.add(a)}}_assertFitsGPU(e){let t=this.renderer?.backend?.device?.limits,n=Math.min(t?.maxBufferSize??1/0,t?.maxStorageBufferBindingSize??1/0);if(e>n)throw Error(`the scene needs a ${J.mb(e)} GPU buffer, past the ${J.mb(n)} this GPU allows for one — load fewer triangles`)}_uploadChunked(e,t){let n=t._gpuUpload;if(!n||n.attr!==e){w(this.renderer,e,t.chunks);return}let r=this.renderer.backend.get(e).buffer,i=t.recordsPerChunk*t.lanesPerRecord*t.LaneType.BYTES_PER_ELEMENT;for(let e=0;e<t.chunks.length;e++){if(n.uploaded.has(e))continue;let a=t.chunks[e];if(!a)throw Error(`chunk ${e} is on disk and was never uploaded`);this.renderer.backend.device.queue.writeBuffer(r,e*i,a,0,a.length),n.uploaded.add(e)}}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount*r.lanesPerRecord:i.length,o=a/4;this._assertFitsGPU(a*4);let s=()=>r?r._gpuUpload?.attr??S(o,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=s(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=o):(this.bvhStorageAttr=s(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,o).toReadOnly()),this.bvhStorageAttr.foldedLeaves=e.foldedLeaves===!0,this._bvhRecords=r,r&&this._uploadChunked(this.bvhStorageAttr,r),this.bvhNodeCount=Math.floor(o/jg),kg.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){let e=1/0,t=-1;for(let n of this._dirtyBVHLeaves??[])n<e&&(e=n),n>t&&(t=n);t>=0&&(this.bvhStorageAttr.addUpdateRange(e*16,(t-e+1)*16),this.bvhStorageAttr.version++),this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.clearUpdateRanges(),e.needsUpdate=!0)}updateTriangleData(e){e?.chunks?.length>1?this._triangleRecords=e:e&&(this._triangleFlat=e.chunks?e.chunks[0]:e),this._uploadTriangles(0,this._triangleRecordCount)}updateBVHData(e){if(this._bvhRecords){w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}this._updateStorageBuffer(this.bvhStorageAttr,e?.chunks?e.chunks[0]:e)}updateBufferRanges(e,t){if(this.triangleGeoAttr&&e.length>0){let t=W.FLOATS_PER_TRIANGLE;for(let n of e){let e=Math.floor(n.offset/t);this._uploadTriangles(e,Math.ceil((n.offset+n.count)/t)-e)}}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){kg.error(`triangle data required`);return}if(!this.bvhStorageNode){kg.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e){let t=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=t,this.accumulationEnabled?t?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=de(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=ue(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(){}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this.lightStorageAttr?.array,i=this._bitTrailMapCache??(r&&this._bitTrailLength?r.slice(this._bitTrailOffset,this._bitTrailOffset+this._bitTrailLength):null);this._bitTrailMapCache=null;let a=e?e.length:0,o=n?n.length:0,s=i?Math.ceil(i.length/4)*4:0,c=Math.max(a+o+s,4);if(this.lightStorageAttr&&c<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,a),i&&t.set(i,a+o),this.lightStorageAttr.needsUpdate=!0}else{let r=new Float32Array(c);e&&r.set(e,0),n&&r.set(n,a),i&&r.set(i,a+o),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=r.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(a+o)/4,this._bitTrailOffset=a+o,this._bitTrailLength=i?i.length:0}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),kg.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),kg.debug(`light BVH ${J.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{kg.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),kg.debug(`material rebuild complete`)}catch(e){kg.error(`material rebuild failed:`,e);try{kg.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){kg.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.placeholderTexture?.dispose(),this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleStaging=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};jt();var Ng=vt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},Pg=65535,Fg={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18,SUN_NEE:1<<19,UNDER_SURFACE:1<<20},Ig=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Ng.debug(`queues capacity ${J.n(e)} · ${J.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){ya(this._renderer,this._countersAttr),ya(this._renderer,this._bounceCountsAttr),ya(this._renderer,this._attrA),ya(this._renderer,this._attrB),ya(this._renderer,this._sortAttr),ya(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Lg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Rg={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function zg(e){return(Lg[e.format]??4)*(Rg[e.type]??4)}function Bg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Vg(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*zg(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*zg(e)}var Hg=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*zg(e));return a}return this._isResident(e)?Vg(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};jt();var Ug=vt(`wavefront`),Wg=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);Ug.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>Ug.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);if(!n)return;let r=Math.ceil(t/n.workgroupSize[0]),i=this.renderer?.backend?.device?.limits.maxComputeWorkgroupsPerDimension??65535;n.dispatchSize=r>i?[i,Math.ceil(r/i),1]:[r,1,1]}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},Gg=(0,n.int)(Se.equirectangular),Kg=(0,n.int)(Se.orthographic),qg=e=>e.equal(Kg);function Jg(){let e={cameraProjection:(0,n.uniform)(0,`int`),panoLonRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLatRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLevelHorizon:(0,n.uniform)(1,`int`),sync(t){e.cameraProjection.value=t.get(`cameraProjection`).value,e.panoLonRange.value.copy(t.get(`panoLonRange`).value),e.panoLatRange.value.copy(t.get(`panoLatRange`).value),e.panoLevelHorizon.value=t.get(`panoLevelHorizon`).value}};return e}var Yg=(e,t,n,r)=>({origin:Zg(e,t,n,r.cameraProjection),direction:Qg(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),Xg=(e,t,n,r,i)=>{let{origin:a,direction:o}=Yg(e,n,r,i);return a.add(o.mul(t))},Zg=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(qg(i),()=>{let i=r.mul((0,n.vec4)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),0,1));a.assign(t.mul((0,n.vec4)(i.xy,0,1)).xyz)}),a}),Qg=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Gg),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).ElseIf(qg(i),()=>{c.assign((0,n.normalize)((0,n.vec3)(t[2])).negate())}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),$g=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=Zg(e,r,i,a).toVar(),y=Qg(e,r,i,a,o,s,c).toVar(),b=v.toVar(),x=y.toVar(),S=g.equal((0,n.int)(1)),C=S.and(_.greaterThan(0)).or(S.not().and(u.greaterThan(0)).and(d.lessThan(64)));return(0,n.If)(l.and(C).and(f.greaterThan(.001)),()=>{let e=(0,n.select)(a.equal(Gg),s.y.sub(s.x).mul(.5),(0,n.select)(qg(a),(0,n.float)(1),i[1].y)),o=(0,n.select)(S,_.mul(f).mul(e),u.div(d.mul(2)).mul(.001).mul(p).mul(m)),c=Ht(t),l=c.x.mul(h.max(.01)),g=c.y,C=(0,n.vec3)(0).toVar(),w=f.toVar();(0,n.If)(a.equal(Gg),()=>{C.assign(Gi({N:y}).mul((0,n.vec3)(l,g,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));C.assign(e.mul(l).add(t.mul(g))),w.assign(f.div((0,n.dot)(y,(0,n.normalize)((0,n.vec3)(r[2]))).negate()))}),b.assign(v.add(C.mul(o))),x.assign((0,n.normalize)(v.add(y.mul(w)).sub(b)))}),ui({origin:b,direction:x})});function e_(e){let{rayBufferRW:t,hitBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,unitsPerMetre:_,apertureScale:v,anamorphicRatio:y,dofMode:b,dofBlur:x,renderWidth:S,chunkRowBase:C,chunkRows:w,transmissiveBounces:T,auxGBufferEnabled:E,listDriven:D=!1,activeIndicesRO:O=null,counters:k=null}=e,A=E.greaterThan((0,n.uint)(0)),j=(e,S,C)=>{let w=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(S).add(.5)),E=Rt({state:en({pixelCoord:w,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),D=$t(w,(0,n.int)(1),E,a,o).toVar().sub(.5),O=(0,n.vec2)(w.x.add(D.x),w.y.sub(D.y)).div(a),k=ui.wrap($g(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ia(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),La(t,C,k.direction,(0,n.uint)(Fg.ACTIVE)),Ra(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),za(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Oa(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),ro(t,C,(0,n.vec3)(1))}),Za(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Ja(r,C,E)};return(0,n.Fn)(()=>{if(D){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(k.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(O.element(e)),r=t.add(C.mul(S));j(r.mod(S),r.div(S),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(S).and(t.lessThan(w)),()=>{j(e,t.add(C),(0,n.uint)(t.mul(S).add(e)))})}})}var t_=32,n_=4096,r_=4,i_=1e8,a_=()=>(0,n.array)(`int`,t_).toVar(),o_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),s_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),c_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),l_=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(i_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},u_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),d_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),f_=(0,n.wgslFn)(`
715
+ `);jt();var lp=vt(`shader`),up=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),lp.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode;oa(e.uniforms.get(`enableAlphaShadows`));let c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d=e.goboMaps?(0,n.texture)(e.goboMaps):u();$f(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();rp(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},dp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new fp;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new fp;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},fp=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},pp=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}},mp=1073741824,hp=1073741824,gp=15,_p=16,vp=2147483648,yp=(e,t)=>~(e<<4|t)>>>0,bp=e=>e>=vp,xp=e=>~e>>>0>>>4,Sp=e=>~e&15;function Cp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/_p,r=e=>{let n=e*_p;return t[n+3]===mp&&t[n+1]>0&&t[n+1]<=gp},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*_p;t[n+3]>=hp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*_p),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*_p,s=n*_p;c.set(e.subarray(o,o+_p),s),!(t[o+3]>=hp)&&(l[s+3]=wp(t,t[o+3],r,i),l[s+7]=wp(t,t[o+7],r,i))}return c}function wp(e,t,n,r){let i=t*_p;return n(t)?yp(e[i],e[i+1]):r[t]}var Tp=(e,t,n)=>e>=vp?yp(xp(e)+n,Sp(e)):e+t;function Ep(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=_p){if(e[a+3]===mp){e[a]+=n;continue}e[a+3]=Tp(e[a+3],t,n),e[a+7]=Tp(e[a+7],t,n)}}jt();var Dp=vt(`bvh`),Op=1073741824,kp=1073741826,Ap=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),jp=1073741824;function Mp(e,t){if(e>=jp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${jp}`);return e}var Np=null;function Pp(e){Np=e}var Fp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Ip=Fp.FLOATS_PER_TRIANGLE,Lp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Rp=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},zp=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Lp(this.triangles),n=Fp.POSITION_A_OFFSET,r=Fp.POSITION_B_OFFSET,i=Fp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Ip,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Ip*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Np&&ri()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;Dp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Ip*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Np())}catch(i){Dp.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?Cp(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Ip*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new dp(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){Dp.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new pp(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){Dp.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Ip);for(let e=0;e<a;e++){let t=this.indices[e]*Ip,n=e*Ip;f.set(d.subarray(t,t+Ip),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return Dp.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Rp;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Rp;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Mp(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Ap(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=Op}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Mp(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Ap(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=kp,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Op}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;Mp(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Ap(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<Op&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Bp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},Vp=Bp.FLOATS_PER_TRIANGLE,Hp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Up=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Wp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):Up(e)}},Gp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Kp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,qp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*Xp,Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Hp(e),u:t?e:Up(e)}};function Yp(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var Xp=16,Zp=1073741824,Qp=1073741825,$p=1e-12;function em(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=$p*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,ee=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}function tm(e,t,n,r,i){let a=Bp.POSITION_A_OFFSET,o=Bp.POSITION_B_OFFSET,s=Bp.POSITION_C_OFFSET,c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let r=0;r<n;r++){let n=t+r,i=e.chunked?e.f.chunkFor(n):e.f,m=e.chunked?e.chunked.baseOf(n):n*Vp;c=Math.min(c,i[m+a],i[m+o],i[m+s]),l=Math.min(l,i[m+a+1],i[m+o+1],i[m+s+1]),u=Math.min(u,i[m+a+2],i[m+o+2],i[m+s+2]),d=Math.max(d,i[m+a],i[m+o],i[m+s]),f=Math.max(f,i[m+a+1],i[m+o+1],i[m+s+1]),p=Math.max(p,i[m+a+2],i[m+o+2],i[m+s+2])}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var nm=new Float32Array(12);function rm(e,t,n,r){let i=Gp(e,t),a=Kp(e,t),o=qp(e,t);if(a[o+3]===Zp){tm(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function im(e,t,n,r,i){let a=Gp(e,t),o=Kp(e,t),s=qp(e,t),c=(t-i)*6,l=o[s+3];if(l===Zp){tm(n,o[s],o[s+1],r,c);return}if(l===Qp){em(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;bp(l)&&(tm(n,xp(l),Sp(l),nm,0),d=nm,f=0);let p=r,m=(u-i)*6;bp(u)&&(tm(n,xp(u),Sp(u),nm,6),p=nm,m=6),a[s]=d[f],a[s+1]=d[f+1],a[s+2]=d[f+2],a[s+4]=d[f+3],a[s+5]=d[f+4],a[s+6]=d[f+5],a[s+8]=p[m],a[s+9]=p[m+1],a[s+10]=p[m+2],a[s+12]=p[m+3],a[s+13]=p[m+4],a[s+14]=p[m+5];for(let e=0;e<3;e++)r[c+e]=Math.min(d[f+e],p[m+e]),r[c+3+e]=Math.max(d[f+3+e],p[m+3+e])}var am=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Jp(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*Vp,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+Bp.POSITION_A_OFFSET]=l,a[s+Bp.POSITION_A_OFFSET+1]=u,a[s+Bp.POSITION_A_OFFSET+2]=d,a[s+Bp.POSITION_B_OFFSET]=f,a[s+Bp.POSITION_B_OFFSET+1]=p,a[s+Bp.POSITION_B_OFFSET+2]=m,a[s+Bp.POSITION_C_OFFSET]=h,a[s+Bp.POSITION_C_OFFSET+1]=g,a[s+Bp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=Yp(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Bp.NORMAL_A_PACKED_OFFSET]=w,o[s+Bp.NORMAL_B_PACKED_OFFSET]=w,o[s+Bp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Jp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Wp(e);for(let e=n+r-1;e>=n;e--)im(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=Jp(t),a=Wp(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,s=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=Kp(a,e),n=qp(a,e);t[n+3]===Qp?(rm(a,t[n],i,s),em(Gp(a,e),n,s,0,o,e*6)):im(a,e,i,o,0)}}refit(e,t,n){let r=Jp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Wp(e);for(let e=n-1;e>=0;e--)im(i,e,r,this._bounds,0)}},om="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=1073741824,S=(e,t)=>~(e<<4|t)>>>0;function C(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===1073741824&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=x||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=x)&&(l[s+3]=w(t,t[o+3],r,i),l[s+7]=w(t,t[o+7],r,i))}return c}function w(e,t,n,r){let i=t*16;return n(t)?S(e[i],e[i+1]):r[t]}const T=y(`bvh`),E=1073741824,D=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),O=1073741824;function k(e,t){if(e>=O)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${O}`);return e}const A={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},j=A.FLOATS_PER_TRIANGLE,M=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var N=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},P=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=M(this.triangles),n=A.POSITION_A_OFFSET,r=A.POSITION_B_OFFSET,i=A.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*j,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(j*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?C(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(j*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){T.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){T.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*j);for(let e=0;e<s;e++){let t=this.indices[e]*j,n=e*j;m.set(p.subarray(t,t+j),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return T.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new N;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new N;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=D(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=E}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}k(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=D(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=E}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;k(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=D(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<E&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const F=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?I(t):n===`assemble`?L(t):R(t)};function I(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new P;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;F.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){F.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function L(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:l}=e;try{let e=performance.now(),u=new P().assembleParallelBVH(t,n,r,i),d=l?C(u):u,f=new Uint32Array(o);if(s){let e=new Uint32Array(a),t=new Uint32Array(s);for(let n=0;n<c;n++){let r=f[n]*20,i=n*20;t.set(e.subarray(r,r+20),i)}}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[f[e]]=e;let m=performance.now()-e;F.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(d.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:d,originalToBvh:p,triangleCount:c},[d.buffer,p.buffer])}catch(e){F.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function R(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f,foldLeaves:p}=e,m=new P;l!==void 0&&(m.maxLeafSize=l),u!==void 0&&(m.numBins=u),d!==void 0&&(m.maxBins=d),f!==void 0&&(m.minBins=f);try{o&&m.setTreeletConfig(o),s&&m.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=m.buildSync(l,i,e,u),f=performance.now(),h=m.flattenBVH(d),g=p?C(h):h,v=performance.now()-f;F.debug(`flatten ${_.ms(v)} (${_.mb(g.byteLength)})`);let y=m.originalToBvhMap||null;if(c){let e=[g.buffer];y&&e.push(y.buffer),self.postMessage({bvhData:g,originalToBvh:y,triangleCount:l.length/20,treeletStats:m.splitStats},e)}else{let e=m.reorderedTriangleData,t=e.byteLength/80,n=[g.buffer,e.buffer];y&&n.push(y.buffer),self.postMessage({bvhData:g,triangles:e,originalToBvh:y,triangleCount:t,treeletStats:m.splitStats},n)}}catch(e){F.error(`build failed:`,e),self.postMessage({error:e.message})}}",sm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,om],{type:`text/javascript;charset=utf-8`});function cm(e){let t;try{if(t=sm&&(self.URL||self.webkitURL).createObjectURL(sm),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(om),{type:`module`,name:e?.name})}}var lm="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=1073741824,x=(e,t)=>~(e<<4|t)>>>0;function S(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/16,r=e=>{let n=e*16;return t[n+3]===1073741824&&t[n+1]>0&&t[n+1]<=15},i=new Uint32Array(n),a=new Uint32Array(n),o=0,s=[0];for(;s.length;){let e=s.pop();i[e]=o,a[o++]=e;let n=e*16;t[n+3]>=b||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*16),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*16,s=n*16;c.set(e.subarray(o,o+16),s),!(t[o+3]>=b)&&(l[s+3]=C(t,t[o+3],r,i),l[s+7]=C(t,t[o+7],r,i))}return c}function C(e,t,n,r){let i=t*16;return n(t)?x(e[i],e[i+1]):r[t]}const w=y(`bvh`),T=1073741824,E=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),D=1073741824;function O(e,t){if(e>=D)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${D}`);return e}const k={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},A=k.FLOATS_PER_TRIANGLE,j=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var M=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},N=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.foldLeaves=!1,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=j(this.triangles),n=k.POSITION_A_OFFSET,r=k.POSITION_B_OFFSET,i=k.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*A,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(A*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n),i=this.flattenBVH(r);return{bvhData:this.foldLeaves?S(i):i,bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(A*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){w.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){w.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*A);for(let e=0;e<s;e++){let t=this.indices[e]*A,n=e*A;m.set(p.subarray(t,t+A),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return w.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new M;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new M;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=E(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=T}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}O(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=E(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=T}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;O(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=E(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<T&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new N;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",um=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,lm],{type:`text/javascript;charset=utf-8`});function dm(e){let t;try{if(t=um&&(self.URL||self.webkitURL).createObjectURL(um),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(lm),{type:`module`,name:e?.name})}}jt(),Pp(()=>ii(cm));var fm=vt(`bvh`),pm=20,mm=5e4,hm=8;function gm(e,t,n,r){let i=e.byteLength/(pm*4),a=Math.min(ni(),hm),o=Math.ceil(Math.log2(a*2.5+1));return fm.debug(`parallel build ${J.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let l=e.buffer instanceof SharedArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength,u=l?e.buffer:new SharedArrayBuffer(e.byteLength);l||new Uint32Array(u).set(e),e=null;let d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*3*4),p=new SharedArrayBuffer(i*3*4),m=new SharedArrayBuffer(i*4),h=new SharedArrayBuffer(i*4),g=ii(cm),_=null,v=[g],y={id:null},b=!1,x=()=>{y.id&&=(clearTimeout(y.id),null);for(let e of v)try{e.terminate()}catch{}},S=e=>{if(!b){b=!0,fm.warn(`parallel build failed (${e}), falling back to single worker`),x();try{let e=new ArrayBuffer(u.byteLength);new Uint32Array(e).set(new Uint32Array(u)),s(vm(new Uint32Array(e),t,n,r))}catch(e){c(e)}}};g.onerror=e=>{S(`coordinator error: ${e.message}`)},g.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){S(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){_=t.splitStats,_m(t,a,u,d,f,p,m,null,i,n,g,v,x,S,s,y,r).catch(e=>S(e.message));return}if(t.type===`assembleResult`){b=!0,x(),s({bvhData:t.bvhData,bvhRoot:!0,order:new Uint32Array(m),triangles:new Uint32Array(u),originalToBvh:t.originalToBvh||null,splitStats:_||{}});return}},n&&n(0),g.postMessage({type:`buildPhase1`,sharedTriangleData:u,sharedCentroids:d,sharedBMin:f,sharedBMax:p,sharedIndices:m,sharedMortonCodes:h,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{fm.warn(`parallel build setup failed:`,e),c(e)})})}async function _m(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){fm.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},[_.buffer]);return}fm.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c,foldLeaves:g.foldLeaves},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=ii(dm);d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function vm(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ii(cm),s=e.byteLength/(pm*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*pm*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization,foldLeaves:r.foldLeaves},[l])})().catch(e=>{fm.warn(`single worker fallback failed:`,e),a(e)})})}function ym(e){return ri()&&typeof SharedArrayBuffer<`u`&&e>=mm}var bm=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function xm(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function Sm(e,t,n){let r=xm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(bm),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function Cm(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function wm(e){for(let t=0;t<16;t++)if(e[t]!==bm[t])return!1;return!0}function Tm(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function Em(e,t){for(let n=0;n<16;n++)if(e[t+n]!==bm[n])return!1;return!0}var Dm=class e{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(bm,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(xm(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return Sm(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}Tm(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}Tm(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e,{owners:t=!0}={}){for(let n=0;t&&n<this.templateCount;n++){if(this.tplOwner[n]<0)continue;let t=this.blasData.get(n);t&&this._readRootAABB(Array.isArray(t)?t[0]:t,n,e,this.tplObjectAABB,n*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(t,n,r,i,a){e.rootAABB(t,r,this.tplTriOffset[n],this.tplTriCount[n],i,a)}static rootAABB(e,t,n,r,i,a){if(!e||Je(e)[3]===Ke.TRIANGLE_LEAF){Om(t,n,r,i,a);return}i[a]=Math.min(e[0],e[8]),i[a+1]=Math.min(e[1],e[9]),i[a+2]=Math.min(e[2],e[10]),i[a+3]=Math.max(e[4],e[12]),i[a+4]=Math.max(e[5],e[13]),i[a+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){Om(t,this.tplTriOffset[e],this.tplTriCount[e],n,r)}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,Ye(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}};function Om(e,t,n,r,i){let a=W.FLOATS_PER_TRIANGLE,o=e&&e.chunks?e.viewAs(Float32Array):null,s=o?null:e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),c=1/0,l=1/0,u=1/0,d=-1/0,f=-1/0,p=-1/0;for(let e=0;e<n;e++){let n=t+e,r=o?o.chunkFor(n):s,i=o?o.baseOf(n):n*a;for(let e=0;e<=8;e+=4){let t=r[i+e],n=r[i+e+1],a=r[i+e+2];t<c&&(c=t),n<l&&(l=n),a<u&&(u=a),t>d&&(d=t),n>f&&(f=n),a>p&&(p=a)}}r[i]=c,r[i+1]=l,r[i+2]=u,r[i+3]=d,r[i+4]=f,r[i+5]=p}var km=16,Am=32,jm=e=>e<Am?e:Am,Mm=8,Nm=64,Pm=new Float64Array(16),Fm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Am*3),this._binBounds=new Float64Array(Am*6*3),this._binSuffix=new Float64Array(Am),this._binSuffixCount=new Int32Array(Am),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};Ye(r,`TLAS node count`);let i=r*km;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=Je(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(Nm);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*km;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=Ke.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*km;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=Je(t);for(let r=0;r<n;r++){let n=r*km;if(l[n+3]!==Ke.BLAS_POINTER_LEAF)continue;let u=l[n+1]&Ge;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=Pm;Sm(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(Em(r,i*16)?We:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=Mm)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=jm(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Im=W.FLOATS_PER_TRIANGLE*4,Lm=64,Rm=.9,zm=64,Bm=4,Vm=7040*1024*1024,Hm=9216*1024*1024;function Um(e){if(e>0)return{gb:e,assumed:!1};let t=typeof navigator<`u`?navigator.deviceMemory:void 0;return t>0?{gb:t,assumed:!1}:{gb:4,assumed:!0}}var Wm=1.15,Gm=12*1024*1024*1024;function Km({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Im,bvh:Math.ceil(e*Rm)*Lm,geometry:n,placements:t*zm,orderMaps:e*Bm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function qm(e,{chunkBytes:t=hn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Gm),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var Jm=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}},Ym="let e,t;const n={MAX_BYTES_PER_TEXTURE:256*1024*1024,MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};self.onmessage=async function(t){let{textures:n,maxTextureSize:a,method:o=`direct-transfer`}=t.data;try{e||r(a);let t=await i(n,a,o);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function r(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function i(e,t,r){let i=h(e,t),o=i.maxWidth*i.maxHeight*e.length*4;if(o>n.MAX_BYTES_PER_TEXTURE)return console.log(`Large texture array detected (${(o/1024/1024).toFixed(2)}MB), using chunked processing`),await a(e,t,r);switch(r){case`direct-transfer`:return await d(e,t);case`offscreen-optimized`:return await p(e,t);case`imageBitmap-batch`:return await m(e,t);default:return await d(e,t)}}async function a(e,t,n){let{maxWidth:r,maxHeight:i}=h(e,t),a=e.length,c=o(r,i,a),l=Math.ceil(a/c);console.log(`Processing ${a} textures in ${l} chunks of up to ${c} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*c*4/1024/1024).toFixed(2)}MB`);let u;try{u=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await f(e,g(e,t),n)}let d=r*i*c*4,p;try{p=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await f(e,g(e,t),n)}for(let t=0;t<l;t++){let n=t*c,o=Math.min(n+c,a),l=o-n,d=await s(e.slice(n,o),r,i,p.subarray(0,r*i*l*4)),f=n*r*i*4,m=l*r*i*4;u.set(new Uint8Array(d.data.slice(0,m)),f),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:u.buffer,width:r,height:i,depth:a}}function o(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function s(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await c(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function c(e,n,r,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function l(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await l(e,i,a)}return await s(e,t,n,r)}async function u(e,t,n,r,i){await c(e,n,r*i*4*t,r,i)}async function d(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await u(t,e,c,i,o)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function f(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await l(e,r,i,n)}async function p(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}t.clearRect(0,0,i,o),t.drawImage(n,0,0);let a=t.getImageData(0,0,i,o),s=i*o*4*e;c.set(a.data,s),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function m(n,r){let{maxWidth:i,maxHeight:s}=h(n,r),c=n.length,l;try{l=new Uint8Array(i*s*c*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`imageBitmap-batch`)}let u=Math.min(o(i,s,n.length),n.length);for(let r=0;r<n.length;r+=u){let a=Math.min(r+u,n.length),o=[];for(let e=r;e<a;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}o.push(r.then(t=>({bitmap:t,index:e})))}let c=await Promise.all(o);e.width=i,e.height=s,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of c){t.clearRect(0,0,i,s),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,s),a=i*s*4*n;l.set(r.data,a),e.close()}}return{data:l.buffer,width:i,height:s,depth:c}}function h(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function g(e,t){let n=h(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",Xm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ym],{type:`text/javascript;charset=utf-8`});function Zm(e){let t;try{if(t=Xm&&(self.URL||self.webkitURL).createObjectURL(Xm),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Ym),{type:`module`,name:e?.name})}}var Qm=`function e({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}self.onmessage=function(t){let{layers:n,width:r,height:i}=t.data;try{let t=r*i*4,a=new Uint8Array(t*n.length);n.forEach((n,o)=>e(n,a,o*t,r,i)),self.postMessage({data:a},[a.buffer])}catch(e){self.postMessage({error:e.message})}};`,$m=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Qm],{type:`text/javascript;charset=utf-8`});function eh(e){let t;try{if(t=$m&&(self.URL||self.webkitURL).createObjectURL($m),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Qm),{type:`module`,name:e?.name})}}function th({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}Dl();var nh=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),rh=new Map;function ih(){rh.clear();for(let e of Tl.values())rh.set(e.id,nh(e.cpu))}ih(),cl(ih);function ah(e){return ll(e)?.outputEncoded===!0}function oh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function sh(e,t){let n=ll(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var ch=.2126,lh=.7152,uh=.0722;function dh(e,t){if(t===1)return;let n=e[0]*ch+e[1]*lh+e[2]*uh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function fh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=rh.get(n)??rh.get(r.NoToneMapping),s=sh(t,n),c=ah(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,dh(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=oh(u[0])*255+.5,l[t+1]=oh(u[1])*255+.5,l[t+2]=oh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var ph=vt(`textures`),mh=8*2**20,hh={busy:0,waiting:[]};async function gh(){return hh.busy<Math.max(1,ni()-1)?hh.busy++:await new Promise(e=>hh.waiting.push(e)),()=>{let e=hh.waiting.shift();e?e():hh.busy--}}var _h={toSRGB:null,toLinear:null};function vh(e){if(!_h[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?oh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}_h[e]=t}return _h[e]}var yh=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Xe.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},bh=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||dt.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*dt.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}forget(e){this.memoryUsage=Math.max(0,this.memoryUsage-e.buffer.byteLength)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Xe.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},xh=class{constructor(e=Xe.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Sh=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Xe.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Xe.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new yh,this.bufferPool=new bh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new xh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof pn)throw t;this._issues?.record(Y.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_reportTextureLayer(e,t){this._issues?.record(Y.TEXTURE_BUILD_FAILED,`texture ${e} could not be read — its surfaces show a white placeholder`,{layer:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||Xe.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Xe.MIN_TEXTURE_WIDTH,Math.min(t,Xe.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new xh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:ni()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Eu();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){ph.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,ph.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=vh(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?ph.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):ph.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=Eu()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;if(typeof createImageBitmap>`u`){let n=await this.processOnCPU(e),i=this._harmonizeTransfer(n,e,t);return this._applyColorManagement(n,e,t,i),this.textureCache.set(r,n),n}let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){if(n instanceof pn)throw n;this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>dt.MAX_TEXTURE_MEMORY?{method:`main-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let t=new Zm;try{let n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(r)}finally{t.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=ri()&&i*t.length>=mh?await this._packInWorker(t,n,r):null;if(a)return this.createDataArrayTextureFromBuffer(a,n,r,t.length);let o=this.bufferPool.getBuffer(i*t.length,Uint8Array);return t.forEach((e,t)=>th(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await gh(),i=null;try{let r=[],a=e.map(e=>{if(typeof SharedArrayBuffer<`u`&&e.data.buffer instanceof SharedArrayBuffer)return e;let t=e.data.slice();return r.push(t.buffer),{...e,data:t}});return i=ii(eh),await new Promise((e,o)=>{i.onmessage=t=>t.data.error?o(Error(t.data.error)):e(t.data.data),i.onerror=e=>o(e.error??Error(e.message??`texture pack worker failed`)),i.postMessage({layers:a,width:t,height:n},r)})}catch(e){return this._issues?.warn(Y.TEXTURE_PROCESSING_FALLBACK,`worker texture packing failed — packing on the main thread`,{cause:String(e?.message??e)}),null}finally{i?.terminate(),r()}}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%dt.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=G.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)dn(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Xe.VEC4_PER_BVH_NODE*Xe.FLOATS_PER_VEC4;Ye(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=Je(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=Ke.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new xh;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:Qe(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array},a.onUpdate=()=>{let e=a.userData.buffer;e&&(this.bufferPool.forget(e),a.userData.buffer=null,a.image.data=null)};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e){if(!n?.image){this._reportTextureLayer(t.length,`no image`),t.push(null);continue}if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Ch(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:Ch(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function Ch(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var wh=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Eh(E,Th(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Eh(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Th(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Eh(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}jt();var Dh=Object.freeze({r:0,g:0,b:0});function Oh(e){if(!e)return Dh;if(!Fr())return e;let t=[e.r,e.g,e.b];return Lr(t),{r:t[0],g:t[1],b:t[2]}}var kh=vt(`emissive`),Ah=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=W.FLOATS_PER_TRIANGLE,a=W.MATERIAL_FLAGS_OFFSET,o=W.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){if(s?.spilledChunks&&!s.isResident(e,1)){e=((e/s.recordsPerChunk|0)+1)*s.recordsPerChunk-1;continue}let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&Le,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Oh(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let ne=g.side===2,z=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:te,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:z,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&kh.debug(`${J.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=W.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,kh.debug(`emissive texture ${J.px(t,n)} · ${J.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return kh.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Oh(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new wh().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,kh.debug(`rebuilt sorted emissive data · ${J.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};jt();var jh=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=vt(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Mh=1<<20,Nh=1<<21,Ph=()=>new Promise(e=>setTimeout(e,0)),Fh=[0,1,2,4,5,6,8,9,10];function Ih(e,t,n,r=Fh){let i=e.lanesPerRecord,a=r.length,o=0,s=0,c=0;for(;c<n;){let l=t+c,u=e.chunkFor(l),d=Math.min(e.recordsPerChunk-l%e.recordsPerChunk,n-c),f=e.baseOf(l);for(let e=0;e<d;e++,f+=i){let e=2166136261,t=2654435769;for(let n=0;n<a;n++){let i=u[f+r[n]];e=Math.imul(e^i,16777619),t=Math.imul(t+i|0,2246822507)^t>>>13}o=o+e>>>0,s=s+t>>>0}c+=d}return`${o.toString(16)}.${s.toString(16)}`}async function Lh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Ih(e,i,a)),r+=a,r>=Nh&&(r=0,await Ph());return n}async function Rh(e,t){let n=await e?.area(Wn.SCENES).open(t);if(!n)return null;try{let e=await n.json(`index.json`),t=await n.file(`nodes.f32`),r=await n.file(`order.u32`);return e?.v!==2||!t||!r?(n.release(),null):{index:e,nodes:t,order:r,release:()=>n.release()}}catch{return n.release(),null}}async function zh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(Wn.SCENES);if(!s)return!1;let c=n.totalNodes-n.tlasNodeCount,l=i.reduce((e,t)=>e+(t?.byteLength??0),0),u=await s.create(t,{label:`${o} (BVH)`,expectedBytes:c*64+l});if(!u)return!1;try{for(let e=n.tlasNodeCount;e<n.totalNodes;){if(a())throw Error(`scene changed while it was being stored`);let t=r.chunkFor(e),i=r.recordsPerChunk-e%r.recordsPerChunk,o=Math.min(i,n.totalNodes-e,Mh),s=r.baseOf(e);await u.write(`nodes.f32`,t.subarray(s,s+o*16)),e+=o}for(let e of i)if(e)for(let t=0;t<e.length;t+=Mh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+Mh*4)));if(l===0&&await u.write(`order.u32`,new Uint8Array),a())throw Error(`scene changed while it was being stored`);return await u.writeJSON(`index.json`,n),await u.commit(),!0}catch{return await u.abort(),!1}}async function Bh(e,t,n,r){for(let i=0;i<r;i+=Mh){let a=Math.min(Mh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Vh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Hh=16,Uh=W.POSITION_A_OFFSET,Wh=W.POSITION_B_OFFSET,Gh=W.POSITION_C_OFFSET;async function Kh(e,t,n,r,{pause:i=null}={}){let a=e.lanesPerRecord,o=[new Float32Array(n),new Float32Array(n),new Float32Array(n)],[s,c,l]=o;for(let r=0;r<n;){let i=e.chunkFor(t+r),o=new Float32Array(i.buffer,i.byteOffset,i.length),u=Math.min(n,(((t+r)/e.recordsPerChunk|0)+1)*e.recordsPerChunk-t);for(let n=e.baseOf(t+r);r<u;r++,n+=a)s[r]=o[n+Uh]+o[n+Wh]+o[n+Gh],c[r]=o[n+Uh+1]+o[n+Wh+1]+o[n+Gh+1],l[r]=o[n+Uh+2]+o[n+Wh+2]+o[n+Gh+2]}let u=new Uint32Array(n);for(let e=0;e<n;e++)u[e]=e;let d=[],f=(e,t)=>{if(t-e<=r)return d.push({start:e,count:t-e}),{piece:d.length-1};let n=e+(t-e>>1);return Jh(u,o,qh(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await Yh(e,t,n,u,i),{order:u,pieces:d,tree:p}}function qh(e,t,n){let r=0,i=-1;for(let a=0;a<3;a++){let o=e[a],s=1/0,c=-1/0;for(let e=t;e<n;e++){let t=o[e];t<s&&(s=t),t>c&&(c=t)}c-s>i&&(i=c-s,r=a)}return r}function Jh(e,t,n,r,i,a){let o=t[n],[s,c,l]=t,u=(t,n)=>{let r=e[t];e[t]=e[n],e[n]=r,r=s[t],s[t]=s[n],s[n]=r,r=c[t],c[t]=c[n],c[n]=r,r=l[t],l[t]=l[n],l[n]=r},d=2654435769,f=()=>(d^=d<<13,d^=d>>>17,d^=d<<5,o[r+(d>>>0)%(i-r)]);for(;i-r>1;){let e=f(),t=f(),n=f(),s=e<t?t<n?t:e<n?n:e:e<n?e:t<n?n:t,c=r,l=r,d=i;for(;l<d;){let e=o[l];e<s?u(c++,l++):e>s?u(l,--d):l++}if(a<c)i=c;else if(a>=d)r=d;else return}}async function Yh(e,t,n,r,i){let a=e.lanesPerRecord,o=new Uint32Array(a),s=new Uint8Array(n),c=0;for(let l=0;l<n;l++){if(s[l]||(s[l]=1,r[l]===l))continue;let n=e.chunkFor(t+l),u=e.baseOf(t+l);for(let e=0;e<a;e++)o[e]=n[u+e];for(let d=l;;){let f=r[d],p=n,m=u;if(f===l){for(let e=0;e<a;e++)p[m+e]=o[e];break}n=e.chunkFor(t+f),u=e.baseOf(t+f);for(let e=0;e<a;e++)p[m+e]=n[u+e];s[f]=1,d=f,i&&!(++c&1048575)&&await i()}}}function Xh(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Hh;let s=new Float32Array(i*Hh),c=new Uint32Array(s.buffer),l=[s],u=new Uint32Array(r.length);for(let e=0;e<t.length;e++){let{bvhData:i,originalToBvh:o}=n[e];n[e].bvhData=n[e].originalToBvh=null;let s=a[e],{start:c,count:d}=t[e];Ep(new Uint32Array(i.buffer,i.byteOffset,i.length),s,c),l.push(i);for(let e=0;e<d;e++)u[r[c+e]]=c+(o?o[e]:e)}let d=0,f=e=>{if(e.piece!==void 0)return{index:a[e.piece],box:n[e.piece].aabb};let t=d++,r=f(e.left),i=f(e.right),o=t*Hh;return s[o]=r.box[0],s[o+1]=r.box[1],s[o+2]=r.box[2],c[o+3]=r.index,s[o+4]=r.box[3],s[o+5]=r.box[4],s[o+6]=r.box[5],c[o+7]=i.index,s[o+8]=i.box[0],s[o+9]=i.box[1],s[o+10]=i.box[2],s[o+12]=i.box[3],s[o+13]=i.box[4],s[o+14]=i.box[5],{index:t,box:[0,1,2].map(e=>Math.min(r.box[e],i.box[e])).concat([3,4,5].map(e=>Math.max(r.box[e],i.box[e])))}};return f(e),{bvhData:l,nodeCount:o,originalToBvh:u}}var Zh=`9.3.3`,Qh=1e4,$h=15e5;function eg(e,t,n=Qh){return e>=n&&t/$h<e/3}var tg="const e=e=>e>=2147483648,t=e=>~e>>>0>>>4,n=e=>~e&15,r={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},i=r.FLOATS_PER_TRIANGLE,a=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),o=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),s=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):o(e)}},c=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,l=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,u=(e,t)=>e.chunked?e.chunked.baseOf(t):t*p,d=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):a(e),u:t?e:o(e)}};function f(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const p=16,m=1073741824,h=1073741825;function g(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}function _(e,t,n,a,o){let s=r.POSITION_A_OFFSET,c=r.POSITION_B_OFFSET,l=r.POSITION_C_OFFSET,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0;for(let r=0;r<n;r++){let n=t+r,a=e.chunked?e.f.chunkFor(n):e.f,o=e.chunked?e.chunked.baseOf(n):n*i;u=Math.min(u,a[o+s],a[o+c],a[o+l]),d=Math.min(d,a[o+s+1],a[o+c+1],a[o+l+1]),f=Math.min(f,a[o+s+2],a[o+c+2],a[o+l+2]),p=Math.max(p,a[o+s],a[o+c],a[o+l]),m=Math.max(m,a[o+s+1],a[o+c+1],a[o+l+1]),h=Math.max(h,a[o+s+2],a[o+c+2],a[o+l+2])}a[o]=u,a[o+1]=d,a[o+2]=f,a[o+3]=p,a[o+4]=m,a[o+5]=h}const v=new Float32Array(12);function y(e,t,n,r){let i=c(e,t),a=l(e,t),o=u(e,t);if(a[o+3]===m){_(n,a[o],a[o+1],r,0);return}for(let e=0;e<3;e++)r[e]=Math.min(i[o+e],i[o+8+e]),r[3+e]=Math.max(i[o+4+e],i[o+12+e])}function b(r,i,a,o,s){let d=c(r,i),f=l(r,i),p=u(r,i),y=(i-s)*6,b=f[p+3];if(b===m){_(a,f[p],f[p+1],o,y);return}if(b===h){g(d,p,o,(f[p]-s)*6,o,y);return}let x=f[p+7],S=o,C=(b-s)*6;e(b)&&(_(a,t(b),n(b),v,0),S=v,C=0);let w=o,T=(x-s)*6;e(x)&&(_(a,t(x),n(x),v,6),w=v,T=6),d[p]=S[C],d[p+1]=S[C+1],d[p+2]=S[C+2],d[p+4]=S[C+3],d[p+5]=S[C+4],d[p+6]=S[C+5],d[p+8]=w[T],d[p+9]=w[T+1],d[p+10]=w[T+2],d[p+12]=w[T+3],d[p+13]=w[T+4],d[p+14]=w[T+5];for(let e=0;e<3;e++)o[y+e]=Math.min(S[C+e],w[T+e]),o[y+3+e]=Math.max(S[C+3+e],w[T+3+e])}var x=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let a=n.length,o=d(e);for(let e=0;e<a;e++){let a=n[e],s=o.chunked?o.f.chunkFor(e):o.f,c=o.chunked?o.u.chunkFor(e):o.u,l=o.chunked?o.chunked.baseOf(e):e*i,u=a*9,d=t[u],p=t[u+1],m=t[u+2],h=t[u+3],g=t[u+4],_=t[u+5],v=t[u+6],y=t[u+7],b=t[u+8];s[l+r.POSITION_A_OFFSET]=d,s[l+r.POSITION_A_OFFSET+1]=p,s[l+r.POSITION_A_OFFSET+2]=m,s[l+r.POSITION_B_OFFSET]=h,s[l+r.POSITION_B_OFFSET+1]=g,s[l+r.POSITION_B_OFFSET+2]=_,s[l+r.POSITION_C_OFFSET]=v,s[l+r.POSITION_C_OFFSET+1]=y,s[l+r.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-p,C=_-m,w=v-d,T=y-p,E=b-m,D=f(S*E-C*T,C*w-x*E,x*T-S*w);c[l+r.NORMAL_A_PACKED_OFFSET]=D,c[l+r.NORMAL_B_PACKED_OFFSET]=D,c[l+r.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=d(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=s(e);for(let e=n+r-1;e>=n;e--)b(a,e,i,this._bounds,n)}refitPartial(e,t,n,r){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let i=d(t),a=s(e);(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let o=this._tlasBounds,f=this._rootBox||=new Float32Array(6);for(let e=r-1;e>=0;e--){let t=l(a,e),n=u(a,e);t[n+3]===h?(y(a,t[n],i,f),g(c(a,e),n,f,0,o,e*6)):b(a,e,i,o,0)}}refit(e,t,n){let r=d(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=s(e);for(let e=n-1;e>=0;e--)b(i,e,r,this._bounds,0)}};const S=64*1024*1024;function C(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var w=class e{constructor(e,t,n,r=S,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(C(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(C(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=S,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=C(this.LaneType,n,this.shared);for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)!this.chunks[e]&&!this._spilled?.has(e)&&this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0,n=this.chunks[t];if(n)return n;if(this._spilled?.has(t))throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);return this._materialize(t)}async spill(e,{keep:t=()=>!1}={}){if(this._owner)throw Error(`ChunkedRecords: spill the storage, not a view of it`);this._store=e,this._spilled??=new Set;let n=0;for(let r=0;r<this.chunks.length;r++){let i=this.chunks[r];if(!(!i||t(r))){await e.write(r,i),this.chunks[r]=null;for(let e of this._liveViews())e.chunks[r]=null;this._spilled.add(r),n+=i.byteLength}}return n}async spillChunk(e,t){let n=this.chunks[e];if(!n)return 0;this._store=t,this._spilled??=new Set,await t.write(e,n),this.chunks[e]=null;for(let t of this._liveViews())t.chunks[e]=null;return this._spilled.add(e),n.byteLength}async ensureResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++){if(!this._spilled.has(e))continue;let t=Math.min(this.recordsPerChunk,this.recordCount-e*this.recordsPerChunk)*this.lanesPerRecord,n=await this._store.read(e,t*this.LaneType.BYTES_PER_ELEMENT),r=C(this.LaneType,t,this.shared);new Uint8Array(r.buffer,r.byteOffset,r.byteLength).set(new Uint8Array(n)),this.chunks[e]=r;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);this._spilled.delete(e)}}_liveViews(){return this._weakViews&&=this._weakViews.filter(e=>e.deref()),[...this._views??[],...(this._weakViews??[]).map(e=>e.deref())]}isResident(e=0,t=this.recordCount){if(!this._spilled?.size||t<=0)return!0;let n=e/this.recordsPerChunk|0,r=(e+t-1)/this.recordsPerChunk|0;for(let e=n;e<=r;e++)if(this._spilled.has(e))return!1;return!0}get spilledChunks(){return this._spilled?.size??0}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}grow(e){if(e<=this.recordCount)return;let t=this.chunks.length-1,n=(e,t)=>Math.min(this.recordsPerChunk,t-e*this.recordsPerChunk)*this.lanesPerRecord,r=this.chunks[t];this.recordCount=e;for(let t of this._liveViews())t.recordCount=e;if(this.chunks.length*this.recordsPerChunk<e){this.chunks.length=Math.ceil(e/this.recordsPerChunk);for(let e of this._liveViews())e.chunks.length=this.chunks.length}if(r&&r.length<n(t,e)){let i=C(this.LaneType,n(t,e),this.shared);i.set(r),this.chunks[t]=i;for(let e of this._liveViews())e.chunks[t]=new e.LaneType(i.buffer,i.byteOffset,i.byteLength/e.LaneType.BYTES_PER_ELEMENT)}else if(!r&&this._spilled?.has(t))throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`)}release(e,t){let n=this.recordsPerChunk,r=Math.ceil(e/n),i=Math.floor((e+t)/n),a=0;for(let e=r;e<i;e++){let t=this.chunks[e];if(t){a+=t.byteLength,this.chunks[e]=void 0;for(let t of this._liveViews())t.chunks[e]=void 0}}return a}trimInPlace(e){let t=Math.max(1,Math.ceil(e/this.recordsPerChunk)),n=Math.max(0,(e-(t-1)*this.recordsPerChunk)*this.lanesPerRecord),r=[this,...this._liveViews()];for(let i of r){i.chunks.length=t;let r=i.chunks[t-1];r&&r.length>n&&(i.chunks[t-1]=r.subarray(0,n)),i.recordCount=e}if(this._spilled)for(let e of this._spilled)e>=t&&this._spilled.delete(e);return this}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,r._owner=this,this._views?this._views.push(r):(this._weakViews??=[]).push(new WeakRef(r)),r._spilled=this._spilled??=new Set,r}};const T=new x;let E=null,D=null,O=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){E=w.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),D=w.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),O=E.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r}=e.data;n?T.refitPartial(E,D,n,r):T.refit(E,D,O),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",ng=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,tg],{type:`text/javascript;charset=utf-8`});function rg(e){let t;try{if(t=ng&&(self.URL||self.webkitURL).createObjectURL(ng),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(tg),{type:`module`,name:e?.name})}}var ig="const e=Math.PI/180;function t(e){let t=2*Math.PI*(e-1)/365;return .006918-.399912*Math.cos(t)+.070257*Math.sin(t)-.006758*Math.cos(2*t)+907e-6*Math.sin(2*t)-.002697*Math.cos(3*t)+.00148*Math.sin(3*t)}function n({hours:n,dayOfYear:r,latitude:i}){let a=t(r),o=(n-12)*15*e,s=i*e,c=Math.sin(s)*Math.sin(a)+Math.cos(s)*Math.cos(a)*Math.cos(o),l=Math.asin(Math.min(1,Math.max(-1,c)))/e;return{azimuth:(Math.atan2(Math.sin(o),Math.cos(o)*Math.sin(s)-Math.tan(a)*Math.cos(s))/e+540)%360,elevation:l}}const r=e=>[0,31,59,90,120,151,181,212,243,273,304,334][e-1]+21,i=Object.freeze({time:10,month:3,latitude:40}),a=n({hours:i.time,dayOfYear:r(i.month),latitude:i.latitude}),o=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`look`}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1,dofMode:`physical`})}),s={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:o.viewer.toneMapping,exposure:1,saturation:o.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:o.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:180-a.azimuth,skySunElevation:a.elevation,skySunStrength:1,skySunSize:.53,skyTurbidity:2,skyOzone:300,skyAirDensity:1,skyGroundAlbedo:`#959595`,skyAltitude:50,skyPreset:`clearDay`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,unitsPerMetre:1,dofMode:o.viewer.dofMode,dofBlur:.05,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};Object.freeze({perspective:0,equirectangular:1,orthographic:2}),s.fov,s.focusDistance,s.aperture,s.focalLength,180-a.azimuth,a.elevation,c({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function c(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const l={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function u(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function d(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),s.maxSamples,s.bounces,s.renderMode,s.enableAlphaShadows,s.maxSubsurfaceSteps;const f=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function p(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function m(e,t,n){let r=p(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(f),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function h(e,t){for(let n=0;n<16;n++)if(e[t+n]!==f[n])return!1;return!0}const g=e=>e<32?e:32,_=new Float64Array(16);var v=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};d(r,`TLAS node count`);let i=r*16;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=u(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(64);let c=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,s,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let e=f*16;o[e]=0,o[e+1]=s[p],a[e+2]=0,o[e+3]=l.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),l=f*16;a[l]=h[0],a[l+1]=h[1],a[l+2]=h[2],o[l+3]=r,a[l+4]=h[3],a[l+5]=h[4],a[l+6]=h[5],o[l+7]=i,a[l+8]=h[6],a[l+9]=h[7],a[l+10]=h[8],a[l+11]=0,a[l+12]=h[9],a[l+13]=h[10],a[l+14]=h[11],a[l+15]=0;let u=n<=m-e,d=u?0:6,S=u?6:0;c=this._push(c,u?i:r,u?e:p,u?m:e,h,S),f=u?r:i,u?m=e:p=e,g=h[d],_=h[d+1],v=h[d+2],y=h[d+3],b=h[d+4],x=h[d+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,d=u(t);for(let r=0;r<n;r++){let n=r*16;if(d[n+3]!==l.BLAS_POINTER_LEAF)continue;let u=d[n+1]&1073741823;d[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,d,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=_;m(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(h(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=m-d,v[1]=h-f,v[2]=_-p,y[0]=d,y[1]=f,y[2]=p;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=g(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=O-1;e>=1;e--){let u=(t+e)*6;w[u]<i&&(i=w[u]),w[u+1]<a&&(a=w[u+1]),w[u+2]<o&&(o=w[u+2]),w[u+3]>s&&(s=w[u+3]),w[u+4]>c&&(c=w[u+4]),w[u+5]>l&&(l=w[u+5]),d+=C[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/u;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const y={silent:0,error:1,warn:2,info:3,debug:4},b=`info`,x=`rayzeeLogLevel`,S=`rayzeeLogNamespaces`,C=`color:#7c8494`,w=`color:inherit`;let T=null,E=null;function D(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function O(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function k(){if(T!==null)return T;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in y?(T=y[e],T):(T=y[D(x)]??y[b],T)}function A(){if(E!==null)return E;let e=globalThis.__RAYZEE_LOG_NS__??D(S);return E=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],E}function j(e,t){if(t<y.debug)return!0;let n=A();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function M(e,t,n){if(e>k()||!j(t,e))return;let r=e===y.error?console.error:e===y.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,C,w,...n.slice(1)):r(`%c${i}`,C,...n)}const N={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${N.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},P={levels:y,setLevel(e){return e in y?(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e],O(x,e===b?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(y).join(`, `)}`),this.getLevel())},getLevel(){let e=k();return Object.keys(y).find(t=>y[t]===e)},isEnabled(e){return(y[e]??y.debug)<=k()},only(...e){let t=e.flat().filter(Boolean);return E=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),O(S,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return T=null,E=null,this.getLevel()}};function F(e){return{namespace:e,error:(...t)=>M(y.error,e,t),warn:(...t)=>M(y.warn,e,t),info:(...t)=>M(y.info,e,t),debug:(...t)=>M(y.debug,e,t),isEnabled:e=>P.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){M(y.info,e,[t]),r.forEach(t=>M(y.debug,e,[t]));return}y.info>k()||((k()>=y.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,C,w),r.forEach(e=>console.log(e)),console.groupEnd())}}}function I(e){e&&e in y&&(globalThis.__RAYZEE_LOG_LEVEL__=e,T=y[e])}const L=F(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;I(r);try{let e=performance.now(),{data:r,nodeCount:i}=new v().buildStructure(new Float64Array(t),n);L.debug(`TLAS ${N.n(i)} nodes in ${N.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){L.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",ag=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,ig],{type:`text/javascript;charset=utf-8`});function og(e){let t;try{if(t=ag&&(self.URL||self.webkitURL).createObjectURL(ag),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(ig),{type:`module`,name:e?.name})}}jt(),Ys();var sg=5e4,cg=2e5,lg=2e6,ug=1<<19,dg=4e7,fg=1.5*1024**3,pg=256*1024*1024,mg=vt(`scene`),hg=e=>Array.isArray(e)?e:[e],gg=e=>hg(e).reduce((e,t)=>e+t.byteLength,0),_g=64*1024*1024;async function vg(e,t,n){for(let r of hg(n))await e.writeAt(t,r),t+=r.byteLength}function yg(e){let t=0;return e.traverse(e=>{let n=e.isMesh?e.geometry:null;n&&(t=Math.max(t,Math.ceil((n.index?n.index.count:n.attributes.position?.count??0)/3)))}),t}var bg=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Xe.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(ni(),6),maxSceneBytes:Hm,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:Qh,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new Jm,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new jr({issues:this.config.issues}),this.bvhBuilder=new zp,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new Sh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ah,this.tlasBuilder=new Fm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?mg.debug(e):mg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Km(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=fg+yg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Vm,maxBytes:t,fits:r.total<=Vm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(mg.debug(J.list([`memory preflight: ${J.mb(r.total)} estimated`,`triangles ${J.mb(r.triangles)} · bvh ${J.mb(r.bvh)} · geometry ${J.mb(r.geometry)}`,`${J.n(n.triangles)} tris · ${J.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${J.mb(r.total)} of CPU memory, past the ${J.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${J.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Y.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`Scene needs about ${J.mb(r.total)} of CPU memory, above the ${J.mb(Vm)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Vm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=qm(Math.ceil(t*Wm),{shared:gn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Y.SCENE_MEMORY_BUDGET,`BVH assembly needs ${J.mb(t)} but only ${J.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?gg(n):0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${J.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;mg.debug(J.list([`memory: peak live ${J.mb(t)}`,`allocated ${J.mb(e)}`,i?`predicted ${J.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e,{sceneKey:t=null,progressive:n=null}={}){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,vn(e=>this.memory.alloc(e));let r=new jh(e.name??``,{namespace:`scene`});try{this._reset(),this._sceneKey=t,this._blasKey=null,this._blasRestored=!1,this._progressive=n?.storage&&n.uploader?n:null;let i=this.geometryExtractor._countStoredTriangles(e);this._streaming=!!this._progressive&&i>Math.floor(67108864/(W.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>dg,this.bvhBuilder.foldLeaves=this._foldLeaves,this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),r.start(`Geometry extraction`),this._streaming?await this._extractStreaming(e):await this._extractGeometry(e),r.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=r.getDuration(`Geometry extraction`),this._geometryBytes=Tr(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,r.start(`BVH construction (worker)`),r.start(`Material textures (parallel)`);let a=!1,o=this._buildBVH().then(()=>r.end(`BVH construction (worker)`)),s=this._createMaterialTextures().then(()=>{r.end(`Material textures (parallel)`),a=!0});return await o,z({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||z({status:`Processing material textures...`,progress:80}),await s,this.performanceMetrics.bvhBuildTime=r.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=r.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,r.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),r.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-r.totalStart,r.print(),this.processingStage=`complete`,await this._restoreGeometry(e),z({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>mg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,mg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),vn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{this._adoptExtraction(this.geometryExtractor.extract(e));let n=performance.now()-t;this._log(`Geometry extraction complete (${n.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw mg.error(`geometry extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry and building BVHs...`,progress:15}),await new Promise(e=>setTimeout(e,0));let t=performance.now(),n=this.geometryExtractor,{storage:r,uploader:i}=this._progressive,a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=n._countStoredTriangles(e),s=bn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await ur.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await ur.create(r,`${a}:blas`,0,{label:`BLAS nodes (while building)`});if(!u)return await l?.dispose(),this._streaming=!1,this._extractGeometry(e);let d=await gr.create(r,`${a}:geo`,this.memoryPreflight?.geometryBytes??0);this._geometrySpill=d;let f={key:a,triStore:l,blasStore:u,bvhStore:null,blasBytes:0,blasAt:new Map,pending:[],extractedChunks:0,emitterChunks:new Set,isEmitter:e=>n._emissiveMaterial(e),uploadTriangles:null,chain:Promise.resolve(),error:null};this._spillStores=[l],this._blasKey=null;let p=new Map,m=this._blasWorkerOpts(),h=[],g=()=>new Promise(e=>h.push(e)),_=()=>{let e=h;h=[];for(let t of e)t()},v=null,y=(e,t,n)=>{let r=n.bvhData,i=new Float32Array(6);Dm.rootAABB(hg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=gg(r),f.blasAt.set(e,a),n.nodeCount=gg(r)/64,n.bvhData=null,this._queueSpill(f,()=>vg(u,a,r)),this._forEachChunk(v,t.start,t.count,e=>{--f.pending[e]===0&&e<f.extractedChunks&&this._finishTriangleChunk(f,e)}),_()},b=0,x=this._blasPool(m,()=>b++,(e,t,n)=>y(e,t,n)),S=Promise.resolve(),C=0,w=e=>{let t=e>=v.recordCount?v.chunks.length:Math.floor(e/v.recordsPerChunk);for(let e=f.extractedChunks;e<t;e++)f.pending[e]||this._finishTriangleChunk(f,e);f.extractedChunks=Math.max(f.extractedChunks,t)},T;try{if(T=await n.extractStreaming(e,{onStore:e=>{v=e,this._setTriangleData(e),f.uploadTriangles=i(e,`triangles`)},onRange:(e,t)=>{this._forEachChunk(v,t.start,t.count,e=>f.pending[e]=(f.pending[e]??0)+1),this._isLargeMesh(t)?(C++,S=S.then(async()=>{y(e,t,await this._buildLargeBLAS(t,m)),C--}),S.catch(e=>{f.error??=e,_()})):x.submit({m:e,range:t})},releaseGeometry:d?e=>d.add(e):null,pause:async e=>{for(w(e),d?.queuedBytes>pg&&await d.written(),z({status:`Extracted ${e.toLocaleString()} triangles, ${b.toLocaleString()} BVHs built...`,progress:15+Math.floor(20*e/Math.max(1,o))}),await new Promise(e=>setTimeout(e,0));v.byteLength>fg&&(x.pending>0||C>0)&&!f.error&&!x.error;)await Promise.race([g(),new Promise(e=>setTimeout(e,50))]);if(f.error||x.error)throw f.error??x.error}}),w(1/0),await Promise.all([x.close(),S]),await f.chain,f.error)throw f.error}catch(e){throw x.abort(e),mg.error(`streamed extraction failed:`,e),z({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}this._adoptExtraction(T),this._streamed={state:f,templates:p},this._log(`Geometry extracted and ${p.size} BLASes built together (${(performance.now()-t).toFixed(0)}ms)`)}_adoptExtraction(e){if(this._setTriangleData(e.triangleData),this.geometryExtractor.releaseTriangles(),this.triangleCount=Ye(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${qe.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.instanceMatrices=e.instanceMatrices||null,this.instanceCount=e.instanceCount||0,this.bakeInverse=e.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=e.materials,this.materialTriangleCounts=e.materialTriangleCounts,this.meshes=e.meshes,this.meshTriangleRanges=e.meshTriangleRanges,this.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new Dm,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this._streamed;this._streamed=null;let c=[],l=[],u=[],d=new Map,f=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=f.get(n.start);if(r!==void 0){d.set(e,r);continue}f.set(n.start,e),s?u.push({m:e,range:n}):this._isLargeMesh(n)?l.push({m:e,range:n}):c.push({m:e,range:n})}let p=this._blasWorkerOpts(),m=c.length+l.length,h=0,g=()=>{h++,z({status:`Building BLAS ${h}/${m}...`,progress:25+Math.floor(h/m*45)})},_=[...c,...l].map(({m:e,range:t})=>({m:e,range:t,t:o(e),triOffset:t.start,triCount:t.count})).sort((e,t)=>e.t-t.t),v=s?null:await this._restoreBLASes(_,Fm.nodeCountFor(r),p),y=s?s.state:!v&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(_):null,b=y&&!s?(e,t,n)=>this._onBLASBuilt(y,o(e),t,n):null;if(s)for(let[e,t]of s.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);v&&(c.length=0,l.length=0,z({status:`Restored stored BVHs`,progress:68}));let x=v?Promise.resolve(v.results):s?Promise.resolve(u.map(({m:e,range:t})=>({m:e,range:t,result:s.templates.get(o(e)).result}))):this._buildBLASesWithPool(c,p,g,b),S=[],C=(async()=>{for(let{m:e,range:t}of l){let n=await this._buildLargeBLAS(t,p);b?.(e,t,n),S.push({m:e,range:t,result:n}),g()}})(),[w]=await Promise.all([x,C]);if(y&&(await y.chain,y.error))throw y.error;let T={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:t,result:r}of[...w,...S]){let i=r.splitStats;i&&(T.sah+=i.sahSplits??0,T.objMed+=i.objectMedianSplits??0,T.spatMed+=i.spatialMedianSplits??0,T.failed+=i.failedSplits??0,T.treeletsImproved+=i.treeletsImproved??0,T.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??gg(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of d)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);z({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,z({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let E=performance.now(),D=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!y}),this.instanceTable.assignOffsets(Fm.nodeCountFor(D.count));let O=this.instanceTable.totalNodeCount,k=await this._buildTLAS(D);this.performanceMetrics.tlasBuildTime=performance.now()-E,this.memory.mark(`assemble`);let A=performance.now();y||this._checkAssemblyHeadroom(O),this._setBVHData(bn.lazy(O,16,Float32Array,void 0,gn));let j=y?await this._beginBVHSpill(y,D.tlasNodeCount):null;this.bvh.setRecords(0,k),k=null,this.tlasBuilder.releaseFlattenBuffer();let M=Math.max(1,Math.ceil(D.templateCount/32));if(v){try{let e=performance.now();await Bh(v.nodes,this.bvh,D.tlasNodeCount,O-D.tlasNodeCount),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{v.release()}D.blasData.clear()}else{for(let e=0;e<D.templateCount;e++){let t=y?await this._readSpilledBLAS(y,e):D.blasData.get(e);if(!t)continue;let n=D.tplBlasOffset[e],r=n;for(let e of hg(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,D.tplTriOffset[e]),D.blasData.delete(e),await j?.(r),e%M===0&&this._sampleMemory(`assembling ${e}/${D.templateCount}`)}await j?.(O,!0),y&&await y.blasStore.dispose()}if(this._setBVHData(this.bvh.materializeAll()),v)for(let[e,t]of v.orders)D.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-A,D.originalToBvhMap.clear(),D.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let N=performance.now()-e;mg.debug(J.list([`${J.n(D.setCount)} BLASes + TLAS`,`${J.n(this.bvh.recordCount)} nodes`,`SAH ${J.n(T.sah)} · objMed ${T.objMed} · spatMed ${T.spatMed} · failed ${T.failed}`,T.treeletsProcessed?`treelets ${T.treeletsImproved}/${T.treeletsProcessed} improved`:null,J.ms(N)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw mg.error(`BVH build failed:`,e),z({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_blasWorkerOpts(){return{depth:this.config.bvhDepth,treeletOptimization:{enabled:this.config.enableTreeletOptimization!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,foldLeaves:this._foldLeaves===!0,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:bt()}}_isLargeMesh(e){return e.count>=cg&&ym(e.count)}async _buildLargeBLAS(e,t){if(e.count>lg)return this._buildSplitBLAS(e,t);let n=new Uint32Array(new SharedArrayBuffer(e.count*this.triangles.lanesPerRecord*4));this.triangles.readRecords(e.start,e.count,n),this.triangles.release(e.start,e.count);let r=await gm(n,this.config.bvhDepth,null,t);return r.reorderedTriangles?(this.triangles.setRecords(e.start,r.reorderedTriangles),delete r.reorderedTriangles):r.order&&(this._writeInOrder(e.start,r.triangles,r.order),delete r.order,delete r.triangles),r}async _buildSplitBLAS(e,t){let n=this.triangles,{order:r,pieces:i,tree:a}=await Kh(n,e.start,e.count,ug,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(ni(),8));i.forEach((t,n)=>o.submit({m:n,range:{start:e.start+t.start,count:t.count}}));let s=[],c={};for(let{m:e,range:t,result:r}of await o.close()){r.aabb=new Float32Array(6),Dm.rootAABB(r.bvhData,n,t.start,t.count,r.aabb,0),s[e]=r;for(let[e,t]of Object.entries(r.splitStats??{}))typeof t==`number`&&(c[e]=(c[e]??0)+t)}return{...Xh(a,i,s,r),splitStats:c}}_blasCacheKey(e){let t={...e};delete t.logLevel;let n=typeof navigator<`u`?navigator.hardwareConcurrency:0;return`blas:2:${Zh}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Fu(Ks().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Rh(r,this._blasKey);if(!i)return null;let a=e=>(mg.debug(`stored BLASes not used: ${e}`),i.release(),null),{index:o}=i;if(o.tlasNodeCount!==t||o.templates.length!==e.length)return a(`layout changed`);let s=t;for(let t=0;t<e.length;t++){let[n,r,i,c,l]=o.templates[t],u=e[t];if(u.t!==n||u.triOffset!==r||u.triCount!==i||l!==s)return a(`layout changed`);s+=c}if(s!==o.totalNodes)return a(`layout changed`);let c=performance.now(),l=await Lh(this.triangles,e);for(let t=0;t<e.length;t++)if(l[t]!==o.templates[t][6])return a(`triangles changed`);let u=performance.now();try{let t=new Map,n=[];for(let r=0;r<e.length;r++){let[a,s,c,l,,u,,d]=o.templates[r],f=await Vh(i.order,u,c);this._permuteRange(s,c,f),t.set(a,f),n.push({m:e[r].m,range:e[r].range,result:{bvhData:new Float32Array(Uint32Array.from(d).buffer),originalToBvh:null,nodeCount:l}})}return this._blasRestored=!0,this.performanceMetrics.blasRestore={checksumMs:u-c,permuteMs:performance.now()-u},mg.debug(`restored ${J.n(e.length)} stored BLASes`),{results:n,orders:t,nodes:i.nodes,release:i.release}}catch(e){throw i.release(),e}}_writeInOrder(e,t,n){let r=this.triangles,i=r.lanesPerRecord;for(let a=0,o=n.length;a<o;){let s=r.chunkFor(e+a),c=Math.min(o,(((e+a)/r.recordsPerChunk|0)+1)*r.recordsPerChunk-e);for(let o=r.baseOf(e+a);a<c;a++,o+=i){let e=n[a]*i;for(let n=0;n<i;n++)s[o+n]=t[e+n]}}}_permuteRange(e,t,n){let r=!0;for(let e=0;e<t&&r;e++)r=n[e]===e;if(r)return;let i=this.triangles.lanesPerRecord,a=this.triangles.slice(e,t),o=new a.constructor(a.length);if(i===20)for(let e=0,r=0;e<t;e++,r+=20){let t=n[e]*20;o[r]=a[t],o[r+1]=a[t+1],o[r+2]=a[t+2],o[r+3]=a[t+3],o[r+4]=a[t+4],o[r+5]=a[t+5],o[r+6]=a[t+6],o[r+7]=a[t+7],o[r+8]=a[t+8],o[r+9]=a[t+9],o[r+10]=a[t+10],o[r+11]=a[t+11],o[r+12]=a[t+12],o[r+13]=a[t+13],o[r+14]=a[t+14],o[r+15]=a[t+15],o[r+16]=a[t+16],o[r+17]=a[t+17],o[r+18]=a[t+18],o[r+19]=a[t+19]}else for(let e=0;e<t;e++){let t=n[e]*i,r=e*i;for(let e=0;e<i;e++)o[r+e]=a[t+e]}this.triangles.setRecords(e,o)}async _storeBLASes(e){let t=Fu(Ks().cacheNamespace),n=this.instanceTable;if(!t||!n||!this.bvh)return!1;let r=this._blasKey,i=this._geometryVersion,a=()=>this._geometryVersion!==i||this._blasKey!==r,o=[];for(let e=0;e<n.templateCount;e++){let t=n.tplOwner[e];t<0||n.sourceMesh[t]!==e||o.push({t:e,triOffset:n.tplTriOffset[e],triCount:n.tplTriCount[e],nodeCount:n.tplNodeCount[e],blasOffset:n.tplBlasOffset[e]})}let s=await Lh(this.triangles,o);if(a())return!1;let c=e=>{let t=this.bvhIndexChunks.chunkFor(e),n=this.bvhIndexChunks.baseOf(e);return Array.from(t.subarray(n,n+16))},l=0,u=[],d=o.map((e,t)=>{u.push(n.bvhToOriginal.get(e.t)??Uint32Array.from({length:e.triCount},(e,t)=>t));let r=[e.t,e.triOffset,e.triCount,e.nodeCount,e.blasOffset,l,s[t],c(e.blasOffset)];return l+=e.triCount,r}),f=await zh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&mg.debug(`stored ${J.n(o.length)} BLASes for the next load`),f}async _beginProgressiveSpill(e){let{storage:t,uploader:n}=this._progressive,r=this.triangles,i=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,a=r.recordsPerChunk*r.lanesPerRecord*r.LaneType.BYTES_PER_ELEMENT,o=await ur.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await ur.create(t,`${i}:blas`,0,{label:`BLAS nodes (while building)`});if(!s)return await o?.dispose(),null;let c={key:i,triStore:o,blasStore:s,bvhStore:null,blasBytes:0,blasAt:new Map,pending:new Int32Array(r.chunks.length),emitterChunks:new Set,isEmitter:e=>{let t=this.materials[e];return(t?.emissiveIntensity??0)>0&&!!t.emissive&&(t.emissive.r>0||t.emissive.g>0||t.emissive.b>0)},uploadTriangles:n(r,`triangles`),chain:Promise.resolve(),error:null};this._spillStores=[o],this._blasKey=null;for(let{triOffset:t,triCount:n}of e)this._forEachChunk(r,t,n,e=>c.pending[e]++);for(let e=0;e<r.chunks.length;e++)c.pending[e]===0&&this._finishTriangleChunk(c,e);return c}_forEachChunk(e,t,n,r){if(n<=0)return;let i=(t+n-1)/e.recordsPerChunk|0;for(let n=t/e.recordsPerChunk|0;n<=i;n++)r(n)}_onBLASBuilt(e,t,n,r){let i=this.instanceTable,a=r.bvhData;i.tplTriOffset[t]=n.start,i.tplTriCount[t]=n.count,i._readRootAABB(hg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=gg(a),e.blasAt.set(t,o),r.nodeCount=gg(a)/64,r.bvhData=null,this._queueSpill(e,()=>vg(e.blasStore,o,a)),this._forEachChunk(this.triangles,n.start,n.count,t=>{--e.pending[t]===0&&this._finishTriangleChunk(e,t)})}_queueSpill(e,t){e.chain=e.chain.then(t).catch(t=>{e.error??=t})}_finishTriangleChunk(e,t){this._queueSpill(e,async()=>{let n=this.triangles,r=n.chunks[t];if(!r)return;e.uploadTriangles(t);let i=n.lanesPerRecord;for(let n=W.MATERIAL_FLAGS_OFFSET;n<r.length;n+=i)if(e.isEmitter(r[n]&16777215)){e.emitterChunks.add(t);return}await n.spillChunk(t,e.triStore)})}async _readSpilledBLAS(e,t){let n=e.blasAt.get(t);if(n===void 0)return null;let r=this.instanceTable.tplNodeCount[t]*64,i=[];for(let t=0;t<r;t+=_g)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(_g,r-t))));return i}async _beginBVHSpill(e,t){let{storage:n,uploader:r}=this._progressive,i=this.bvh,a=i.recordsPerChunk*i.lanesPerRecord*i.LaneType.BYTES_PER_ELEMENT,o=await ur.create(n,`${e.key}:bvh`,a,{label:`BLAS nodes`,expectedBytes:i.recordCount*64}),s=r(i),c=Math.ceil(t/i.recordsPerChunk);o&&this._spillStores.push(o);let l=c;return async(e,t=!1)=>{for(;l<i.chunks.length&&(t||(l+1)*i.recordsPerChunk<=e);)i.chunks[l]||i._materialize(l),s(l),o&&await i.spillChunk(l,o),l++;if(t)for(let e=0;e<Math.min(c,i.chunks.length);e++)i.chunks[e]||i._materialize(e),s(e)}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=e,o=e+t;a<o;){let e=i.chunkFor(a),t=Math.min(o,((a/i.recordsPerChunk|0)+1)*i.recordsPerChunk),s=i.baseOf(a);Ep(e,n,r,s,s+(t-a)*16),a=t}}_buildBLASesWithPool(e,t,n,r=null){let i=this._blasPool(t,n,r);for(let t of e)i.submit(t);return i.close()}_blasPool(e,t,n=null,r=this.config.maxConcurrentTextureTasks||4){let i=[],a=[],o=[],s=[],c=!1,l=0,u=0,d=null,f,p=new Promise((e,t)=>f={resolve:e,reject:t});p.catch(()=>{});let m=e=>{d||(d=e,o.forEach(e=>e.terminate()),f.reject(e))},h=()=>{d||!c||i.length>0||l>0||(o.forEach(e=>e.terminate()),f.resolve(a))},g=t=>{let n=i.shift();if(!n){s.push(t),h();return}let{m:r,range:a}=n;l++;try{let n=this.triangles.copyOf(a.start,a.count),i=a.count,o=i<=500?{...e.treeletOptimization,enabled:!1}:e.treeletOptimization;t._currentTask={m:r,range:a},t.postMessage({triangleData:n.buffer,triangleByteOffset:n.byteOffset,triangleByteLength:n.byteLength,triangleCount:i,depth:e.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:o,reinsertionOptimization:e.reinsertionOptimization,maxLeafSize:e.maxLeafSize,foldLeaves:e.foldLeaves,numBins:e.numBins,maxBins:e.maxBins,minBins:e.minBins,logLevel:e.logLevel},[n.buffer])}catch(e){m(e)}},_=(e,r)=>{let i=r.data;if(i.error){m(Error(i.error));return}if(i.progress!==void 0)return;let{m:o,range:s}=e._currentTask;l--;try{i.triangles&&this.triangles.setRecords(s.start,i.triangles);let e={bvhData:i.bvhData,originalToBvh:i.originalToBvh||null,splitStats:i.treeletStats||null};n?.(o,s,e),a.push({m:o,range:s,result:e})}catch(e){m(e);return}u++,t?.(u),g(e)},v=()=>{let e=ii(cm);return e.onmessage=t=>_(e,t),e.onerror=e=>m(e),o.push(e),e};return{submit(e){if(!d){i.push(e);try{let e=s.pop()??(o.length<r?v():null);e&&g(e)}catch(e){m(e)}}},close(){return c=!0,h(),p},abort(e){m(e??Error(`BLAS pool aborted`))},get pending(){return i.length+l},get error(){return d}}}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw mg.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Xe.MATERIAL_BUCKET_COUNT,n=Xe.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps],o=it(r(i),e,t),s=it(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(Y.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=at(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return ot(o,c);if(t[o].length>=n)return mg.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Y.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=ot(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){mg.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw mg.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=bn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(this._geometryVersion=(this._geometryVersion??0)+1,this._tlasLeafBoxesOf=null,!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=ii(rg),!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable,a=W.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(this._geometryVersion=(this._geometryVersion??0)+1,!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new am;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(Y.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16);this._movedPlacements?.length!==n.count&&(this._movedPlacements=new Uint8Array(n.count));let i=this._movedPlacements,a=0;for(let t of e){let e=this.meshes?.[t],o=n.placementRunOf(t);if(!e||!o)continue;e.updateMatrixWorld(!0);let s=e.matrixWorld.elements,c=e.isInstancedMesh?this._ownInstanceMatrices(e):null,l=n.tplBakeInverse?.get(n.sourceMesh[o.start])??null;for(let e=0;e<o.count;e++){let t=o.start+e;n.isSet[t]&&(c?(Cm(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(Cm(s,l,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,s),this._writeLeafMatrix(t),i[t]=1,a++)}}return this._refitTLAS(i),i.fill(0),{refitTimeMs:performance.now()-t,placements:a}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Fm.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=W.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):mg.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&(e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this._releaseBitTrailMap()),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n,{keepUserLights:i}),!0):(mg.error(`failed to get BVH data`),!1)):(mg.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower;let e=this.emissiveBitTrailMap;return this._releaseBitTrailMap(),{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:e,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}get spilled(){return!!(this.triangles?.spilledChunks||this.bvh?.spilledChunks)}async spillToDisk(e){let t=this.triangles,n=this.bvh;if(!e||this.spilled||this._spillStores||!t?.chunks||t.chunks.length<2||!n?.chunks)return null;await this._blasStoring;let r=this._geometryVersion,i=performance.now(),a=`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`,o=e=>e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,s=await ur.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await ur.create(e,`${a}:bvh`,o(n),{label:`BLAS nodes`,expectedBytes:n.byteLength});if(!s||!c)return await s?.dispose(),null;this._spillStores=[s,c];let l=Math.ceil((this.instanceTable?.tlasNodeCount??1)/n.recordsPerChunk),u=await t.spill(s);if(u+=await n.spill(c,{keep:e=>e<l}),await s.flush(),await c.flush(),r!==this._geometryVersion)return null;let d=performance.now()-i;return mg.info(`spilled ${(u/1048576).toFixed(0)} MB of triangles and BLAS nodes to disk in ${d.toFixed(0)} ms`),{bytes:u,ms:d}}ensureResident(){return this._paging??=(async()=>{await this.triangles?.ensureResident?.(),await this.bvh?.ensureResident?.(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes)return;z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Tr(e),mg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&mg.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,e?.dispose().catch(()=>{})}_disposeSpill(){let e=this._spillStores;this._spillStores=null;for(let t of e??[])t.dispose().catch(()=>{})}_releaseBitTrailMap(){this.emissiveBitTrailMap=null,this.emissiveTriangleBuilder&&(this.emissiveTriangleBuilder.emissiveBitTrailMap=null)}async _buildTLAS(e){let t=e.count;if(t>=sg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Fm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,mg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ii(og);let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:bt()},[e.buffer])})}_setBVHData(e){this._tlasLeafBoxesOf=null;let t=e?e instanceof bn?e:bn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=W.FLOATS_PER_TRIANGLE,n=e?e instanceof bn?e:bn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=W.POSITION_A_OFFSET,r=W.POSITION_B_OFFSET,i=W.POSITION_C_OFFSET,a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=wm(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=Be(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=W.NORMAL_A_PACKED_OFFSET,o=W.NORMAL_B_PACKED_OFFSET,s=W.NORMAL_C_PACKED_OFFSET,c=r,l=!c||wm(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=Be(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<t*6)&&(this._tlasBounds=new Float32Array(t*6),this._tlasLeafBoxesOf=null);let n=this.instanceTable,r=e&&this._tlasLeafBoxesOf===n;for(let i=t-1;i>=0;i--){let t=this.bvhIndexChunks.chunkFor(i),a=this.bvh.chunkFor(i),o=this.bvh.baseOf(i),s=t[o+3];if(s===Ke.BLAS_POINTER_LEAF){let a=t[o+1]&Ge;a<n.count&&!(r&&!e[a])&&n.writeWorldAABB(a,this._tlasBounds,i*6)}else if(s<Ke.TRIANGLE_LEAF){let e=s,n=t[o+7],r=e*6,c=n*6,l=this._tlasBounds;a[o]=l[r],a[o+1]=l[r+1],a[o+2]=l[r+2],a[o+4]=l[r+3],a[o+5]=l[r+4],a[o+6]=l[r+5],a[o+8]=l[c],a[o+9]=l[c+1],a[o+10]=l[c+2],a[o+12]=l[c+3],a[o+13]=l[c+4],a[o+14]=l[c+5];let u=i*6;l[u]=Math.min(l[r],l[c]),l[u+1]=Math.min(l[r+1],l[c+1]),l[u+2]=Math.min(l[r+2],l[c+2]),l[u+3]=Math.max(l[r+3],l[c+3]),l[u+4]=Math.max(l[r+4],l[c+4]),l[u+5]=Math.max(l[r+5],l[c+5])}}this._tlasLeafBoxesOf=n}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){mg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{mg.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,ii(cm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){mg.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._geometryVersion=(this._geometryVersion??0)+1,this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},xg=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],Sg=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],Cg=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function wg(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=xg[i],o=Sg[i],s=Cg[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}var Tg=1/(4*Math.PI);function Eg(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=wg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Lr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Dg=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=Eg(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=Eg(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=Eg(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Tg,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=Eg(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*Tg,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}};jt();var Og=1<<18,kg=vt(`pathtracer`),Ag=100,jg=4,Mg=class extends P{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:N.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new bg,this.lightSerializer=new Dg,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ft(0,0),this.uniforms=new nn(a,o),this._defineUniformGetters(),this.materialData=new Yr(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this._triangleFlat,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleShadeAttr&&this._uploadTriangles(0,this._triangleRecordCount,{geo:!1})},this.environment=new Ju(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new up,this._initRenderingState(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.tracedFrames=0,this.resetCount=0,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._bitTrailOffset=0,this._bitTrailLength=0,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new F(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/12)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/16)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/20)):this.numSpotLights.value=0}reset(){this.resetCount++,this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,(this._pinSeedToFrame||this._lockstep)&&(this._seedTick=0)}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Ag}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,t){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount:Math.ceil(i.length/W.FLOATS_PER_TRIANGLE),o=r?._gpuUpload?.triangles?r._gpuUpload:null,{geo:s,shade:c}=o??this._allocateTriangleBuffers(a);this.triangleStorageNode?(this.triangleStorageNode.geo.value=s,this.triangleStorageNode.geo.bufferCount=s.count,this.triangleStorageNode.shade.value=c,this.triangleStorageNode.shade.bufferCount=c.count):this.triangleStorageNode={geo:(0,n.storage)(s,`uvec4`,s.count).toReadOnly(),shade:(0,n.storage)(c,`uvec4`,c.count).toReadOnly()},this.triangleGeoAttr=s,this.triangleShadeAttr=c,this._triangleRecords=r,this._triangleFlat=i,this._triangleRecordCount=a,this.triangleCount=t,this._uploadTriangles(0,a,{skipChunks:o?.uploaded}),kg.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}_allocateTriangleBuffers(e){let t=Math.max(1,e);this._assertFitsGPU(t*3*16);let n=S(t*3,4,Uint32Array),r=S(t*2,4,Uint32Array);return this.renderer.backend.createStorageAttribute(n),this.renderer.backend.createStorageAttribute(r),{geo:n,shade:r}}_uploadTriangles(e,t,{geo:n=!0,shade:r=!0,skipChunks:i=null,source:a=null,sourceStart:o=0,geoAttr:s=this.triangleGeoAttr,shadeAttr:c=this.triangleShadeAttr}={}){if(t<=0||!s)return;let l=this.renderer.backend,u=l.get(s).buffer,d=l.get(c).buffer,f=W.FLOATS_PER_TRIANGLE,p=this._triangleRecords,m=a?t:p?p.recordsPerChunk:this._triangleRecordCount,h=Og;this._triangleStaging??={geo:new Uint32Array(h*12),shade:new Uint32Array(h*8)};let g=this._triangleStaging.geo,_=this._triangleStaging.shade;for(let s=e,c=e+t;s<c;){let t=a?0:Math.floor(s/m),v=a?e:t*m,y=Math.min(c,v+m);if(i?.has(t)){s=y;continue}let b=a??(p?p.chunks[t]:this._triangleFlat);if(!b)throw Error(`triangle chunk ${t} is on disk and was never uploaded`);let x=Math.min(h,y-s),S=(a?s-e+o:s-v)*f;for(let e=0,t=0,i=0;e<x;e++,S+=f){if(n)for(let e=0;e<12;e++)g[t++]=b[S+e];if(r)for(let e=12;e<f;e++)_[i++]=b[S+e]}n&&l.device.queue.writeBuffer(u,s*12*4,g,0,x*12),r&&l.device.queue.writeBuffer(d,s*8*4,_,0,x*8),s+=x}}createChunkUploader(e){this._assertFitsGPU(e.recordCount*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT);let t=S(e.recordCount*e.lanesPerRecord/4,4,e.LaneType),n=this.renderer.backend;n.createStorageAttribute(t);let r=n.get(t).buffer,i=e.recordsPerChunk*e.lanesPerRecord*e.LaneType.BYTES_PER_ELEMENT,a=new Set;return e._gpuUpload={attr:t,uploaded:a},t=>{let o=e.chunks[t];n.device.queue.writeBuffer(r,t*i,o,0,o.length),a.add(t)}}createTriangleChunkUploader(e){let{geo:t,shade:n}=this._allocateTriangleBuffers(e.recordCount),r=new Set;e._gpuUpload={triangles:!0,geo:t,shade:n,uploaded:r};let i=e.recordsPerChunk;return a=>{let o=a*i,s=Math.min(i,e.recordCount-o);this._uploadTriangles(o,s,{source:e.chunks[a],geoAttr:t,shadeAttr:n}),r.add(a)}}_assertFitsGPU(e){let t=this.renderer?.backend?.device?.limits,n=Math.min(t?.maxBufferSize??1/0,t?.maxStorageBufferBindingSize??1/0);if(e>n)throw Error(`the scene needs a ${J.mb(e)} GPU buffer, past the ${J.mb(n)} this GPU allows for one — load fewer triangles`)}_uploadChunked(e,t){let n=t._gpuUpload;if(!n||n.attr!==e){w(this.renderer,e,t.chunks);return}let r=this.renderer.backend.get(e).buffer,i=t.recordsPerChunk*t.lanesPerRecord*t.LaneType.BYTES_PER_ELEMENT;for(let e=0;e<t.chunks.length;e++){if(n.uploaded.has(e))continue;let a=t.chunks[e];if(!a)throw Error(`chunk ${e} is on disk and was never uploaded`);this.renderer.backend.device.queue.writeBuffer(r,e*i,a,0,a.length),n.uploaded.add(e)}}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=r?r.recordCount*r.lanesPerRecord:i.length,o=a/4;this._assertFitsGPU(a*4);let s=()=>r?r._gpuUpload?.attr??S(o,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=s(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=o):(this.bvhStorageAttr=s(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,o).toReadOnly()),this.bvhStorageAttr.foldedLeaves=e.foldedLeaves===!0,this._bvhRecords=r,r&&this._uploadChunked(this.bvhStorageAttr,r),this.bvhNodeCount=Math.floor(o/jg),kg.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){let e=1/0,t=-1;for(let n of this._dirtyBVHLeaves??[])n<e&&(e=n),n>t&&(t=n);t>=0&&(this.bvhStorageAttr.addUpdateRange(e*16,(t-e+1)*16),this.bvhStorageAttr.version++),this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.clearUpdateRanges(),e.needsUpdate=!0)}updateTriangleData(e,t){e?.chunks?.length>1?this._triangleRecords=e:e&&(this._triangleFlat=e.chunks?e.chunks[0]:e),t?this.updateBufferRanges(t,[]):this._uploadTriangles(0,this._triangleRecordCount)}updateBVHData(e,t){if(this._bvhRecords){e?.chunks?.length>1&&(this._bvhRecords=e),t?this.updateBufferRanges([],t):w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}let n=e?.chunks?e.chunks[0]:e;if(!t){this._updateStorageBuffer(this.bvhStorageAttr,n);return}let r=this.bvhStorageAttr?.array;if(n&&r&&n!==r)for(let e of t)r.set(n.subarray(e.offset,e.offset+e.count),e.offset);this.updateBufferRanges([],t)}updateBufferRanges(e,t){if(this.triangleGeoAttr&&e.length>0){let t=W.FLOATS_PER_TRIANGLE;for(let n of e){let e=Math.floor(n.offset/t);this._uploadTriangles(e,Math.ceil((n.offset+n.count)/t)-e)}}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){kg.error(`triangle data required`);return}if(!this.bvhStorageNode){kg.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e){let t=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=t,this.accumulationEnabled?t?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=de(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=ue(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(){}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this.lightStorageAttr?.array,i=this._bitTrailMapCache??(r&&this._bitTrailLength?r.slice(this._bitTrailOffset,this._bitTrailOffset+this._bitTrailLength):null);this._bitTrailMapCache=null;let a=e?e.length:0,o=n?n.length:0,s=i?Math.ceil(i.length/4)*4:0,c=Math.max(a+o+s,4);if(this.lightStorageAttr&&c<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,a),i&&t.set(i,a+o),this.lightStorageAttr.needsUpdate=!0}else{let r=new Float32Array(c);e&&r.set(e,0),n&&r.set(n,a),i&&r.set(i,a+o),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=r.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(a+o)/4,this._bitTrailOffset=a+o,this._bitTrailLength=i?i.length:0}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),kg.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),kg.debug(`light BVH ${J.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{kg.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),kg.debug(`material rebuild complete`)}catch(e){kg.error(`material rebuild failed:`,e);try{kg.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){kg.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.placeholderTexture?.dispose(),this.triangleGeoAttr=null,this.triangleShadeAttr=null,this._triangleStaging=null,this._triangleRecords=null,this._triangleFlat=null,this._triangleRecordCount=0,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};jt();var Ng=vt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},Pg=65535,Fg={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18,SUN_NEE:1<<19,UNDER_SURFACE:1<<20},Ig=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Ng.debug(`queues capacity ${J.n(e)} · ${J.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){ya(this._renderer,this._countersAttr),ya(this._renderer,this._bounceCountsAttr),ya(this._renderer,this._attrA),ya(this._renderer,this._attrB),ya(this._renderer,this._sortAttr),ya(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Lg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Rg={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function zg(e){return(Lg[e.format]??4)*(Rg[e.type]??4)}function Bg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Vg(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*zg(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*zg(e)}var Hg=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*zg(e));return a}return this._isResident(e)?Vg(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};jt();var Ug=vt(`wavefront`),Wg=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);Ug.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>Ug.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);if(!n)return;let r=Math.ceil(t/n.workgroupSize[0]),i=this.renderer?.backend?.device?.limits.maxComputeWorkgroupsPerDimension??65535;n.dispatchSize=r>i?[i,Math.ceil(r/i),1]:[r,1,1]}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},Gg=(0,n.int)(Se.equirectangular),Kg=(0,n.int)(Se.orthographic),qg=e=>e.equal(Kg);function Jg(){let e={cameraProjection:(0,n.uniform)(0,`int`),panoLonRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLatRange:(0,n.uniform)(new r.Vector2,`vec2`),panoLevelHorizon:(0,n.uniform)(1,`int`),sync(t){e.cameraProjection.value=t.get(`cameraProjection`).value,e.panoLonRange.value.copy(t.get(`panoLonRange`).value),e.panoLatRange.value.copy(t.get(`panoLatRange`).value),e.panoLevelHorizon.value=t.get(`panoLevelHorizon`).value}};return e}var Yg=(e,t,n,r)=>({origin:Zg(e,t,n,r.cameraProjection),direction:Qg(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),Xg=(e,t,n,r,i)=>{let{origin:a,direction:o}=Yg(e,n,r,i);return a.add(o.mul(t))},Zg=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(qg(i),()=>{let i=r.mul((0,n.vec4)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),0,1));a.assign(t.mul((0,n.vec4)(i.xy,0,1)).xyz)}),a}),Qg=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Gg),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).ElseIf(qg(i),()=>{c.assign((0,n.normalize)((0,n.vec3)(t[2])).negate())}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),$g=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=Zg(e,r,i,a).toVar(),y=Qg(e,r,i,a,o,s,c).toVar(),b=v.toVar(),x=y.toVar(),S=g.equal((0,n.int)(1)),C=S.and(_.greaterThan(0)).or(S.not().and(u.greaterThan(0)).and(d.lessThan(64)));return(0,n.If)(l.and(C).and(f.greaterThan(.001)),()=>{let e=(0,n.select)(a.equal(Gg),s.y.sub(s.x).mul(.5),(0,n.select)(qg(a),(0,n.float)(1),i[1].y)),o=(0,n.select)(S,_.mul(f).mul(e),u.div(d.mul(2)).mul(.001).mul(p).mul(m)),c=Ht(t),l=c.x.mul(h.max(.01)),g=c.y,C=(0,n.vec3)(0).toVar(),w=f.toVar();(0,n.If)(a.equal(Gg),()=>{C.assign(Gi({N:y}).mul((0,n.vec3)(l,g,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));C.assign(e.mul(l).add(t.mul(g))),w.assign(f.div((0,n.dot)(y,(0,n.normalize)((0,n.vec3)(r[2]))).negate()))}),b.assign(v.add(C.mul(o))),x.assign((0,n.normalize)(v.add(y.mul(w)).sub(b)))}),ui({origin:b,direction:x})});function e_(e){let{rayBufferRW:t,hitBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,unitsPerMetre:_,apertureScale:v,anamorphicRatio:y,dofMode:b,dofBlur:x,renderWidth:S,chunkRowBase:C,chunkRows:w,transmissiveBounces:T,auxGBufferEnabled:E,listDriven:D=!1,activeIndicesRO:O=null,counters:k=null}=e,A=E.greaterThan((0,n.uint)(0)),j=(e,S,C)=>{let w=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(S).add(.5)),E=Rt({state:en({pixelCoord:w,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),D=$t(w,(0,n.int)(1),E,a,o).toVar().sub(.5),O=(0,n.vec2)(w.x.add(D.x),w.y.sub(D.y)).div(a),k=ui.wrap($g(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ia(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),La(t,C,k.direction,(0,n.uint)(Fg.ACTIVE)),Ra(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),za(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Oa(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),ro(t,C,(0,n.vec3)(1))}),Za(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Ja(r,C,E)};return(0,n.Fn)(()=>{if(D){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(k.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(O.element(e)),r=t.add(C.mul(S));j(r.mod(S),r.div(S),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(S).and(t.lessThan(w)),()=>{j(e,t.add(C),(0,n.uint)(t.mul(S).add(e)))})}})}var t_=32,n_=4096,r_=4,i_=1e8,a_=()=>(0,n.array)(`int`,t_).toVar(),o_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),s_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),c_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),l_=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(i_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},u_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),d_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),f_=(0,n.wgslFn)(`
716
716
  fn RayTriangleGeometry( rayOrigin: vec3f, rayDir: vec3f, pA: vec3f, pB: vec3f, pC: vec3f, closestHitDst: f32, woopParams: vec4f ) -> vec4f {
717
717
 
718
718
  // Returns vec4(t, u, v, hit) where hit > 0.5 means intersection.
@@ -892,7 +892,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
892
892
  let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
893
893
  return clamp( ndcDepth, 0.0f, 1.0f );
894
894
  }
895
- `),$v=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=ui({origin:e,direction:t}),y=hi.wrap(y_(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=M_({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Fi).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=di.wrap(na(y.materialIndex,a)).toVar(),r=Si.wrap(Af(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(Zv({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Qv({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Xv({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=Rt({state:zt({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Id({N:d,xi:(0,n.vec2)(Vt(p).toVar(),Vt(p).toVar())}).toVar(),h=ui({origin:Ei(y.hitPoint,d),direction:m}),v=hi.wrap(y_(h,r,i,(0,n.bool)(!1),(0,n.bool)(!1)).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(M_({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=di.wrap(na(v.materialIndex,a)).toVar(),t=Si.wrap(Af(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=M_({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=M_({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=M_({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function ey(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,unitsPerMetre:b,apertureScale:x,anamorphicRatio:S,dofMode:C,dofBlur:w,bvhBuffer:T,triangleBuffer:E,materialBuffer:D,envTexture:O,environmentMatrix:k,environmentIntensity:A,enableEnvironmentLight:j,visMode:M,debugVisScale:N,frame:P}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),F=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(F.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(F).add(.5)),s=Rt({state:(0,n.uint)(F.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),I=ui.wrap($g(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S,C,w)),L=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(M.equal((0,n.int)(9)),()=>{let e=$t(o,(0,n.int)(0),s,a,P);L.assign((0,n.vec4)(e,1,1))}).Else(()=>{L.assign($v(I.origin,I.direction,T,E,D,O,k,A,j,M,N,o,a,u,d,P))});let R=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(F));(0,n.textureStore)(t,R,L).toWriteOnly(),(0,n.textureStore)(r,R,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,R,(0,n.vec4)(L.xyz,1)).toWriteOnly()})})}function ty({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function ny({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)($.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Wa(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function ry({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function iy({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)($.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(Wa(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}jt();var ay=vt(`wavefront`),oy=256,sy=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],cy=class extends Mg{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lockstep=!1,this._lockstepRead=null,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this.hostMemoryGB=i.hostMemoryGB,this._chunkRows=0,this._numChunks=1,this.vramTracker=new Hg(this.renderer),this._registerVRAMProviders(),ay.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleGeoAttr,this.triangleShadeAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;let t=this._lockstepRead;if(t&&this.frameCount>=t.due){if(!t.apply)return;this._lockstepRead=null,t.apply()}if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let n=this.frameCount,r=this.renderMode.value,i=null;r===1&&n===0&&(i=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(r),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(n);let a=this._updateAuxAccumulationUniforms(n);this.frame.value=n,this.seedFrame.value=this._seedTick++,this.tracedFrames++,this._setWfDispatch();let o=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=o.color,this.shaderBuilder.prevAlbedoTexNode.value=o.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=o.normalDepth),this._refreshWfTextureNodes();let s=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){s.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end();return}let c=this.maxBounces.value,l=this._bounceLoopBound(),u=this._wfRenderHeight.value,d=this._chunkRows,f=this._numChunks<=1;l>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let p=this._lastBounceCounts,m=c<=this._lastBounceCountsBudget&&l<=this._lastBounceCountsLoopBound,h=f&&p?m?l+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0;for(let e=0,t=0;t<u;t+=d,e++){let r=Math.min(d,u-t),i=this._setChunk(t,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,o=f&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(o*1.5)+1024);s.setDispatchForCount(`generateList`,e),s.dispatch(`resetFrameCounters`),s.dispatch(`buildActivePixels`),s.dispatch(`seedEnter`),s.dispatch(`generateList`)}else s.dispatch(`generate`),s.dispatch(`initActiveIndices`);e===0&&n>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&s.dispatch(`countConvergedDilated`);let c=this._lastBounceEnergy,m=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=l;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(f&&e>0&&this._curveSizingValid){let n=e-1,r;n<h&&p[n]!==void 0?r=p[n]:h>0&&(r=p[h-1]),t=r>0?r:i}else e===0&&a&&(t=o);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of sy)s.setDispatchForCount(e,n)}else{s.dispatch(`enterFull`);for(let e of sy)s.setDispatchForCount(e,i)}if(s.dispatch(`extend`),this._sortMaterials&&(s.dispatch(`resetGlobalHist`),s.dispatch(`globalHist`),s.dispatch(`globalPrefix`),s.dispatch(`globalScatter`)),s.dispatch(`shade`),s.dispatch(`compact`),t?s.dispatch(`compactCopyback`):s.dispatch(`snapshotBounceCount`),m>=0&&e<h&&e<l&&c?.[e]!==void 0&&c[e]<=m)break}s.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let g=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,g),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=a?this._auxSamples+1:1),this._auxSeedPending=!1,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}async captureAccumulation(){let e=this.storageTextures,t=e.renderWidth,n=e.renderHeight,r=t*n,i=async i=>{let a=await this.renderer.readRenderTargetPixelsAsync(e.readTarget,0,0,t,n,i),o=Math.ceil(t*16/256)*64;if(o===t*4)return new Float32Array(a.buffer,a.byteOffset,r*4).slice();let s=new Float32Array(r*4);for(let e=0;e<n;e++)s.set(a.subarray(e*o,e*o+t*4),e*t*4);return s},a=async(e,t)=>e?new t(await this.renderer.getArrayBufferAsync(e,null,0,r*4)):null,o=this._auxGBufferEnabled&&this._auxSamples>0,s={frameCount:this.frameCount,seedTick:this._seedTick,auxSamples:o?this._auxSamples:0,convergedFraction:this._convergedFraction,convergedGeometryFraction:this._convergedGeometryFraction,isComplete:this.isComplete},c=[i(0),o?i(1):null,o?i(2):null,a(this._m2Attr,Float32Array),a(this._streakAttr,Uint32Array),a(this._frozenMaskAttr,Uint32Array)],[l,u,d,f,p,m]=await Promise.all(c);return{width:t,height:n,state:s,color:l,normalDepth:u,albedo:d,m2:f,streak:p,frozenMask:m}}restoreAccumulation(e){let t=this.storageTextures,{width:n,height:r,state:i}=e;if(t.renderWidth!==n||t.renderHeight!==r)throw Error(`checkpoint is ${n}×${r}; the render is ${t.renderWidth}×${t.renderHeight}`);let a=this.renderer.backend,o=a.device;a.get(t.readTarget.textures[0]).texture||this.renderer.initRenderTarget(t.readTarget);let s=(e,i)=>o.queue.writeTexture({texture:a.get(t.readTarget.textures[e]).texture},i,{bytesPerRow:n*16,rowsPerImage:r},{width:n,height:r}),c=(e,t)=>{e&&t&&o.queue.writeBuffer(a.get(e).buffer,0,t)};s(0,e.color),e.normalDepth&&s(1,e.normalDepth),e.albedo&&s(2,e.albedo),c(this._m2Attr,e.m2),c(this._streakAttr,e.streak),c(this._frozenMaskAttr,e.frozenMask),this.frameCount=i.frameCount,this.frame.value=i.frameCount,this._seedTick=i.seedTick,this.hasPreviousAccumulated.value=+(i.frameCount>0),this._auxSamples=e.normalDepth?i.auxSamples:0,this._auxSeedPending=this._auxGBufferEnabled&&!e.normalDepth,this._convergedFraction=i.convergedFraction??0,this._convergedGeometryFraction=i.convergedGeometryFraction??0,this.isComplete=!1}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1,this._lockstep&&(this._lockstepRead=null,this._readbackGeneration++,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._curveSizingValid=!1)}setLockstepReadbacks(e){e=!!e,e!==this._lockstep&&(this._lockstep=e,this._lockstepRead=null,this._readbackGeneration++)}get lockstepReadbacks(){return this._lockstep}readbackWait(){let e=this._lockstepRead;return e&&!e.apply&&this.frameCount>=e.due?e.read:null}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()?!1:this._lockstep?!this._lockstepRead&&this.frameCount%this._readbackEveryNFrames===0:this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value}_maybeReadbackCounters(){if(this._lockstep){this._issueLockstepReadback();return}if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&this._applyBounceCounts(e,n,r,i),this._readbackPending=!1}).catch(e=>{ay.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&n>0&&this._applyCounters(e,n),this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_issueLockstepReadback(){if(this._lockstepRead||this.frameCount%this._readbackEveryNFrames!==0||this.cameraChanged||this.cameraOptimizer?.isInInteractionMode())return;let e=this._queueManager?.getBounceCountsAttribute(),t=this._queueManager?.getCountersAttribute();if(!e||!t)return;let n=this._readbackGeneration,r=this.maxBounces.value,i=this._bounceLoopBound(),a=this._queueManager.MAX_BOUNCE_SNAPSHOTS,o=this._wfRenderWidth.value*this._wfRenderHeight.value,s={due:this.frameCount+this._readbackEveryNFrames,read:null,apply:null};s.read=Promise.all([this.renderer.getArrayBufferAsync(e),this.renderer.getArrayBufferAsync(t)]).then(([e,t])=>{s.apply=()=>{n===this._readbackGeneration&&(this._applyBounceCounts(e,r,i,a),o>0&&this._applyCounters(t,o))}},e=>{ay.warn(`lockstep readback failed:`,e),s.apply=()=>{}}),this._lockstepRead=s}_applyBounceCounts(e,t,n,r){let i=new Uint32Array(e.slice(0));this._lastBounceCounts=i.subarray(0,r),this._lastBounceEnergy=i.subarray(r,2*r),this._lastBounceCountsBudget=t,this._lastBounceCountsLoopBound=n,this._curveSizingValid=!0}_applyCounters(e,t){let n=new Uint32Array(e);this._convergedFraction=n[$.CONVERGED_COUNT]/t;let r=n[$.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?n[$.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=n[$.ACTIVE_PIXEL_COUNT]}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(hf(e.srgbBuckets,n.srgbBuckets),hf(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=Hm(this.hostMemoryGB).gb*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/192),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,U),t=Math.min(this.storageTextures.renderHeight||1,U);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t;this._packedBuffers?this._packedBuffers.resize(i):this._packedBuffers=new ba(i,this.renderer);let o=i*1;ya(this.renderer,this._gBufferAttr),this._gBufferAttr=S(o,4,Uint32Array);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),l=U*U;(!this._m2Attr||this._m2Attr.count<l)&&(ya(this.renderer,this._m2Attr),this._m2Attr=S(l,1),ya(this.renderer,this._streakAttr),this._streakAttr=S(l,1,Uint32Array),ya(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=S(l,1,Uint32Array));let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Ig(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new Wg(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,v=this.shaderBuilder.prevAlbedoTexNode,y=this.shaderBuilder.prevNormalDepthTexNode,b=this.storageTextures.getWriteTextures(),x=g.getCounters(),C=g.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),C.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=g.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*t/oy),1,1],[oy,1,1]));let O={rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=e_(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*t/oy),1,1],[oy,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(t*r/oy),1,1],[oy,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e),(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=e_({...O,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:x});this._kernelManager.register(`generateList`,F().compute([Math.ceil(a/oy),1,1],[oy,1,1]));let I=this.bvhStorageNode,L=this.triangleStorageNode,R=this.materialData.materialStorageNode,ee=(0,n.texture)(this.environment.envCDFTexture),te=this.lightStorageNode,ne=this.materialData,z=this.environment,B=mf(ne.srgbBuckets),re=mf(ne.linearBuckets);cf(B,re),Nf(B);let ie=z.environmentTexture?(0,n.texture)(z.environmentTexture):e.envTex;this._wfTexNodes={envTex:ie,envCDFTex:ee,srgbBuckets:B,linearBuckets:re},this._sortMaterials=(V.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let ae=D_({bvhBuffer:I,triangleBuffer:L,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:x,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ae().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,ty({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,ny({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,ry({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,iy({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let oe=Wv({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envCDFTexture:ee,lightBuffer:te,rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,counters:x,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:ie,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform,hasSun:this.hasSun,sunDirection:this.sunDirection,sunRadiance:this.sunRadiance,sunParams:this.sunParams});this._kernelManager.register(`shade`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let se=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=se;let ce=(se?qv:Kv)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:x,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ce().compute([Math.ceil(a/256),1,1],[256,1,1]));let le=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,le().compute([1,1,1],[1,1,1]));let ue=g.activeIndicesRO.b,de=g.activeIndices.a,fe=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),C.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),de.element(e).assign(ue.element(e))});this._kernelManager.register(`compactCopyback`,fe().compute([Math.ceil(a/oy),1,1],[oy,1,1]));let pe=Yv({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:_,prevAlbedoTexture:v,prevNormalDepthTexture:y,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,pe().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let me=ey({writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envTexture:ie,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,me().compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1])),this._wavefrontReady=!0;let he=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);ay.info(J.list([J.px(t,r),`${J.mb(he)} wavefront buffers`,`budget ${J.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},ly=class extends P{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:N.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Jg(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(U,U),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(U,U),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleGeoAttr&&!this._triStorageNode&&(this._triStorageNode={geo:(0,n.storage)(e.triangleGeoAttr,`uvec4`,e.triangleGeoAttr.count).toReadOnly(),shade:(0,n.storage)(e.triangleShadeAttr,`uvec4`,e.triangleShadeAttr.count).toReadOnly()}),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&hf(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=mf(this.pathTracer?.materialData?.linearBuckets),cf(mf(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex,u=this._leafStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(o)).and(f.lessThan((0,n.int)(s))),()=>{let p=ui(Yg((0,n.vec2)((0,n.float)(d).add(.5).div(o),(0,n.float)(f).add(.5).div(s)),i,a,this.cameraRay)),m=hi.wrap(v_(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),_).toWriteOnly(),u&&(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=di.wrap(na(m.materialIndex,r)).toVar(),a=wi.wrap(bf(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(wf(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=Tf(m.normal,i,a,o).toVar();v.assign(Ef(s,i,a)),y.assign(Sf(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),b).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(U,U);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},uy=class extends P{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:N.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Jg(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(U,U),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(U,U),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=Xg(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Xg(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},dy=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),fy=e=>(0,n.vec3)(dy(e.x),dy(e.y),dy(e.z)),py=class extends P{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:N.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(U,U),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(U,U),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(U,U),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(U,U),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(U,U),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Hi(fy(m.div((0,n.max)(_,(0,n.vec3)(Ee))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Hi(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ee)),T=fy(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),te=I.add(L).add(R).add(ee);(0,n.If)(te.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(te),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=fy((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Hi(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},my=1e-6,hy=1.5/255,gy=.01,_y=3,vy=2,yy=2,by=3,xy=2,Sy=38,Cy=.1,wy=4,Ty=Math.cos(89*Math.PI/180),Ey=.5,Dy=16,Oy={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},ky=.25*Math.SQRT2,Ay=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-ky,ky,.5],[ky,ky,.5],[ky,-ky,.5],[-ky,-ky,.5]],jy=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),My=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-_y);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Ny=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Py=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),Fy=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(my)))),Iy=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(Fy(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(hy));return(0,n.float)(1).div(a)},Ly=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(gy),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Ry=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},zy=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},By=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Vy=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Hy=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Uy=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Wy=(e,t)=>t.add(my).div(e.add(my)),Gy=(e,t)=>(0,n.vec4)(e.xyz.mul(Wy(e.x,t)),e.w),Ky=e=>(0,n.vec4)(Hy(Uy(e.xyz)),(0,n.saturate)(e.w)),qy=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),Jy=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Yy=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Xy(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var Zy=class extends P{constructor(e,i={}){super(`NRD`,{...i,executionMode:N.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...ke,...i.settings||{}};let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=Jg(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Dy),this._dispatchY=Math.ceil(o/Dy),this._buildKernels()}_allocStorage(){let e=()=>Nt(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in ke&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return Xg(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(qg(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(qg(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Ey,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Dy,Dy,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Oy[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(Hy(Ri(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ee))))),Li(r.w,Ii).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Ce),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Ce).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=Py(k,.5).toVar(),D=A.mul(Te).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=By(a.planeDistSensitivity,p,f,O).toVar(),ee=Iy(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),te=Ly(k,a.roughnessFraction.mul(i)).toVar(),ne=zy(M,T).toVar(),z=a.minHitDistanceWeight.mul(i).mul(E);t||(z=z.mul(T)),z=z.toVar();let B=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;B=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),B=B.div((0,n.max)(B.x,B.y))}let re=B.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ie=(0,n.float)(1).toVar();for(let t=0;t<Ay.length;t++){let r=Ay[t],i=e.add(Jy(m,(0,n.vec2)(r[0],r[1])).mul(re)),a=Vy(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=Ny((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(jy(g,ee,(0,n.float)(0))),u.mulAssign(jy(h.w,te.x,te.y)),u.mulAssign(jy((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Ce),(0,n.float)(0),u));let _=Yy(u,x(d));u.mulAssign(z.add(My(_.w,ne.x,ne.y))),ie.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ie,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Ce),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Ce);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),te=this._bilinear(R),ne=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(my).toVar(),z=(0,n.float)(1).sub(y),B=[],re=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,te.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(Ty),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(ne),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Ce),(0,n.float)(1),(0,n.float)(0));B.push(r.mul(i).mul(a).mul(te.inScreen[e]).mul(z).toVar()),re.push((0,n.textureLoad)(c,te.taps[e]).x)}let ie=te.customWeights(B).map(e=>e.toVar()),ae=B[0].add(B[1]).add(B[2]).add(B[3]).greaterThan(3.5).toVar(),oe=B[0].add(B[1].mul(2)).add(B[2].mul(4)).add(B[3].mul(8)),se=this._applyCustomWeights(re,ie,(0,n.float)(0)).toVar(),ce=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();ce.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ce.mul(ce))));let le=(0,n.sqrt)((0,n.saturate)(te.filter(B))).mul(ce).toVar();se.assign(se.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(se.add(1))))),se.assign((0,n.min)(se,E));let ue=Ky(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,te,ie,ae)).toVar(),de=(0,n.max)(this._applyCustomWeights(te.taps.map(e=>(0,n.textureLoad)(s,e).x),ie,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=se.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(Py(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(Sy).div(se.add(1))).toVar(),ye=se.mul(e.maxBlurRadius).mul(Cy).toVar();ye.assign(ye.div(ye.add(1)).mul((0,n.float)(1).sub(pe)));let be=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),ye);_e.assign(Gy(_e,be));let xe=(0,n.float)(1.2).add((0,n.float)(1).div(se.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(xe)),ye))),(0,n.textureStore)(u,_,_e).toWriteOnly();let V=(0,n.min)(se,D).mul((0,n.float)(1).sub(pe)),Se=fe.div(fe.add(V)),we=(0,n.mix)(de,T.x,Se).toVar(),Te=(0,n.min)(we,ue.x.mul(ve).mul(wy));we.assign((0,n.mix)(we,Te,ye)),(0,n.textureStore)(d,_,(0,n.vec4)(we,se,oe,(0,n.select)(ae,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(Ce),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Te).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/vy).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=Iy(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=By(e.planeDistSensitivity,k,D,w).toVar(),c=zy(P,j).toVar(),d=Ry(T.mul(T),(0,n.sqrt)(e.roughnessFraction),gy).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-vy;e<=vy;e++)for(let h=-vy;h<=vy;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===vy*2)continue;let g=Vy(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=My(Ny((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(My(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(jy((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Ce),(0,n.float)(0),x));let S=Yy(x,(0,n.textureLoad)(i,_));x.mulAssign(My(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,my))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),te=R.mul(R).toVar(),ne=(0,n.float)(0).toVar(),z=(0,n.float)(0).toVar(),B=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(Ce),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=yy&&Math.abs(r)<=yy&&(ee.addAssign(c),te.addAssign(c.mul(c))),i&&(ne.addAssign(c),z.addAssign(c.mul(c)))},re=e.antiFirefly.greaterThan(.5);for(let e=-yy;e<=yy;e++)for(let t=-yy;t<=yy;t++)t===0&&e===0||B(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(re,()=>{for(let e=-by;e<=by;e++)for(let t=-by;t<=by;t++)Math.abs(t)<=yy&&Math.abs(e)<=yy||B(t,e,!0)}),(0,n.If)(re,()=>{let e=1/((by*2+1)**2-9),t=ne.mul(e),r=qy(t,z.mul(e)).mul(xy);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(yy*2+1)**2,r=ee.mul(t),i=qy(r,te.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,Gy(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(Ce),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(Ce),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=qy(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),te=R.mul(t.antilag.x),ne=t.antilag.y.mul(4),z=ee.clamp(I.sub(te),I.add(te)),B=ee.sub(z).abs().div((0,n.max)(ee,z).add(my)),re=(0,n.float)(1).div((0,n.float)(1).add(B.mul(D.mul(N)).div(ne))).toVar(),ie=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ie,D,re));let ae=h.add(1),oe=this._handover(ae),se=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(oe)).div(ae)))).mul(re).toVar(),ce=(0,n.float)(1).add(se.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(ce)),I.add(R.mul(ce))),(0,n.min)(se,le)).toVar();P.assign(Gy(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(Uy(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ee))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Dy,Dy,1])}setupEventListeners(){this.on(`denoiser:reset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=Xy(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Dy),this._dispatchY=Math.ceil(t/Dy);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}},Qy=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),$y=(0,n.wgslFn)(`
895
+ `),$v=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=ui({origin:e,direction:t}),y=hi.wrap(y_(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=M_({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Fi).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=di.wrap(na(y.materialIndex,a)).toVar(),r=Si.wrap(Af(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(Zv({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Qv({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Xv({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=di.wrap(na(y.materialIndex,a)).toVar(),t=Si.wrap(Af(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=Rt({state:zt({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Id({N:d,xi:(0,n.vec2)(Vt(p).toVar(),Vt(p).toVar())}).toVar(),h=ui({origin:Ei(y.hitPoint,d),direction:m}),v=hi.wrap(y_(h,r,i,(0,n.bool)(!1),(0,n.bool)(!1)).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(M_({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=di.wrap(na(v.materialIndex,a)).toVar(),t=Si.wrap(Af(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=M_({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=M_({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=M_({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function ey(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,unitsPerMetre:b,apertureScale:x,anamorphicRatio:S,dofMode:C,dofBlur:w,bvhBuffer:T,triangleBuffer:E,materialBuffer:D,envTexture:O,environmentMatrix:k,environmentIntensity:A,enableEnvironmentLight:j,visMode:M,debugVisScale:N,frame:P}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),F=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(F.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(F).add(.5)),s=Rt({state:(0,n.uint)(F.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),I=ui.wrap($g(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S,C,w)),L=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(M.equal((0,n.int)(9)),()=>{let e=$t(o,(0,n.int)(0),s,a,P);L.assign((0,n.vec4)(e,1,1))}).Else(()=>{L.assign($v(I.origin,I.direction,T,E,D,O,k,A,j,M,N,o,a,u,d,P))});let R=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(F));(0,n.textureStore)(t,R,L).toWriteOnly(),(0,n.textureStore)(r,R,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,R,(0,n.vec4)(L.xyz,1)).toWriteOnly()})})}function ty({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function ny({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)($.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Wa(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function ry({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function iy({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)($.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(Wa(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}jt();var ay=vt(`wavefront`),oy=256,sy=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],cy=class extends Mg{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lockstep=!1,this._lockstepRead=null,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this.hostMemoryGB=i.hostMemoryGB,this._chunkRows=0,this._numChunks=1,this.vramTracker=new Hg(this.renderer),this._registerVRAMProviders(),ay.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleGeoAttr,this.triangleShadeAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;let t=this._lockstepRead;if(t&&this.frameCount>=t.due){if(!t.apply)return;this._lockstepRead=null,t.apply()}if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let n=this.frameCount,r=this.renderMode.value,i=null;r===1&&n===0&&(i=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(r),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(n);let a=this._updateAuxAccumulationUniforms(n);this.frame.value=n,this.seedFrame.value=this._seedTick++,this.tracedFrames++,this._setWfDispatch();let o=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=o.color,this.shaderBuilder.prevAlbedoTexNode.value=o.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=o.normalDepth),this._refreshWfTextureNodes();let s=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){s.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end();return}let c=this.maxBounces.value,l=this._bounceLoopBound(),u=this._wfRenderHeight.value,d=this._chunkRows,f=this._numChunks<=1;l>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let p=this._lastBounceCounts,m=c<=this._lastBounceCountsBudget&&l<=this._lastBounceCountsLoopBound,h=f&&p?m?l+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0;for(let e=0,t=0;t<u;t+=d,e++){let r=Math.min(d,u-t),i=this._setChunk(t,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,o=f&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(o*1.5)+1024);s.setDispatchForCount(`generateList`,e),s.dispatch(`resetFrameCounters`),s.dispatch(`buildActivePixels`),s.dispatch(`seedEnter`),s.dispatch(`generateList`)}else s.dispatch(`generate`),s.dispatch(`initActiveIndices`);e===0&&n>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&s.dispatch(`countConvergedDilated`);let c=this._lastBounceEnergy,m=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=l;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(f&&e>0&&this._curveSizingValid){let n=e-1,r;n<h&&p[n]!==void 0?r=p[n]:h>0&&(r=p[h-1]),t=r>0?r:i}else e===0&&a&&(t=o);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of sy)s.setDispatchForCount(e,n)}else{s.dispatch(`enterFull`);for(let e of sy)s.setDispatchForCount(e,i)}if(s.dispatch(`extend`),this._sortMaterials&&(s.dispatch(`resetGlobalHist`),s.dispatch(`globalHist`),s.dispatch(`globalPrefix`),s.dispatch(`globalScatter`)),s.dispatch(`shade`),s.dispatch(`compact`),t?s.dispatch(`compactCopyback`):s.dispatch(`snapshotBounceCount`),m>=0&&e<h&&e<l&&c?.[e]!==void 0&&c[e]<=m)break}s.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let g=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,g),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=a?this._auxSamples+1:1),this._auxSeedPending=!1,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}async captureAccumulation(){let e=this.storageTextures,t=e.renderWidth,n=e.renderHeight,r=t*n,i=async i=>{let a=await this.renderer.readRenderTargetPixelsAsync(e.readTarget,0,0,t,n,i),o=Math.ceil(t*16/256)*64;if(o===t*4)return new Float32Array(a.buffer,a.byteOffset,r*4).slice();let s=new Float32Array(r*4);for(let e=0;e<n;e++)s.set(a.subarray(e*o,e*o+t*4),e*t*4);return s},a=async(e,t)=>e?new t(await this.renderer.getArrayBufferAsync(e,null,0,r*4)):null,o=this._auxGBufferEnabled&&this._auxSamples>0,s={frameCount:this.frameCount,seedTick:this._seedTick,auxSamples:o?this._auxSamples:0,convergedFraction:this._convergedFraction,convergedGeometryFraction:this._convergedGeometryFraction,isComplete:this.isComplete},c=[i(0),o?i(1):null,o?i(2):null,a(this._m2Attr,Float32Array),a(this._streakAttr,Uint32Array),a(this._frozenMaskAttr,Uint32Array)],[l,u,d,f,p,m]=await Promise.all(c);return{width:t,height:n,state:s,color:l,normalDepth:u,albedo:d,m2:f,streak:p,frozenMask:m}}restoreAccumulation(e){let t=this.storageTextures,{width:n,height:r,state:i}=e;if(t.renderWidth!==n||t.renderHeight!==r)throw Error(`checkpoint is ${n}×${r}; the render is ${t.renderWidth}×${t.renderHeight}`);let a=this.renderer.backend,o=a.device;a.get(t.readTarget.textures[0]).texture||this.renderer.initRenderTarget(t.readTarget);let s=(e,i)=>o.queue.writeTexture({texture:a.get(t.readTarget.textures[e]).texture},i,{bytesPerRow:n*16,rowsPerImage:r},{width:n,height:r}),c=(e,t)=>{e&&t&&o.queue.writeBuffer(a.get(e).buffer,0,t)};s(0,e.color),e.normalDepth&&s(1,e.normalDepth),e.albedo&&s(2,e.albedo),c(this._m2Attr,e.m2),c(this._streakAttr,e.streak),c(this._frozenMaskAttr,e.frozenMask),this.frameCount=i.frameCount,this.frame.value=i.frameCount,this._seedTick=i.seedTick,this.hasPreviousAccumulated.value=+(i.frameCount>0),this._auxSamples=e.normalDepth?i.auxSamples:0,this._auxSeedPending=this._auxGBufferEnabled&&!e.normalDepth,this._convergedFraction=i.convergedFraction??0,this._convergedGeometryFraction=i.convergedGeometryFraction??0,this.isComplete=!1}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1,this._lockstep&&(this._lockstepRead=null,this._readbackGeneration++,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._curveSizingValid=!1)}setLockstepReadbacks(e){e=!!e,e!==this._lockstep&&(this._lockstep=e,this._lockstepRead=null,this._readbackGeneration++)}get lockstepReadbacks(){return this._lockstep}readbackWait(){let e=this._lockstepRead;return e&&!e.apply&&this.frameCount>=e.due?e.read:null}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()?!1:this._lockstep?!this._lockstepRead&&this.frameCount%this._readbackEveryNFrames===0:this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value}_maybeReadbackCounters(){if(this._lockstep){this._issueLockstepReadback();return}if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&this._applyBounceCounts(e,n,r,i),this._readbackPending=!1}).catch(e=>{ay.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&n>0&&this._applyCounters(e,n),this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_issueLockstepReadback(){if(this._lockstepRead||this.frameCount%this._readbackEveryNFrames!==0||this.cameraChanged||this.cameraOptimizer?.isInInteractionMode())return;let e=this._queueManager?.getBounceCountsAttribute(),t=this._queueManager?.getCountersAttribute();if(!e||!t)return;let n=this._readbackGeneration,r=this.maxBounces.value,i=this._bounceLoopBound(),a=this._queueManager.MAX_BOUNCE_SNAPSHOTS,o=this._wfRenderWidth.value*this._wfRenderHeight.value,s={due:this.frameCount+this._readbackEveryNFrames,read:null,apply:null};s.read=Promise.all([this.renderer.getArrayBufferAsync(e),this.renderer.getArrayBufferAsync(t)]).then(([e,t])=>{s.apply=()=>{n===this._readbackGeneration&&(this._applyBounceCounts(e,r,i,a),o>0&&this._applyCounters(t,o))}},e=>{ay.warn(`lockstep readback failed:`,e),s.apply=()=>{}}),this._lockstepRead=s}_applyBounceCounts(e,t,n,r){let i=new Uint32Array(e.slice(0));this._lastBounceCounts=i.subarray(0,r),this._lastBounceEnergy=i.subarray(r,2*r),this._lastBounceCountsBudget=t,this._lastBounceCountsLoopBound=n,this._curveSizingValid=!0}_applyCounters(e,t){let n=new Uint32Array(e);this._convergedFraction=n[$.CONVERGED_COUNT]/t;let r=n[$.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?n[$.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=n[$.ACTIVE_PIXEL_COUNT]}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(hf(e.srgbBuckets,n.srgbBuckets),hf(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=Um(this.hostMemoryGB).gb*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/192),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,U),t=Math.min(this.storageTextures.renderHeight||1,U);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t;this._packedBuffers?this._packedBuffers.resize(i):this._packedBuffers=new ba(i,this.renderer);let o=i*1;ya(this.renderer,this._gBufferAttr),this._gBufferAttr=S(o,4,Uint32Array);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),l=U*U;(!this._m2Attr||this._m2Attr.count<l)&&(ya(this.renderer,this._m2Attr),this._m2Attr=S(l,1),ya(this.renderer,this._streakAttr),this._streakAttr=S(l,1,Uint32Array),ya(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=S(l,1,Uint32Array));let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Ig(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new Wg(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,v=this.shaderBuilder.prevAlbedoTexNode,y=this.shaderBuilder.prevNormalDepthTexNode,b=this.storageTextures.getWriteTextures(),x=g.getCounters(),C=g.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),C.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=g.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*t/oy),1,1],[oy,1,1]));let O={rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=e_(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*t/oy),1,1],[oy,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(t*r/oy),1,1],[oy,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e),(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=e_({...O,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:x});this._kernelManager.register(`generateList`,F().compute([Math.ceil(a/oy),1,1],[oy,1,1]));let I=this.bvhStorageNode,L=this.triangleStorageNode,R=this.materialData.materialStorageNode,ee=(0,n.texture)(this.environment.envCDFTexture),te=this.lightStorageNode,ne=this.materialData,z=this.environment,B=mf(ne.srgbBuckets),re=mf(ne.linearBuckets);cf(B,re),Nf(B);let ie=z.environmentTexture?(0,n.texture)(z.environmentTexture):e.envTex;this._wfTexNodes={envTex:ie,envCDFTex:ee,srgbBuckets:B,linearBuckets:re},this._sortMaterials=(V.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let ae=D_({bvhBuffer:I,triangleBuffer:L,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:x,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ae().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,ty({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,ny({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,ry({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,iy({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let oe=Wv({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envCDFTexture:ee,lightBuffer:te,rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,counters:x,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:ie,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform,hasSun:this.hasSun,sunDirection:this.sunDirection,sunRadiance:this.sunRadiance,sunParams:this.sunParams});this._kernelManager.register(`shade`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let se=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=se;let ce=(se?qv:Kv)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:x,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ce().compute([Math.ceil(a/256),1,1],[256,1,1]));let le=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,le().compute([1,1,1],[1,1,1]));let ue=g.activeIndicesRO.b,de=g.activeIndices.a,fe=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),C.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),de.element(e).assign(ue.element(e))});this._kernelManager.register(`compactCopyback`,fe().compute([Math.ceil(a/oy),1,1],[oy,1,1]));let pe=Yv({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:_,prevAlbedoTexture:v,prevNormalDepthTexture:y,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,pe().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let me=ey({writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envTexture:ie,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,me().compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1])),this._wavefrontReady=!0;let he=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);ay.info(J.list([J.px(t,r),`${J.mb(he)} wavefront buffers`,`budget ${J.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},ly=class extends P{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:N.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Jg(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(U,U),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(U,U),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleGeoAttr&&!this._triStorageNode&&(this._triStorageNode={geo:(0,n.storage)(e.triangleGeoAttr,`uvec4`,e.triangleGeoAttr.count).toReadOnly(),shade:(0,n.storage)(e.triangleShadeAttr,`uvec4`,e.triangleShadeAttr.count).toReadOnly()}),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&hf(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=mf(this.pathTracer?.materialData?.linearBuckets),cf(mf(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex,u=this._leafStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(o)).and(f.lessThan((0,n.int)(s))),()=>{let p=ui(Yg((0,n.vec2)((0,n.float)(d).add(.5).div(o),(0,n.float)(f).add(.5).div(s)),i,a,this.cameraRay)),m=hi.wrap(v_(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),_).toWriteOnly(),u&&(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=di.wrap(na(m.materialIndex,r)).toVar(),a=wi.wrap(bf(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(wf(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=Tf(m.normal,i,a,o).toVar();v.assign(Ef(s,i,a)),y.assign(Sf(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),b).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(U,U);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},uy=class extends P{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:N.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Jg(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(U,U),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(U,U),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=Xg(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Xg(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(U,U);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},dy=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),fy=e=>(0,n.vec3)(dy(e.x),dy(e.y),dy(e.z)),py=class extends P{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:N.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(U,U),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(U,U),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(U,U),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(U,U),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(U,U),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Hi(fy(m.div((0,n.max)(_,(0,n.vec3)(Ee))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Hi(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ee)),T=fy(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),te=I.add(L).add(R).add(ee);(0,n.If)(te.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(te),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=fy((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Hi(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(U,U);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},my=1e-6,hy=1.5/255,gy=.01,_y=3,vy=2,yy=2,by=3,xy=2,Sy=38,Cy=.1,wy=4,Ty=Math.cos(89*Math.PI/180),Ey=.5,Dy=16,Oy={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},ky=.25*Math.SQRT2,Ay=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-ky,ky,.5],[ky,ky,.5],[ky,-ky,.5],[-ky,-ky,.5]],jy=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),My=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-_y);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Ny=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Py=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),Fy=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(my)))),Iy=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(Fy(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(hy));return(0,n.float)(1).div(a)},Ly=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(gy),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Ry=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},zy=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},By=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Vy=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Hy=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Uy=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Wy=(e,t)=>t.add(my).div(e.add(my)),Gy=(e,t)=>(0,n.vec4)(e.xyz.mul(Wy(e.x,t)),e.w),Ky=e=>(0,n.vec4)(Hy(Uy(e.xyz)),(0,n.saturate)(e.w)),qy=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),Jy=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Yy=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Xy(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var Zy=class extends P{constructor(e,i={}){super(`NRD`,{...i,executionMode:N.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...ke,...i.settings||{}};let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=Jg(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Dy),this._dispatchY=Math.ceil(o/Dy),this._buildKernels()}_allocStorage(){let e=()=>Nt(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in ke&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return Xg(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(qg(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(qg(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Ey,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Dy,Dy,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Oy[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(Hy(Ri(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ee))))),Li(r.w,Ii).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Ce),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Ce).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=Py(k,.5).toVar(),D=A.mul(Te).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=By(a.planeDistSensitivity,p,f,O).toVar(),ee=Iy(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),te=Ly(k,a.roughnessFraction.mul(i)).toVar(),ne=zy(M,T).toVar(),z=a.minHitDistanceWeight.mul(i).mul(E);t||(z=z.mul(T)),z=z.toVar();let B=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;B=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),B=B.div((0,n.max)(B.x,B.y))}let re=B.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ie=(0,n.float)(1).toVar();for(let t=0;t<Ay.length;t++){let r=Ay[t],i=e.add(Jy(m,(0,n.vec2)(r[0],r[1])).mul(re)),a=Vy(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=Ny((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(jy(g,ee,(0,n.float)(0))),u.mulAssign(jy(h.w,te.x,te.y)),u.mulAssign(jy((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Ce),(0,n.float)(0),u));let _=Yy(u,x(d));u.mulAssign(z.add(My(_.w,ne.x,ne.y))),ie.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ie,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Ce),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Ce);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),te=this._bilinear(R),ne=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(my).toVar(),z=(0,n.float)(1).sub(y),B=[],re=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,te.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(Ty),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(ne),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Ce),(0,n.float)(1),(0,n.float)(0));B.push(r.mul(i).mul(a).mul(te.inScreen[e]).mul(z).toVar()),re.push((0,n.textureLoad)(c,te.taps[e]).x)}let ie=te.customWeights(B).map(e=>e.toVar()),ae=B[0].add(B[1]).add(B[2]).add(B[3]).greaterThan(3.5).toVar(),oe=B[0].add(B[1].mul(2)).add(B[2].mul(4)).add(B[3].mul(8)),se=this._applyCustomWeights(re,ie,(0,n.float)(0)).toVar(),ce=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();ce.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ce.mul(ce))));let le=(0,n.sqrt)((0,n.saturate)(te.filter(B))).mul(ce).toVar();se.assign(se.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(se.add(1))))),se.assign((0,n.min)(se,E));let ue=Ky(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,te,ie,ae)).toVar(),de=(0,n.max)(this._applyCustomWeights(te.taps.map(e=>(0,n.textureLoad)(s,e).x),ie,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=se.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(Py(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(Sy).div(se.add(1))).toVar(),ye=se.mul(e.maxBlurRadius).mul(Cy).toVar();ye.assign(ye.div(ye.add(1)).mul((0,n.float)(1).sub(pe)));let be=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),ye);_e.assign(Gy(_e,be));let xe=(0,n.float)(1.2).add((0,n.float)(1).div(se.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(xe)),ye))),(0,n.textureStore)(u,_,_e).toWriteOnly();let V=(0,n.min)(se,D).mul((0,n.float)(1).sub(pe)),Se=fe.div(fe.add(V)),we=(0,n.mix)(de,T.x,Se).toVar(),Te=(0,n.min)(we,ue.x.mul(ve).mul(wy));we.assign((0,n.mix)(we,Te,ye)),(0,n.textureStore)(d,_,(0,n.vec4)(we,se,oe,(0,n.select)(ae,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(Ce),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Te).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/vy).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=Iy(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=By(e.planeDistSensitivity,k,D,w).toVar(),c=zy(P,j).toVar(),d=Ry(T.mul(T),(0,n.sqrt)(e.roughnessFraction),gy).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-vy;e<=vy;e++)for(let h=-vy;h<=vy;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===vy*2)continue;let g=Vy(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=My(Ny((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(My(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(jy((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Ce),(0,n.float)(0),x));let S=Yy(x,(0,n.textureLoad)(i,_));x.mulAssign(My(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,my))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),te=R.mul(R).toVar(),ne=(0,n.float)(0).toVar(),z=(0,n.float)(0).toVar(),B=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(Ce),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=yy&&Math.abs(r)<=yy&&(ee.addAssign(c),te.addAssign(c.mul(c))),i&&(ne.addAssign(c),z.addAssign(c.mul(c)))},re=e.antiFirefly.greaterThan(.5);for(let e=-yy;e<=yy;e++)for(let t=-yy;t<=yy;t++)t===0&&e===0||B(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(re,()=>{for(let e=-by;e<=by;e++)for(let t=-by;t<=by;t++)Math.abs(t)<=yy&&Math.abs(e)<=yy||B(t,e,!0)}),(0,n.If)(re,()=>{let e=1/((by*2+1)**2-9),t=ne.mul(e),r=qy(t,z.mul(e)).mul(xy);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(yy*2+1)**2,r=ee.mul(t),i=qy(r,te.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,Gy(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Dy).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Dy).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(Ce),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(Ce),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=qy(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),te=R.mul(t.antilag.x),ne=t.antilag.y.mul(4),z=ee.clamp(I.sub(te),I.add(te)),B=ee.sub(z).abs().div((0,n.max)(ee,z).add(my)),re=(0,n.float)(1).div((0,n.float)(1).add(B.mul(D.mul(N)).div(ne))).toVar(),ie=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ie,D,re));let ae=h.add(1),oe=this._handover(ae),se=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(oe)).div(ae)))).mul(re).toVar(),ce=(0,n.float)(1).add(se.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(ce)),I.add(R.mul(ce))),(0,n.min)(se,le)).toVar();P.assign(Gy(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(Uy(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ee))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Dy,Dy,1])}setupEventListeners(){this.on(`denoiser:reset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=Xy(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Dy),this._dispatchY=Math.ceil(t/Dy);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}},Qy=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),$y=(0,n.wgslFn)(`
896
896
  fn temporalAccumulate(
897
897
  lum: f32,
898
898
  prevMean: f32,
@@ -968,7 +968,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
968
968
  return vec4f( newExposure, geoMean, targetExp, 1.0 );
969
969
 
970
970
  }
971
- `),hb=class extends P{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:N.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,n.uniform)(r.keyValue??.18),this.minExposureU=(0,n.uniform)(r.minExposure??.1),this.maxExposureU=(0,n.uniform)(r.maxExposure??20),this.adaptSpeedBrightU=(0,n.uniform)(r.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,n.uniform)(r.adaptSpeedDark??.5),this.epsilonU=(0,n.uniform)(r.epsilon??1e-4),this.deltaTimeU=(0,n.uniform)(1/60),this.isFirstFrameU=(0,n.uniform)(1),this.previousExposureU=(0,n.uniform)(r.initialExposure??1),this.lowPercentileU=(0,n.uniform)(r.lowPercentile??.1),this.highPercentileU=(0,n.uniform)(r.highPercentile??.9),this.centerWeightU=(0,n.uniform)(r.centerWeight??8),this.inputResW=(0,n.uniform)(1),this.inputResH=(0,n.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=r.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=r.FloatType,this._downsampleStorageTex.format=r.RGBAFormat,this._downsampleStorageTex.minFilter=r.NearestFilter,this._downsampleStorageTex.magFilter=r.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=r.FloatType,this._reductionStorageTex.format=r.RGBAFormat,this._reductionStorageTex.minFilter=r.NearestFilter,this._reductionStorageTex.magFilter=r.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationResult=(0,n.attributeArray)(1,`vec4`),this._readbackBuffer=new t.ReadbackBuffer(16),this._readbackBuffer.name=`AutoExposureAdaptation`,this._histogramBuffer=(0,n.attributeArray)(lb,`uint`).toAtomic()}_buildCompute(){this._buildDownsampleCompute(),this._buildHistogramCompute(),this._buildHistogramAnalyzeCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,r=this.epsilonU,i=this.inputResW,a=this.inputResH;this._downsampleComputeNode=(0,n.Fn)(()=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y)),c=i.div((0,n.float)(64)),l=a.div((0,n.float)(64)),u=(0,n.float)(o).mul(c),d=(0,n.float)(s).mul(l),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let i=0;i<4;i++){let a=Hi((0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(u.add((0,n.float)((i+.5)/4).mul(c))),(0,n.int)(d.add((0,n.float)((t+.5)/4).mul(l))))).xyz);(0,n.If)(a.greaterThan(r),()=>{f.addAssign(a.add(r).log()),p.addAssign(1)})}(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(s)),(0,n.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildHistogramCompute(){let e=this._downsampleTarget.texture,t=this._histogramBuffer,r=this.centerWeightU;this._histogramComputeNode=(0,n.Fn)(()=>{let i=n.localId.x;(0,n.atomicStore)(t.element(i),(0,n.uint)(0)),(0,n.workgroupBarrier)();for(let a=0;a<16;a++){let o=i.mul(16).add(a),s=o.mod(64),c=o.div(64),l=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(s),(0,n.int)(c))),u=l.x,d=l.y;(0,n.If)(d.greaterThan(0),()=>{let e=(0,n.uint)(u.div(d).sub((0,n.float)(ub)).div((0,n.float)(db)).mul((0,n.float)(lb)).floor().clamp(0,(0,n.float)(lb-1))),i=(0,n.float)(s).add(.5).div((0,n.float)(64)),a=(0,n.float)(c).add(.5).div((0,n.float)(64)),o=i.sub(.5),l=a.sub(.5),f=(0,n.uint)(o.mul(o).add(l.mul(l)).mul(r).negate().exp().mul((0,n.float)(pb)));(0,n.atomicAdd)(t.element(e),f)})}})().compute([1,1,1],[256,1,1])}_buildHistogramAnalyzeCompute(){let e=this._histogramBuffer,t=this._reductionStorageTex,r=this.lowPercentileU,i=this.highPercentileU;this._histogramAnalyzeNode=(0,n.Fn)(()=>{let a=(0,n.float)(0).toVar();(0,n.Loop)(lb,({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(t))))});let o=a.mul(r),s=a.mul(i),c=(0,n.float)(0).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)(lb,({i:t})=>{let r=(0,n.float)((0,n.atomicLoad)(e.element(t)));d.assign(c),c.addAssign(r),(0,n.If)(d.lessThan(s).and(c.greaterThan(o)),()=>{let e=(0,n.float)(ub).add((0,n.float)(t).add(.5).mul((0,n.float)(fb)));l.addAssign(e.mul(r)),u.addAssign(r)})});let f=(0,n.max)(u,(0,n.float)(1)),p=l.div(f),m=p.exp();(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(0),(0,n.uint)(0)),(0,n.vec4)(m,a,p,1)).toWriteOnly()})().compute(1,[1,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationResult,r=this.keyValueU,i=this.minExposureU,a=this.maxExposureU,o=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,n.Fn)(()=>{let d=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(0),(0,n.int)(0))).x,f=mb(d,u,r,i,a,o,s,c,l);t.element((0,n.uint)(0)).assign(f)})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>e&&this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=+!!this.isFirstFrame,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._histogramComputeNode),this.renderer.compute(this._histogramAnalyzeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.getArrayBufferAsync(this._adaptationResult.value,this._readbackBuffer).then(t=>{let n=t&&t.buffer?new Float32Array(t.buffer.slice(0)):null;this._readbackBuffer.release(),this._pendingReadback=!1,n&&e===this._readbackGeneration&&this._applyReadback(n)}).catch(()=>{try{this._readbackBuffer.release()}catch{}this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark),e.lowPercentile!==void 0&&(this.lowPercentileU.value=e.lowPercentile),e.highPercentile!==void 0&&(this.highPercentileU.value=e.highPercentile),e.centerWeight!==void 0&&(this.centerWeightU.value=e.centerWeight)}dispose(){this._downsampleComputeNode?.dispose(),this._histogramComputeNode?.dispose(),this._histogramAnalyzeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._readbackBuffer?.dispose(),this._inputTexNode?.dispose(),this._reductionReadTexNode?.dispose()}},gb=[`oidn:output`,`edgeFiltering:output`,`bilateralFiltering:output`,`asvgf:output`,`nrd:output`,`pathtracer:color`],_b=class extends P{constructor(e,i={}){super(`Compositor`,{...i,executionMode:N.ALWAYS}),this.renderer=e,this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode;let a=this._sourceTexNode.sample((0,n.uv)()),o=(0,n.mix)((0,n.vec3)((0,n.dot)(a.xyz,Fi)),a.xyz,this.saturation),s=(0,n.select)(this._transparentBackground,a.w,1);this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.colorNode=(0,n.vec4)(o,s),this.compositorMaterial.blending=r.NoBlending,this.compositorQuad=new t.QuadMesh(this.compositorMaterial)}_resolveSourceTexture(e){return e.getTexture(`bloom:output`)||this.resolveLightTexture(e)}resolveLightTexture(e){return this.resolveLightSource(e)?.texture??null}resolveLightSource(e){for(let t of gb){let n=e.getTexture(t);if(n)return{key:t,texture:n}}return null}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Fi).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let t=this._resolveSourceTexture(e);t&&(this._sourceTexNode.value=t,this.renderer.setRenderTarget(null),this.compositorQuad.render(this.renderer))}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},vb=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},yb=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},bb=!1,xb=[],Sb=new WeakMap;function Cb(e){bb=!!e}function wb(){return xb.slice()}function Tb(){xb.length=0}function Eb(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var Db=e=>!e||!e.image||!(e.image.width>0);function Ob(e,t,n){if(!bb){n();return}let r=Sb.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},Sb.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&kb(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=Eb(e).filter(t=>Db(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function kb(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(Db(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&xb.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}var Ab=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(Y.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new vb,this.eventBus=new yb,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(Ob(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};jt();var jb=vt(`engine`),Mb=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return t!==`time`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,jb.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},Nb=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,n){try{return await this.renderer.readRenderTargetPixelsAsync(this.draw(e,t,n),0,0,t,n)}finally{this.release()}}draw(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();return this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i),this.target}release(){this.target?.dispose(),this.target=null}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};R();var Pb=new r.Vector3,Fb=new r.Vector3;function Ib(e,t){return Fb.subVectors(e,t.position).dot(t.getWorldDirection(Pb))}function Lb(e,t,n=!1){return n?e.distance:Ib(e.point,t)}var Rb=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:I.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=this.pathTracer?.cameraProjection?.value===Se.equirectangular,r=Lb(e,this.camera,t);this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:r/this.assetLoader.getSceneScale(),worldDistance:r})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}pickSurface(e,t){return this.raycaster.setFromCamera({x:e,y:t},this.camera),this.filterValidIntersects(this.raycaster.intersectObjects(this.scene.children,!0))[0]??null}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:I.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:I.FOCUS_CHANGED,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:I.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},zb="var e=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}};let t=null;async function n(e,t){return t||(await navigator.storage.getDirectory()).getDirectoryHandle(e,{create:!0})}self.onmessage=async({data:r})=>{let{id:i,op:a,args:o}=r;try{if(a===`init`){t=new e(n(o.namespace,o.root)),postMessage({id:i,result:{}});return}let r=await t[a](o),s=r?.buffer instanceof ArrayBuffer?[r.buffer]:[];postMessage({id:i,result:r},s)}catch(e){postMessage({id:i,error:{name:e.name,message:e.message}})}};",Bb=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,zb],{type:`text/javascript;charset=utf-8`});function Vb(e){let t;try{if(t=Bb&&(self.URL||self.webkitURL).createObjectURL(Bb),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(zb),{type:`module`,name:e?.name})}}function Hb({name:e,message:t}){let n=Error(t);return n.name=e,n}var Ub=class{constructor({namespace:e,root:t=null}){this._worker=new Vb,this._pending=new Map,this._nextId=0,this._worker.onmessage=({data:e})=>{let t=this._pending.get(e.id);t&&(this._pending.delete(e.id),e.error?t.reject(Hb(e.error)):t.resolve(e.result))},this._ready=this.call(`init`,{namespace:e,root:t})}call(e,t,n=[]){return this._worker?new Promise((r,i)=>{let a=this._nextId++;this._pending.set(a,{resolve:r,reject:i}),this._worker.postMessage({id:a,op:e,args:t},n)}):Promise.reject(Error(`storage: transport disposed`))}dispose(){this._worker?.terminate(),this._worker=null;for(let{reject:e}of this._pending.values())e(Error(`storage: transport disposed`));this._pending.clear()}};function Wb(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}async function Gb(e){let t=typeof navigator<`u`?navigator.storage:null;if(!t?.getDirectory)return{root:null,reason:`this browser has no origin private file system`};try{return{root:await(await t.getDirectory()).getDirectoryHandle(e,{create:!0})}}catch(e){return{root:null,reason:`${e.name}: ${e.message}`}}}async function Kb({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await Gb(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(Wb()||typeof Worker>`u`))return{storage:sr({namespace:e,root:r.root})};let i=new Ub({namespace:e,root:t}),a=new or({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function qb(e){let t=Pu.get(e);t||(t={refs:0,opened:Kb({namespace:e})},Pu.set(e,t)),t.refs++;let{storage:n,reason:r}=await t.opened;t.storage=n;let i=!1,a=()=>{i||(i=!0,t.refs--,!(t.refs>0)&&(Pu.get(e)===t&&Pu.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}Ys();var Jb=864e5,Yb=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),Xb=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),Zb=(e,t)=>e.headers?.get?.(t)??null,Qb=e=>e.reason??new DOMException(`aborted`,`AbortError`);function $b(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function ex(e,{onProgress:t,signal:n}){let r=Number(Zb(e,`content-length`))||0,i=Zb(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),Qb(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(Xb(s,r))}return new Blob(o,{type:i})}var tx=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),nx=()=>{},rx=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(Wn.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=$b(e),policy:r=Yb.REVALIDATE,maxAgeMs:i=Jb,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==Yb.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===Yb.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(Xb(c.size,c.size)),{file:tx(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw Qb(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(Zb(s,`content-length`))||0,l={url:e,contentType:Zb(s,`content-type`)??``,lastModified:Zb(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:tx(await ex(s,{onProgress:r,signal:i}),n,l.contentType),release:nx,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(Xb(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:tx(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=Zb(n,`last-modified`),t=n.status===206?Number(Zb(n,`content-range`)?.match(/\/(\d+)$/)?.[1])||null:Number(Zb(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};function ix(e,t,n){return new rx(t).fetch(e,n)}function ax(){return new rx(Fu(Ks().cacheNamespace))}async function ox(e,{downloads:t=ax(),...n}={}){if(!t._storage||!/^https?:/i.test(e))return{url:e,release:nx,cached:!1};let{file:r,release:i}=await t.fetch(e,n),a=URL.createObjectURL(r);return{url:a,cached:!0,release:()=>{URL.revokeObjectURL(a),i()}}}R();var sx={maxBounces:{uniform:`maxBounces`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},maxSubsurfaceSteps:{uniform:`maxSubsurfaceSteps`,reset:!0},maxTransparentBounces:{uniform:`maxTransparentBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},backgroundBlurriness:{uniform:`backgroundBlurriness`,reset:!0},backgroundBlurSamples:{uniform:`backgroundBlurSamples`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},groundProjectionEnabled:{uniform:`groundProjectionEnabled`,reset:!0},groundProjectionRadius:{uniform:`groundProjectionRadius`,reset:!0},groundProjectionHeight:{uniform:`groundProjectionHeight`,reset:!0},groundProjectionLevel:{uniform:`groundProjectionLevel`,reset:!0},enableGroundCatcher:{uniform:`enableGroundCatcher`,reset:!0},groundCatcherHeight:{uniform:`groundCatcherHeight`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},panoramaLevelHorizon:{uniform:`panoLevelHorizon`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},unitsPerMetre:{uniform:`unitsPerMetre`,reset:!0},dofMode:{handler:`handleDofMode`,reset:!0},dofBlur:{uniform:`dofBlur`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},shadowTerminatorOffset:{uniform:`shadowTerminatorOffset`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},noiseThreshold:{uniform:`noiseThreshold`,reset:!0},adaptiveMinSamples:{uniform:`adaptiveMinSamples`,reset:!0},adaptiveStopFraction:{uniform:`adaptiveStopFraction`,reset:!0},usePixelFreeze:{uniform:`usePixelFreeze`,reset:!0},pixelFreezeThreshold:{uniform:`pixelFreezeThreshold`,reset:!0},pixelFreezeStability:{uniform:`pixelFreezeStability`,reset:!0},convergenceOverlay:{handler:`handleConvergenceOverlay`,reset:!1},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},cameraProjection:{handler:`handleCameraProjection`,reset:!0},panoramaLonRange:{handler:`handlePanoramaLonRange`,reset:!0},panoramaLatRange:{handler:`handlePanoramaLatRange`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},interactionRenderScale:{handler:`handleInteractionRenderScale`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},backgroundColor:{handler:`handleBackgroundColor`,reset:!0},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},cx=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),lx={bounces:`maxBounces`,debugMode:`visMode`},ux=class extends r.EventDispatcher{constructor(e=V,{issues:t=null}={}){super(),this._issues=t,this._values=new Map,this._sources=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind(e){this._pathTracer=e.stages.pathTracer,this._resetCallback=e.resetCallback,this._delegates={},this._handlers=this._buildHandlers(e)}_buildHandlers({stages:e,renderer:t,resetCallback:n,reconcileCompletion:i,denoisingManager:a,onInteractionRenderScale:o,onCameraProjection:s}){let c=new r.Vector2,l=(t,n)=>{c.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,c)};return{handleCameraProjection:t=>{e.pathTracer?.setUniform(`cameraProjection`,Se[t]??Se.perspective),s?.(t),t===`equirectangular`&&a?.requiresMotionVectors&&a.setDenoiserStrategy(`edgeaware`)},handleDofMode:t=>e.pathTracer?.setUniform(`dofMode`,+(t===`look`)),handlePanoramaLonRange:e=>l(`panoLonRange`,e),handlePanoramaLatRange:e=>l(`panoLatRange`,e),handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.compositor?.setTransparentBackground(t)},handleBackgroundColor:t=>{let n=t?.isColor?t:new r.Color(t);e.pathTracer?.setUniform(`backgroundColor`,n)},handleExposure:n=>{!e.autoExposure?.enabled&&t&&(t.toneMappingExposure=n)},handleSaturation:t=>{e.compositor?.setSaturation(t)},handleConvergenceOverlay:t=>{e.pathTracer?.setUniform(`convergenceOverlay`,t),e.compositor?.setConvergenceOverlay(t),t&&!this.get(`useAdaptiveSampling`)&&n?.()},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t),i?.()},handleMaxSamples:t=>{e.pathTracer?.setUniform(`maxSamples`,t),e.pathTracer?.updateCompletionThreshold(),i?.()},handleRenderTimeLimit:()=>{i?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)},handleInteractionRenderScale:e=>{o?.(e)}}}set(e,t,{reset:n,silent:r,source:i=cx.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:I.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=cx.HOST}={}){let i=!1;for(let[n,a]of Object.entries(e)){let e=this._applyOne(n,a,r);e?.route&&((e.route.reset??!0)&&(i=!0),t||this.dispatchEvent({type:I.SETTING_CHANGED,key:n,value:a,prev:e.prev}))}(n===void 0?i:n)&&this._resetCallback?.()}_applyOne(e,t,n){let r=this._values.get(e);if(r===t)return null;this._values.set(e,t),this._sources.set(e,n);let i=sx[e];return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(Y.SETTING_UNKNOWN_KEY,`unknown setting "${e}" — stored but never applied to any stage`,{key:e})}get(e){return this._values.get(e)}getEffective(){let e={};for(let[t,n]of this._values)e[t]={value:n,source:this._sources.get(t)??cx.DEFAULT,routed:sx[t]!==void 0};return e}getAll(){return Object.fromEntries(this._values)}serialize(){let e={};for(let[t,n]of this._values){if(this._sources.get(t)!==cx.HOST||!sx[t])continue;let r=zr(n);r!==void 0&&(e[t]=r)}return e}restore(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))sx[r]?t[r]=Br(i):n.push(r);return this.setMany(t),n}applyAll(){for(let[e,t]of this._values){let n=sx[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(sx))t in e&&(this._values.set(t,e[t]),this._sources.set(t,cx.DEFAULT));for(let[t,n]of Object.entries(lx))t in e&&(this._values.set(n,e[t]),this._sources.set(n,cx.DEFAULT))}};function dx(){let{wgsl:e,bindings:t}=_l({group:fx,firstBinding:px});return{wgsl:e,bindings:t,version:sl()}}var fx,px,mx,hx,gx,_x,vx=y((()=>{Dl(),fx=0,px=3,dx().wgsl,mx={packed:`
971
+ `),hb=class extends P{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:N.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,n.uniform)(r.keyValue??.18),this.minExposureU=(0,n.uniform)(r.minExposure??.1),this.maxExposureU=(0,n.uniform)(r.maxExposure??20),this.adaptSpeedBrightU=(0,n.uniform)(r.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,n.uniform)(r.adaptSpeedDark??.5),this.epsilonU=(0,n.uniform)(r.epsilon??1e-4),this.deltaTimeU=(0,n.uniform)(1/60),this.isFirstFrameU=(0,n.uniform)(1),this.previousExposureU=(0,n.uniform)(r.initialExposure??1),this.lowPercentileU=(0,n.uniform)(r.lowPercentile??.1),this.highPercentileU=(0,n.uniform)(r.highPercentile??.9),this.centerWeightU=(0,n.uniform)(r.centerWeight??8),this.inputResW=(0,n.uniform)(1),this.inputResH=(0,n.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=r.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=r.FloatType,this._downsampleStorageTex.format=r.RGBAFormat,this._downsampleStorageTex.minFilter=r.NearestFilter,this._downsampleStorageTex.magFilter=r.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=r.FloatType,this._reductionStorageTex.format=r.RGBAFormat,this._reductionStorageTex.minFilter=r.NearestFilter,this._reductionStorageTex.magFilter=r.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationResult=(0,n.attributeArray)(1,`vec4`),this._readbackBuffer=new t.ReadbackBuffer(16),this._readbackBuffer.name=`AutoExposureAdaptation`,this._histogramBuffer=(0,n.attributeArray)(lb,`uint`).toAtomic()}_buildCompute(){this._buildDownsampleCompute(),this._buildHistogramCompute(),this._buildHistogramAnalyzeCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,r=this.epsilonU,i=this.inputResW,a=this.inputResH;this._downsampleComputeNode=(0,n.Fn)(()=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y)),c=i.div((0,n.float)(64)),l=a.div((0,n.float)(64)),u=(0,n.float)(o).mul(c),d=(0,n.float)(s).mul(l),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let i=0;i<4;i++){let a=Hi((0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(u.add((0,n.float)((i+.5)/4).mul(c))),(0,n.int)(d.add((0,n.float)((t+.5)/4).mul(l))))).xyz);(0,n.If)(a.greaterThan(r),()=>{f.addAssign(a.add(r).log()),p.addAssign(1)})}(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(s)),(0,n.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildHistogramCompute(){let e=this._downsampleTarget.texture,t=this._histogramBuffer,r=this.centerWeightU;this._histogramComputeNode=(0,n.Fn)(()=>{let i=n.localId.x;(0,n.atomicStore)(t.element(i),(0,n.uint)(0)),(0,n.workgroupBarrier)();for(let a=0;a<16;a++){let o=i.mul(16).add(a),s=o.mod(64),c=o.div(64),l=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(s),(0,n.int)(c))),u=l.x,d=l.y;(0,n.If)(d.greaterThan(0),()=>{let e=(0,n.uint)(u.div(d).sub((0,n.float)(ub)).div((0,n.float)(db)).mul((0,n.float)(lb)).floor().clamp(0,(0,n.float)(lb-1))),i=(0,n.float)(s).add(.5).div((0,n.float)(64)),a=(0,n.float)(c).add(.5).div((0,n.float)(64)),o=i.sub(.5),l=a.sub(.5),f=(0,n.uint)(o.mul(o).add(l.mul(l)).mul(r).negate().exp().mul((0,n.float)(pb)));(0,n.atomicAdd)(t.element(e),f)})}})().compute([1,1,1],[256,1,1])}_buildHistogramAnalyzeCompute(){let e=this._histogramBuffer,t=this._reductionStorageTex,r=this.lowPercentileU,i=this.highPercentileU;this._histogramAnalyzeNode=(0,n.Fn)(()=>{let a=(0,n.float)(0).toVar();(0,n.Loop)(lb,({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(t))))});let o=a.mul(r),s=a.mul(i),c=(0,n.float)(0).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)(lb,({i:t})=>{let r=(0,n.float)((0,n.atomicLoad)(e.element(t)));d.assign(c),c.addAssign(r),(0,n.If)(d.lessThan(s).and(c.greaterThan(o)),()=>{let e=(0,n.float)(ub).add((0,n.float)(t).add(.5).mul((0,n.float)(fb)));l.addAssign(e.mul(r)),u.addAssign(r)})});let f=(0,n.max)(u,(0,n.float)(1)),p=l.div(f),m=p.exp();(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(0),(0,n.uint)(0)),(0,n.vec4)(m,a,p,1)).toWriteOnly()})().compute(1,[1,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationResult,r=this.keyValueU,i=this.minExposureU,a=this.maxExposureU,o=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,n.Fn)(()=>{let d=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(0),(0,n.int)(0))).x,f=mb(d,u,r,i,a,o,s,c,l);t.element((0,n.uint)(0)).assign(f)})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>e&&this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=+!!this.isFirstFrame,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._histogramComputeNode),this.renderer.compute(this._histogramAnalyzeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.getArrayBufferAsync(this._adaptationResult.value,this._readbackBuffer).then(t=>{let n=t&&t.buffer?new Float32Array(t.buffer.slice(0)):null;this._readbackBuffer.release(),this._pendingReadback=!1,n&&e===this._readbackGeneration&&this._applyReadback(n)}).catch(()=>{try{this._readbackBuffer.release()}catch{}this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark),e.lowPercentile!==void 0&&(this.lowPercentileU.value=e.lowPercentile),e.highPercentile!==void 0&&(this.highPercentileU.value=e.highPercentile),e.centerWeight!==void 0&&(this.centerWeightU.value=e.centerWeight)}dispose(){this._downsampleComputeNode?.dispose(),this._histogramComputeNode?.dispose(),this._histogramAnalyzeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._readbackBuffer?.dispose(),this._inputTexNode?.dispose(),this._reductionReadTexNode?.dispose()}},gb=[`oidn:output`,`edgeFiltering:output`,`bilateralFiltering:output`,`asvgf:output`,`nrd:output`,`pathtracer:color`],_b=class extends P{constructor(e,i={}){super(`Compositor`,{...i,executionMode:N.ALWAYS}),this.renderer=e,this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode;let a=this._sourceTexNode.sample((0,n.uv)()),o=(0,n.mix)((0,n.vec3)((0,n.dot)(a.xyz,Fi)),a.xyz,this.saturation),s=(0,n.select)(this._transparentBackground,a.w,1);this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.colorNode=(0,n.vec4)(o,s),this.compositorMaterial.blending=r.NoBlending,this.compositorQuad=new t.QuadMesh(this.compositorMaterial)}_resolveSourceTexture(e){return e.getTexture(`bloom:output`)||this.resolveLightTexture(e)}resolveLightTexture(e){return this.resolveLightSource(e)?.texture??null}resolveLightSource(e){for(let t of gb){let n=e.getTexture(t);if(n)return{key:t,texture:n}}return null}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Fi).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let t=this._resolveSourceTexture(e);t&&(this._sourceTexNode.value=t,this.renderer.setRenderTarget(null),this.compositorQuad.render(this.renderer))}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},vb=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},yb=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},bb=!1,xb=[],Sb=new WeakMap;function Cb(e){bb=!!e}function wb(){return xb.slice()}function Tb(){xb.length=0}function Eb(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var Db=e=>!e||!e.image||!(e.image.width>0);function Ob(e,t,n){if(!bb){n();return}let r=Sb.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},Sb.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&kb(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=Eb(e).filter(t=>Db(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function kb(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(Db(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&xb.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}var Ab=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(Y.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new vb,this.eventBus=new yb,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(Ob(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};jt();var jb=vt(`engine`),Mb=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return t!==`time`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,jb.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},Nb=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,n){try{return await this.renderer.readRenderTargetPixelsAsync(this.draw(e,t,n),0,0,t,n)}finally{this.release()}}draw(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();return this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i),this.target}release(){this.target?.dispose(),this.target=null}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};R();var Pb=new r.Vector3,Fb=new r.Vector3;function Ib(e,t){return Fb.subVectors(e,t.position).dot(t.getWorldDirection(Pb))}function Lb(e,t,n=!1){return n?e.distance:Ib(e.point,t)}var Rb=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:I.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=this.pathTracer?.cameraProjection?.value===Se.equirectangular,r=Lb(e,this.camera,t);this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:r/this.assetLoader.getSceneScale(),worldDistance:r})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}pickSurface(e,t){return this.raycaster.setFromCamera({x:e,y:t},this.camera),this.filterValidIntersects(this.raycaster.intersectObjects(this.scene.children,!0))[0]??null}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:I.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:I.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:I.FOCUS_CHANGED,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:I.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},zb="var e=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}};let t=null;async function n(e,t){return t||(await navigator.storage.getDirectory()).getDirectoryHandle(e,{create:!0})}self.onmessage=async({data:r})=>{let{id:i,op:a,args:o}=r;try{if(a===`init`){t=new e(n(o.namespace,o.root)),postMessage({id:i,result:{}});return}let r=await t[a](o),s=r?.buffer instanceof ArrayBuffer?[r.buffer]:[];postMessage({id:i,result:r},s)}catch(e){postMessage({id:i,error:{name:e.name,message:e.message}})}};",Bb=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,zb],{type:`text/javascript;charset=utf-8`});function Vb(e){let t;try{if(t=Bb&&(self.URL||self.webkitURL).createObjectURL(Bb),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(zb),{type:`module`,name:e?.name})}}function Hb({name:e,message:t}){let n=Error(t);return n.name=e,n}var Ub=class{constructor({namespace:e,root:t=null}){this._worker=new Vb,this._pending=new Map,this._nextId=0,this._worker.onmessage=({data:e})=>{let t=this._pending.get(e.id);t&&(this._pending.delete(e.id),e.error?t.reject(Hb(e.error)):t.resolve(e.result))},this._ready=this.call(`init`,{namespace:e,root:t})}call(e,t,n=[]){return this._worker?new Promise((r,i)=>{let a=this._nextId++;this._pending.set(a,{resolve:r,reject:i}),this._worker.postMessage({id:a,op:e,args:t},n)}):Promise.reject(Error(`storage: transport disposed`))}dispose(){this._worker?.terminate(),this._worker=null;for(let{reject:e}of this._pending.values())e(Error(`storage: transport disposed`));this._pending.clear()}};function Wb(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}async function Gb(e){let t=typeof navigator<`u`?navigator.storage:null;if(!t?.getDirectory)return{root:null,reason:`this browser has no origin private file system`};try{return{root:await(await t.getDirectory()).getDirectoryHandle(e,{create:!0})}}catch(e){return{root:null,reason:`${e.name}: ${e.message}`}}}async function Kb({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await Gb(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(Wb()||typeof Worker>`u`))return{storage:sr({namespace:e,root:r.root})};let i=new Ub({namespace:e,root:t}),a=new or({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function qb(e){let t=Pu.get(e);t||(t={refs:0,opened:Kb({namespace:e})},Pu.set(e,t)),t.refs++;let{storage:n,reason:r}=await t.opened;t.storage=n;let i=!1,a=()=>{i||(i=!0,t.refs--,!(t.refs>0)&&(Pu.get(e)===t&&Pu.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}Ys();var Jb=864e5,Yb=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),Xb=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),Zb=(e,t)=>e.headers?.get?.(t)??null,Qb=e=>e.reason??new DOMException(`aborted`,`AbortError`);function $b(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function ex(e,{onProgress:t,signal:n}){let r=Number(Zb(e,`content-length`))||0,i=Zb(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),Qb(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(Xb(s,r))}return new Blob(o,{type:i})}var tx=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),nx=()=>{},rx=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(Wn.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=$b(e),policy:r=Yb.REVALIDATE,maxAgeMs:i=Jb,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==Yb.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===Yb.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(Xb(c.size,c.size)),{file:tx(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw Qb(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(Zb(s,`content-length`))||0,l={url:e,contentType:Zb(s,`content-type`)??``,lastModified:Zb(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:tx(await ex(s,{onProgress:r,signal:i}),n,l.contentType),release:nx,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(Xb(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:tx(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=Zb(n,`last-modified`),t=n.status===206?Number(Zb(n,`content-range`)?.match(/\/(\d+)$/)?.[1])||null:Number(Zb(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};function ix(e,t,n){return new rx(t).fetch(e,n)}function ax(){return new rx(Fu(Ks().cacheNamespace))}async function ox(e,{downloads:t=ax(),...n}={}){if(!t._storage||!/^https?:/i.test(e))return{url:e,release:nx,cached:!1};let{file:r,release:i}=await t.fetch(e,n),a=URL.createObjectURL(r);return{url:a,cached:!0,release:()=>{URL.revokeObjectURL(a),i()}}}R();var sx={maxBounces:{uniform:`maxBounces`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},maxSubsurfaceSteps:{uniform:`maxSubsurfaceSteps`,reset:!0},maxTransparentBounces:{uniform:`maxTransparentBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},backgroundBlurriness:{uniform:`backgroundBlurriness`,reset:!0},backgroundBlurSamples:{uniform:`backgroundBlurSamples`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},groundProjectionEnabled:{uniform:`groundProjectionEnabled`,reset:!0},groundProjectionRadius:{uniform:`groundProjectionRadius`,reset:!0},groundProjectionHeight:{uniform:`groundProjectionHeight`,reset:!0},groundProjectionLevel:{uniform:`groundProjectionLevel`,reset:!0},enableGroundCatcher:{uniform:`enableGroundCatcher`,reset:!0},groundCatcherHeight:{uniform:`groundCatcherHeight`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},panoramaLevelHorizon:{uniform:`panoLevelHorizon`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},unitsPerMetre:{uniform:`unitsPerMetre`,reset:!0},dofMode:{handler:`handleDofMode`,reset:!0},dofBlur:{uniform:`dofBlur`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},shadowTerminatorOffset:{uniform:`shadowTerminatorOffset`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},noiseThreshold:{uniform:`noiseThreshold`,reset:!0},adaptiveMinSamples:{uniform:`adaptiveMinSamples`,reset:!0},adaptiveStopFraction:{uniform:`adaptiveStopFraction`,reset:!0},usePixelFreeze:{uniform:`usePixelFreeze`,reset:!0},pixelFreezeThreshold:{uniform:`pixelFreezeThreshold`,reset:!0},pixelFreezeStability:{uniform:`pixelFreezeStability`,reset:!0},convergenceOverlay:{handler:`handleConvergenceOverlay`,reset:!1},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},cameraProjection:{handler:`handleCameraProjection`,reset:!0},panoramaLonRange:{handler:`handlePanoramaLonRange`,reset:!0},panoramaLatRange:{handler:`handlePanoramaLatRange`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},interactionRenderScale:{handler:`handleInteractionRenderScale`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},backgroundColor:{handler:`handleBackgroundColor`,reset:!0},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},cx=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),lx={bounces:`maxBounces`,debugMode:`visMode`},ux=class extends r.EventDispatcher{constructor(e=V,{issues:t=null}={}){super(),this._issues=t,this._values=new Map,this._sources=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind(e){this._pathTracer=e.stages.pathTracer,this._resetCallback=e.resetCallback,this._delegates={},this._handlers=this._buildHandlers(e)}_buildHandlers({stages:e,renderer:t,resetCallback:n,reconcileCompletion:i,denoisingManager:a,onInteractionRenderScale:o,onCameraProjection:s}){let c=new r.Vector2,l=(t,n)=>{c.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,c)};return{handleCameraProjection:t=>{e.pathTracer?.setUniform(`cameraProjection`,Se[t]??Se.perspective),s?.(t),t===`equirectangular`&&a?.requiresMotionVectors&&a.setDenoiserStrategy(`edgeaware`)},handleDofMode:t=>e.pathTracer?.setUniform(`dofMode`,+(t===`look`)),handlePanoramaLonRange:e=>l(`panoLonRange`,e),handlePanoramaLatRange:e=>l(`panoLatRange`,e),handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.compositor?.setTransparentBackground(t)},handleBackgroundColor:t=>{let n=t?.isColor?t:new r.Color(t);e.pathTracer?.setUniform(`backgroundColor`,n)},handleExposure:n=>{!e.autoExposure?.enabled&&t&&(t.toneMappingExposure=n)},handleSaturation:t=>{e.compositor?.setSaturation(t)},handleConvergenceOverlay:t=>{e.pathTracer?.setUniform(`convergenceOverlay`,t),e.compositor?.setConvergenceOverlay(t),t&&!this.get(`useAdaptiveSampling`)&&n?.()},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t),i?.()},handleMaxSamples:t=>{e.pathTracer?.setUniform(`maxSamples`,t),e.pathTracer?.updateCompletionThreshold(),i?.()},handleRenderTimeLimit:()=>{i?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)},handleInteractionRenderScale:e=>{o?.(e)}}}set(e,t,{reset:n,silent:r,source:i=cx.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:I.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=cx.HOST}={}){let i=!1;for(let[n,a]of Object.entries(e)){let e=this._applyOne(n,a,r);e?.route&&((e.route.reset??!0)&&(i=!0),t||this.dispatchEvent({type:I.SETTING_CHANGED,key:n,value:a,prev:e.prev}))}(n===void 0?i:n)&&this._resetCallback?.()}_applyOne(e,t,n){let r=this._values.get(e);if(r===t)return null;this._values.set(e,t),this._sources.set(e,n);let i=sx[e];return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(Y.SETTING_UNKNOWN_KEY,`unknown setting "${e}" — stored but never applied to any stage`,{key:e})}get(e){return this._values.get(e)}getEffective(){let e={};for(let[t,n]of this._values)e[t]={value:n,source:this._sources.get(t)??cx.DEFAULT,routed:sx[t]!==void 0};return e}getAll(){return Object.fromEntries(this._values)}serialize(){let e={};for(let[t,n]of this._values){if(this._sources.get(t)!==cx.HOST||!sx[t])continue;let r=zr(n);r!==void 0&&(e[t]=r)}return e}restore(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))sx[r]?t[r]=Br(i):n.push(r);return this.setMany(t),n}applyAll(){for(let[e,t]of this._values){let n=sx[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(sx))t in e&&(this._values.set(t,e[t]),this._sources.set(t,cx.DEFAULT));for(let[t,n]of Object.entries(lx))t in e&&(this._values.set(n,e[t]),this._sources.set(n,cx.DEFAULT))}};function dx(){let{wgsl:e,bindings:t}=_l({group:fx,firstBinding:px});return{wgsl:e,bindings:t,version:sl()}}var fx,px,mx,hx,gx,_x,vx,yx,bx=y((()=>{Dl(),fx=0,px=3,dx().wgsl,mx={packed:`
972
972
  @group(0) @binding(0) var<storage, read> src: array<u32>;
973
973
 
974
974
  fn rayzee_source( x: u32, y: u32 ) -> vec4<f32> {
@@ -979,7 +979,29 @@ fn rayzee_source( x: u32, y: u32 ) -> vec4<f32> {
979
979
 
980
980
  fn rayzee_source( x: u32, y: u32 ) -> vec4<f32> {
981
981
  return textureLoad( src, vec2<u32>( x, y ), 0 );
982
- }`},hx=(e,t)=>`
982
+ }`},hx={rgba8:`
983
+ @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
984
+
985
+ fn rayzee_store( i: u32, linear: vec4<f32>, mapped: vec3<f32> ) {
986
+ let b8 = rayzee_to_u8( rayzee_encode( mapped, params.mode ) );
987
+ var a8 = 255u;
988
+ if ( params.alpha == 1u ) { a8 = rayzee_to_u8( vec3<f32>( linear.a ) ).x; }
989
+ dst[ i ] = b8.x | ( b8.y << 8u ) | ( b8.z << 16u ) | ( a8 << 24u );
990
+ }`,planar:`
991
+ @group(0) @binding(1) var<storage, read_write> dst: array<f32>;
992
+
993
+ fn rayzee_store( i: u32, linear: vec4<f32>, mapped: vec3<f32> ) {
994
+ var c = clamp( mapped, vec3<f32>( 0.0 ), vec3<f32>( 1.0 ) );
995
+ if ( ! rayzee_output_encoded( params.mode ) ) {
996
+ let m = max( mapped, vec3<f32>( 0.0 ) );
997
+ c = select( pow( m, vec3<f32>( 1.0 / 2.2 ) ), vec3<f32>( 0.0 ), m <= vec3<f32>( 0.0 ) );
998
+ }
999
+ let n = params.width * params.height;
1000
+ dst[ i ] = c.r;
1001
+ dst[ n + i ] = c.g;
1002
+ dst[ 2u * n + i ] = c.b;
1003
+ dst[ 3u * n + i ] = linear.a;
1004
+ }`},gx={rgba8:4,planar:16},_x=(e,t,n)=>`
983
1005
  struct Params {
984
1006
  width: u32,
985
1007
  height: u32,
@@ -990,11 +1012,11 @@ struct Params {
990
1012
  alpha: u32,
991
1013
  };
992
1014
 
993
- @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
994
1015
  @group(0) @binding(2) var<uniform> params: Params;
995
1016
  ${mx[t]}
996
1017
 
997
1018
  ${e}
1019
+ ${hx[n]}
998
1020
 
999
1021
  @compute @workgroup_size(8, 8)
1000
1022
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
@@ -1004,16 +1026,12 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1004
1026
  if ( params.flipY == 1u ) { srcY = params.height - 1u - gid.y; }
1005
1027
 
1006
1028
  let linear = rayzee_source( gid.x, srcY );
1007
- let mapped = rayzee_tone_map( linear.rgb, params.mode, params.exposure, params.saturation );
1008
- let b8 = rayzee_to_u8( rayzee_encode( mapped, params.mode ) );
1009
- var a8 = 255u;
1010
- if ( params.alpha == 1u ) { a8 = rayzee_to_u8( vec3<f32>( linear.a ) ).x; }
1011
- dst[ gid.y * params.width + gid.x ] = b8.x | ( b8.y << 8u ) | ( b8.z << 16u ) | ( a8 << 24u );
1029
+ rayzee_store( gid.y * params.width + gid.x, linear, rayzee_tone_map( linear.rgb, params.mode, params.exposure, params.saturation ) );
1012
1030
  }
1013
- `,gx=32,_x=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`}={}){this.device=e,this.label=t,this.input=n,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(gx),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=dx();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:hx(e,this.input)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*4;this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:gx,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:o,height:s}=this;this._paramU32[0]=o,this._paramU32[1]=s,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this.device.queue.writeBuffer(this._params,0,this._paramData);let c=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),l=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...c,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:o*s*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),u=this.device.createCommandEncoder({label:this.label}),d=u.beginComputePass();d.setPipeline(this._pipeline),d.setBindGroup(0,l),d.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(s/8)),d.end(),u.copyBufferToBuffer(this._storage,0,this._map,0,o*s*4),this.device.queue.submit([u.finish()]),await this._map.mapAsync(GPUMapMode.READ);let f=new Uint8ClampedArray(this._map.getMappedRange().slice(0));return this._map.unmap(),f}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}}));vx();var yx=512,bx=4<<20,xx=15e8,Sx=new TextDecoder;function Cx(e){return e.length>=2&&e[0]===31&&e[1]===139}function wx(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Tx(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function Ex(e){return Cx(e)?`gzip`:wx(e)?`zip`:Tx(e)?`tar`:null}function Dx(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return Sx.decode(e.subarray(t,r))}function Ox(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=Dx(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function kx(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function Ax(e){let t=Sx.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var jx=e=>e+(yx-e%yx)%yx,Mx=e=>e===`L`||e===`x`||e===`X`;function Nx(e){let t=Dx(e,345,155),n=Dx(e,0,100);return{type:String.fromCharCode(e[156]||48),size:Ox(e,124,12),name:t?`${t}/${n}`:n}}function Px(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:kx(t)||null}function Fx(e){for(let t=0;t<yx;t++)if(e[t]!==0)return!1;return!0}var Ix=class{constructor({filter:e=null,retain:t=null,byteBudget:n=xx,onEntry:r=null}={}){this.filter=e,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(yx),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(yx-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===yx&&(this._headerLen=0,this._bodyStart=t+n,this._readHeader())}else{let t=Math.min(this._remaining,e.length-n);if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<yx;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=Nx(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=jx(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,Mx(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=Px(n,a);o&&(this.listing.push({path:o,size:r}),this._indexed=this.filter?this.filter(o,r):!0,this._indexed&&!(this.retain&&!this.retain(o,r))&&(this.retainedBytes+r>this.byteBudget?this.truncated=!0:(this._dst=new Uint8Array(r),this.retainedBytes+=r)),this._remaining===0&&this._endBody())}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=Dx(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=Ax(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}};async function Lx(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await Rx(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function Rx(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=bx){let r=Math.min(n+bx,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=bx){let i=Math.min(r+bx,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function zx(e,t={}){let{onProgress:n,...r}=t,i=new Ix(r),a=0,o=0;return await Lx(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}var Bx=1<<20;async function Vx(e,{onProgress:t=null}={}){let n=e.size,r=[],i=null,a=0,o=null,s=0,c=0,l=async(t,r)=>{if(i&&t>=a&&t+r<=a+i.length)return i.subarray(t-a,t-a+r);let o=Math.min(n,t+Math.max(r,Bx));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+yx<=n;){let e=await l(s,yx);if(Fx(e))break;let{type:n,size:i,name:a}=Nx(e),u=o??a;o=null;let d=s+yx;if(Mx(n)){let e=await l(d,i);o=n===`L`?Dx(e,0,e.length):Ax(e)}else{let e=Px(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+jx(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function Hx(){let e=new Ix({retain:()=>!1});return{push:t=>e.push(t),finish:()=>(e.end(),e.listing.filter(e=>e.offset!==void 0))}}async function Ux(e,t={}){let{index:n=null,headersOnly:r=!1,onProgress:i=null,...a}=t,o,s,c,l,u=null;if(n||r){u=n?.listing??await Vx(e,{onProgress:i});let{filter:t}=a;s=u.map(e=>!t||t(e.path,e.size)?{...e}:{path:e.path,size:e.size}),o=Object.create(null),c=0,l=!1}else{let t=new Ix({...a});await Rx(e,e=>t.push(e)),t.end(),{entries:o,listing:s,retainedBytes:c,truncated:l}=t.result()}let d=new Map;for(let e of s)e.offset!==void 0&&d.set(e.path,e);return{entries:o,listing:s,read:async t=>{if(o[t])return o[t];let n=d.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},readHead:async(t,n)=>{if(o[t])return o[t].subarray(0,n);let r=d.get(t);return r?new Uint8Array(await e.slice(r.offset,r.offset+Math.min(r.size,n)).arrayBuffer()):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function Wx(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=kx(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function Gx(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var Kx=101010256,qx=117853008,Jx=101075792,Yx=33639248,Xx=67324752,Zx=65557,Qx=new TextDecoder;async function $x(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function eS(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function tS(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function nS(e){let t=e.size,n=await $x(e,Math.max(0,t-Zx-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===Kx){i=e;break}if(i<0)throw Error(`zip: end of central directory not found`);let a=r.getUint16(i+10,!0),o=r.getUint32(i+12,!0),s=r.getUint32(i+16,!0);if(a===65535||o===4294967295||s===4294967295){let t=i-20;if(t<0||r.getUint32(t,!0)!==qx)throw Error(`zip: ZIP64 locator missing`);let n=eS(r,t+8),c=new DataView((await $x(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==Jx)throw Error(`zip: ZIP64 end record missing`);a=eS(c,32),o=eS(c,40),s=eS(c,48)}let c=await $x(e,s,s+o),l=new DataView(c.buffer),u=[],d=0;for(let e=0;e<a&&d+46<=c.length;e++){if(l.getUint32(d,!0)!==Yx)throw Error(`zip: corrupt central directory`);let e=l.getUint16(d+8,!0),t=l.getUint16(d+10,!0),n=l.getUint32(d+20,!0),r=l.getUint32(d+24,!0),i=l.getUint16(d+28,!0),a=l.getUint16(d+30,!0),o=l.getUint16(d+32,!0),s=l.getUint32(d+42,!0),f=c.subarray(d+46,d+46+i),p=e&2048?Qx.decode(f):tS(f);for(let e=d+46+i,t=e+a;e+4<=t;){let t=l.getUint16(e,!0),i=l.getUint16(e+2,!0);if(t===1){let t=e+4;r===4294967295&&(r=eS(l,t),t+=8),n===4294967295&&(n=eS(l,t),t+=8),s===4294967295&&(s=eS(l,t))}e+=4+i}p.endsWith(`/`)||u.push({name:p,size:r,compSize:n,method:t,local:s,encrypted:(e&1)!=0}),d+=46+i+a+o}return u}async function rS(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await $x(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==Xx)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function iS(e,t){let n=await rS(e,t),r=await $x(e,n,n+t.compSize);if(t.method===0)return r;if(t.method===8)return t.size===0?new Uint8Array:(0,m.inflateSync)(r,{out:new Uint8Array(t.size)});throw Error(`zip: "${t.name}" uses compression method ${t.method}, which is not supported`)}async function aS(e,{filter:t=null}={}){let n=await nS(e),r=new Map,i=n.map(e=>t&&!t(e.name,e.size)?{path:e.name,size:e.size}:(r.set(e.name,e),{path:e.name,size:e.size,offset:e.local})),a=async t=>{let n=r.get(t);return n?iS(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await iS(e,n)]);let i=await rS(e,n);return e.slice(i,i+n.compSize)};return{entries:Object.create(null),listing:i,read:a,readHead:async(e,t)=>{let n=await o(e);return n?new Uint8Array(await n.slice(0,t).arrayBuffer()):null},slice:o,retainedBytes:0,truncated:!1,indexed:r.size}}var oS=1,sS=3;async function cS(e,t){return`${e}:${Rn(await Ln(t))}`}async function lS(e,{storage:t,label:n=e.name,onProgress:r=null}){if(!t||typeof DecompressionStream>`u`)return null;let i=t.area(Wn.ARCHIVES),a=await cS(`gunzip`,e),o=await i.open(a),s=!!o;if(!o){let s=await i.create(a,{label:n,expectedBytes:e.size*sS});if(!s)return null;let c=Hx(),l=new TransformStream({transform(e,t){c.push(e),t.enqueue(e)}});try{let t=e.stream().pipeThrough(new DecompressionStream(`gzip`)).pipeThrough(l),n=await s.writeStream(`data.tar`,t,{onProgress:r});await s.writeJSON(`index.json`,{v:oS,listing:c.finish()}),await s.commit({compressedBytes:e.size,tarBytes:n})}catch(e){if(await s.abort(),e?.name!==`QuotaExceededError`)throw e;return t._issue(Y.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:Wn.ARCHIVES}),null}if(o=await i.open(a,{wait:!0}),!o)return null}let c=await o.file(`data.tar`),l=await o.json(`index.json`);return!c||l?.v!==oS?(o.release(),null):{file:c,index:l,release:()=>o.release(),cached:s}}async function uS(e,t){if(!t)return null;let n=await t.area(Wn.ARCHIVES).open(await cS(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===oS?e:null}finally{n.release()}}async function dS(e,t,n){if(!t||!n)return!1;let r=await t.area(Wn.ARCHIVES).create(await cS(`tarindex`,e),{label:`${e.name} (index)`});if(!r)return!1;try{return await r.writeJSON(`index.json`,n),await r.commit(),!0}catch{return await r.abort(),!1}}var fS=`__rayzeeArchivePath`,pS=`__rayzeeArchiveLoader`,mS=64,hS=32<<20,gS=64<<20,_S={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},vS=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],yS=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],bS=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}};function xS(e){return e.isInstancedMesh?`InstancedMesh`:e.isSkinnedMesh||e.isBatchedMesh?null:e.isMesh?`Mesh`:e.isPerspectiveCamera?`PerspectiveCamera`:e.isOrthographicCamera?`OrthographicCamera`:e.isLight||e.isPoints||e.isLine||e.isSprite||e.isLOD?null:e.isGroup?`Group`:e.constructor===r.Object3D?`Object3D`:null}function SS(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[fS],delete t[pS],t}catch{throw new bS(`${t}: userData is not plain JSON`)}}var CS=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/mS)*mS;return this.sections.push({offset:t,array:e}),this.length=t+e.byteLength,{offset:t,byteLength:e.byteLength,type:e.constructor.name,length:e.length}}};function wS(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new bS(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function TS(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new bS(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=wS(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?wS(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:SS(e.userData,n)}}function ES(e,t){let n={uuid:e.uuid,userData:SS(e.userData,`texture ${e.uuid}`)};for(let t of vS)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[fS];if(r)n.path=r,n.loader=e.userData.__rayzeeArchiveLoader??`image`;else if(e.isDataTexture&&ArrayBuffer.isView(e.image?.data))n.data={section:t.add(e.image.data),width:e.image.width,height:e.image.height};else throw new bS(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function DS(e,t){let n=e.toJSON(t);n.exactColors={};for(let[t,r]of Object.entries(e))r?.isColor&&(n.exactColors[t]=[r.r,r.g,r.b]);return e.ior!==void 0&&(n.exactIor=e.ior),n}function OS(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function kS(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new CS,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=xS(e);if(!n)throw new bS(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:SS(e.userData,`${n} "${e.name}"`)};for(let t of yS)r[t]=e[t];if(r.position=e.position.toArray(),r.quaternion=e.quaternion.toArray(),r.scale=e.scale.toArray(),r.layers=e.layers.mask,e.matrixAutoUpdate||(r.matrix=e.matrix.toArray()),e.isMesh){s.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)c.set(e.uuid,e),OS(e,l);r.geometry=e.geometry.uuid,r.material=Array.isArray(e.material)?t.map(e=>e.uuid):e.material.uuid}if(e.isInstancedMesh&&(r.count=e.count,r.instanceMatrix=a.add(e.instanceMatrix.array),r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null),e.isCamera)for(let t of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])e[t]!==void 0&&(r[t]=e[t]);let i=o.push(r)-1;for(let t of e.children)u(t,i)};u(e,-1),t&&l.set(t.uuid,t);let d={textures:{},images:{}};for(let e of l.keys())d.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...s.values()].map(e=>TS(e,a)),textures:[...l.values()].map(e=>ES(e,a)),materials:[...c.values()].map(e=>DS(e,d)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function AS(e,{manifest:t,sections:n},{release:r=!1}={}){for(let t of n){let{offset:n,array:i}=t,a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<a.length;t+=hS)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+hS)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function jS(e){let t=_S[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function MS(e,t){let n=new Map,r=[...t].sort((e,t)=>e.offset-t.offset),i=null,a=0;for(let t of r){let{offset:r,byteLength:o,type:s}=t,c=jS(s),l=r+o;if(o>gS){n.set(r,new c(await e.slice(r,l).arrayBuffer()));continue}(!i||r<a||l>a+i.byteLength)&&(a=r,i=await e.slice(r,Math.min(e.size,r+gS)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function NS(e){let t=[];for(let n of e.nodes)n.instanceMatrix&&t.push(n.instanceMatrix),n.instanceColor&&t.push(n.instanceColor);for(let n of e.geometries){for(let e of Object.values(n.attributes))t.push(e.section);n.index&&t.push(n.index.section)}for(let n of e.textures)n.data&&t.push(n.data.section);return t}function PS(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function FS(e,t){for(let n of vS)t[n]!==void 0&&(e[n]=t[n]);e.repeat.fromArray(t.repeat),e.offset.fromArray(t.offset),e.center.fromArray(t.center),e.rotation=t.rotation,e.uuid=t.uuid,Object.assign(e.userData,t.userData),e.needsUpdate=!0}async function IS(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await MS(t,NS(e)),a=e=>i.get(e.offset),o={};for(let t of e.textures){let e;if(t.path){if(e=await n(t.path,t.loader),!e)throw Error(`scene graph: "${t.path}" is missing from the archive`);e.userData[fS]=t.path,e.userData[pS]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);FS(e,t),o[t.uuid]=e}let s=new r.MaterialLoader().setTextures(o),c={};for(let t of e.materials){let e=s.parse(t);for(let[n,r]of Object.entries(t.exactColors??{}))e[n]?.setRGB(r[0],r[1],r[2]);t.exactIor!==void 0&&(e.ior=t.exactIor),c[t.uuid]=e}let l={};for(let t of e.geometries){let e=new r.BufferGeometry;e.uuid=t.uuid,e.name=t.name;for(let[n,r]of Object.entries(t.attributes))e.setAttribute(n,PS(i,r));t.index&&e.setIndex(PS(i,t.index));for(let n of t.groups)e.addGroup(n.start,n.count,n.materialIndex);e.setDrawRange(t.drawRange.start,t.drawRange.count),e.userData=t.userData,l[t.uuid]=e}let u=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>c[e]):c[t.material],n;switch(t.type){case`InstancedMesh`:n=new r.InstancedMesh(l[t.geometry],e,1),n.instanceMatrix=new r.InstancedBufferAttribute(a(t.instanceMatrix),16),n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break;case`Mesh`:n=new r.Mesh(l[t.geometry],e);break;case`PerspectiveCamera`:n=new r.PerspectiveCamera;break;case`OrthographicCamera`:n=new r.OrthographicCamera;break;case`Group`:n=new r.Group;break;default:n=new r.Object3D}n.uuid=t.uuid;for(let e of yS)n[e]=t[e];if(n.position.fromArray(t.position),n.quaternion.fromArray(t.quaternion),n.scale.fromArray(t.scale),n.layers.mask=t.layers,n.userData=t.userData,t.matrix&&n.matrix.fromArray(t.matrix),n.isCamera){for(let e of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])t[e]!==void 0&&(n[e]=t[e]);n.updateProjectionMatrix()}u.push(n),t.parent>=0&&u[t.parent].add(n)}return{root:u[0],environment:e.environment?o[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var LS=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function RS(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):LS.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function zS(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function BS({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function VS(e,t){return ti().decodeImage(t===`image/png`?zS(e):e,t)}async function HS(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}async function US(e,t=RS({uri:e})){let n=BS(await VS(await HS(e),t));return n.flipY=!0,n}function WS(e,t=null){return e.loadImageSource=function(e){if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let n=this.json.images[e],i=RS(n),a=n.uri??`bufferView ${n.bufferView}`,o=(n.bufferView===void 0?HS(this.options.manager.resolveURL(r.LoaderUtils.resolveURL(n.uri,this.options.path))):this.getDependency(`bufferView`,n.bufferView).then(e=>new Uint8Array(e))).then(e=>VS(e,i)).then(e=>{let t=BS(e,{shared:!0});return n.extras&&typeof n.extras==`object`&&Object.assign(t.userData,n.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var GS=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer);function KS(e){e&&GS(e)&&e.buffer.transfer(0)}function qS(e,t){let n=e.constructor;if(GS(e))return new n(e.buffer.transfer(t*n.BYTES_PER_ELEMENT));let r=new n(t);return r.set(t<e.length?e.subarray(0,t):e),r}var JS={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},YS=9,XS=10,ZS=12,QS=13,$S=32,eC=34,tC=35,nC=43,rC=45,iC=46,aC=48,oC=57,sC=91,cC=93,lC=69,uC=101,dC=e=>e===$S||e===YS||e===XS||e===QS||e===ZS,fC=e=>e>=aC&&e<=oC,pC=15,mC=22,hC=(()=>{let e=new Float64Array(mC+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),gC=new TextDecoder;function _C(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return gC.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var vC=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&dC(e[t]);)t++;if(t<n&&e[t]===tC){for(;t<n&&e[t]!==XS;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===sC)return this.i=t+1,{type:JS.LBRACKET};if(r===cC)return this.i=t+1,{type:JS.RBRACKET};if(r===eC){let r=++t;for(;t<n&&e[t]!==eC;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:JS.STRING,value:_C(e,r,t)}}if(fC(r)||r===iC&&fC(e[t+1])||(r===rC||r===nC)&&(fC(e[t+1])||e[t+1]===iC&&fC(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(dC(n)||n===eC||n===sC||n===cC||n===tC)break;t++}return this.i=t,{type:JS.WORD,value:_C(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===rC?(i=!0,r++):t[r]===nC&&r++;let a=0,o=0,s=0;for(;r<n&&fC(t[r]);)a=a*10+(t[r]-aC),o++,r++;if(r<n&&t[r]===iC)for(r++;r<n&&fC(t[r]);)a=a*10+(t[r]-aC),o++,s++,r++;let c=0;if(r<n&&(t[r]===uC||t[r]===lC)){let e=r+1,i=!1;if(e<n&&(t[e]===rC||t[e]===nC)&&(i=t[e]===rC,e++),e<n&&fC(t[e])){let a=0;for(;e<n&&fC(t[e]);)a=a*10+(t[e]-aC),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${_C(t,e,r)}"`);let l=c-s;if(!(o<=pC&&l>=-mC&&l<=mC)){let n=Number(_C(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${_C(t,e,r)}"`);return{type:JS.NUMBER,value:n}}let u=l===0?a:l>0?a*hC[l]:a/hC[-l];return i&&(u=-u),{type:JS.NUMBER,value:u}}};function yC(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function bC(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function xC(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function SC(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function CC(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function wC(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function TC(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function EC(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function DC(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function OC(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function kC(e,t,n){let r=OC(EC(t,e)),i=OC(DC(OC(n),r)),a=DC(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function AC(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return yC();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var jC=8,MC=1,NC=2,PC=3,FC=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]);function IC(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var LC={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},RC=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.instanceIncludes=e.instanceIncludes!==!1,this._includes=new Map,this._stateIds=new WeakMap,this._nextStateId=1,this._effects=0,this._movedShapes=!1,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,transformTimes:{start:0,end:1},hasMotion:!1,warnings:[]},this.ctm=yC(),this.ctmEnd=null,this.activeTransform=PC,this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.objectBeginCTM=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){this.dirStack=[t],await this._run(new vC(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=qS(e.matrices,e.count*16),e.matricesEnd&&=qS(e.matricesEnd,e.count*16);return this.ir}_addInstance(e,t=this.ctm){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let n=this.ir.instances.get(e);n||this.ir.instances.set(e,n={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let r=(n.count+1)*16;if(r>n.matrices.length){let e=Math.max(r,n.matrices.length*2);n.matrices=qS(n.matrices,e),n.matricesEnd&&=qS(n.matricesEnd,e)}let i=n.count*16;for(let e=0;e<16;e++)n.matrices[i+e]=t[e];let a=this._ctmEndSnapshot();if(a&&!n.matricesEnd&&(n.matricesEnd=n.matrices.slice()),n.matricesEnd){let e=a||t;for(let t=0;t<16;t++)n.matricesEnd[i+t]=e[t]}n.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_ctmEndSnapshot(){return this.ctmEnd===null||IC(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===PC&&this.ctmEnd===null){this.ctm=SC(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&NC?SC(t,e):t,this.activeTransform&MC&&(this.ctm=SC(this.ctm,e))}_setCTM(e){if(this.activeTransform===PC){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&NC?e:t,this.activeTransform&MC&&(this.ctm=e)}_pushGraphicsState(){this.attributeStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform,material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation})}_popGraphicsState(){let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation})}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==JS.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==JS.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===JS.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==JS.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===JS.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===JS.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==JS.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===JS.NUMBER){let t=[];for(;n()&&t.length<jC;){let e=this._next();if(e.type!==JS.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(LC[e]||Float64Array)(jC*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==JS.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=qS(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:qS(r,i)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==JS.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===JS.NUMBER||e.type===JS.STRING)return e.value;if(e.type===JS.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==JS.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);FC.has(e.value)&&this._effects++;let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this._setCTM(yC());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(CC(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(wC(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(TC(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=kC([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(AC(t));break}case`Transform`:this._setCTM(this._readBracketedOrBareNumbers(16));break;case`ConcatTransform`:this._concat(this._readBracketedOrBareNumbers(16));break;case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),{ctm:this.ctm,ctmEnd:this.ctmEnd});break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd);break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:AC(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=AC(n));break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),filename:this._str(e.filename,null)};break}case`Integrator`:case`Sampler`:case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=yC(),this.ctmEnd=null,this.activeTransform=PC,this.state={material:null,areaLight:null,reverseOrientation:!1};break;case`WorldEnd`:break;case`AttributeBegin`:this._pushGraphicsState();break;case`AttributeEnd`:this._popGraphicsState();break;case`TransformBegin`:this.transformStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform});break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=MC:e===`EndTime`?this.activeTransform=NC:e===`All`?this.activeTransform=PC:this._warn(`ActiveTransform "${e}" not recognised`);break}case`TransformTimes`:{let[e,t]=this._readNumbers(2);this.ir.transformTimes={start:e,end:t};break}case`MediumInterface`:this._peek()&&this._peek().type===JS.STRING&&this._next(),this._peek()&&this._peek().type===JS.STRING&&this._next();break;case`MakeNamedMedium`:this._skipNamedAndParams();break;case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ctmEnd!==null&&!IC(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-light`,`animated LightSource transforms are not supported — using the start transform`),this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation},t=this.currentObject===null?this._ctmEndSnapshot():null;t?e.ctmEnd=t:this.currentObject!==null&&this.ctmEnd!==null&&!IC(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-template`,`animated transforms inside ObjectBegin are not supported — using the start transform`),this._emitShape(e);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this._pushGraphicsState(),this.currentObject=e,this.objectBeginCTM=this.ctm.slice(),this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:this.currentObject=null,this.objectBeginCTM=null,this._popGraphicsState();break;case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=SC(AC(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=this._includeKey(e,t);if(n!==null&&this._placeRepeat(n,e))return;let r=await this.resolveInclude(e,t);if(r==null){this._warn(`Include target not found: ${e}`);return}let i=n===null?null:this._includeState(),a=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(a);try{await this._run(new vC(r))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t,r)}i&&this._sameIncludeState(i)&&!this._includes.has(n)&&this._includes.set(n,{start:i.shapes,end:this.ir.shapes.length,ctm:i.ctm.slice(),template:null})}_includeKey(e,t){return!this.instanceIncludes||this.currentObject!==null||this.ctmEnd!==null||this.activeTransform!==PC||this.state.areaLight?null:`${t}\0${e}\0${this._stateId(this.state.material)}\0${this.state.reverseOrientation}`}_stateId(e){if(!e)return 0;let t=this._stateIds.get(e);return t===void 0&&this._stateIds.set(e,t=this._nextStateId++),t}_includeState(){return{shapes:this.ir.shapes.length,effects:this._effects,ctm:this.ctm,attributes:this.attributeStack.length,transforms:this.transformStack.length,material:this.state.material,reverseOrientation:this.state.reverseOrientation}}_sameIncludeState(e){return this._effects===e.effects&&this.ctmEnd===null&&this.activeTransform===PC&&IC(this.ctm,e.ctm)&&this.attributeStack.length===e.attributes&&this.transformStack.length===e.transforms&&this.state.material===e.material&&this.state.areaLight===null&&this.state.reverseOrientation===e.reverseOrientation}_placeRepeat(e,t){let n=this._includes.get(e);if(!n)return!1;if(n.template===null){let{start:r,end:i}=n;if(i===r||this.ir.instanceCount+2>this.maxPlacements)return!1;for(let t=r;t<i;t++)if(!this.ir.shapes[t])return this._includes.delete(e),!1;let a=`${t}#${this.ir.objects.size}`,o=AC(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=SC(o,c=t.ctm)),t.relativeCTM=l,s.push(t),this.ir.shapes[e]=null}this.ir.objects.set(a,s),this._addInstance(a,n.ctm),n.template=a,this._movedShapes=!0}return this._addInstance(n.template),!0}_skipTypeAndParams(){this._peek()&&this._peek().type===JS.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===JS.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnOnce(e,t){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(t))}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}},zC={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},BC=[.92,.92,.92];function VC(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function HC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function UC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function WC(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:VC(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=GC(i.value[0]);return e&&zC[e]?{rgb:zC[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function GC(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(zC))if(e.toLowerCase().includes(t))return t;return null}function KC(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=HC(e,`uroughness`,null),r=HC(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function qC(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await WC(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await WC(i,`reflectance`,t,null),n=i.eta,r=i.k,c=n&&n.type===`spectrum`&&typeof n.value[0]==`string`;if(e.rgb||e.texture)s(e);else if(n&&r&&!c){let e=(await WC(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await WC(i,`k`,t,[3.9,2.45,2.14])).rgb,r=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);o([r(e[0],n[0]),r(e[1],n[1]),r(e[2],n[2])])}else o(n?(await WC(i,`eta`,t,BC)).rgb||BC:zC.cu);a.metalness=1,a.roughness=KC(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=HC(i,`eta`,1.5),a.roughness=KC(i,0),a.thickness=n===`thindielectric`?0:HC(i,`thickness`,0);break;case`coateddiffuse`:s(await WC(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=KC(i,0);break;case`diffusetransmission`:{let e=await WC(i,`transmittance`,t,[.25,.25,.25]);s(await WC(i,`reflectance`,t,[.25,.25,.25])),a.transmission=e.rgb?(e.rgb[0]+e.rgb[1]+e.rgb[2])/3:.5,a.roughness=1,a.ior=1;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,HC(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,r]=await Promise.all([qC(o,t),qC(s,t)]),i=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,r.color,n),a.roughness=i(e.roughness,r.roughness),a.metalness=i(e.metalness,r.metalness),a.ior=i(e.ior??1.5,r.ior??1.5),a.transmission=i(e.transmission??0,r.transmission??0),a.thickness=i(e.thickness??0,r.thickness??0),a.clearcoat=i(e.clearcoat??0,r.clearcoat??0),a.clearcoatRoughness=i(e.clearcoatRoughness??0,r.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,r.emissive,n),a.emissiveIntensity=i(e.emissiveIntensity??0,r.emissiveIntensity??0),a.map=(n<.5?e.map:r.map)||null;break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await WC(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}return a.roughness=Math.max(0,Math.min(1,a.roughness)),a}function JC(e){return e===3?3/16:3/(8*e)}function YC(e){return 1/(e+3/(8*JC(e)))}function XC(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function ZC(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function QC(e,t){let n=e.length/3,r=XC(n,t),i=r.edgeV0.length,a=ZC(e,r,n,JC,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function $C(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=QC(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=ZC(i,XC(s,a),s,YC,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function ew(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}var tw=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})();function nw(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function rw(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?AC(t):null,c=e.srgb?tw:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=ew(f,p,m);nw(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var iw=2;function aw(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function ow(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function sw(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function cw(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function lw(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function uw(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?aw(c,i):ow(c,i);let l=t===`bspline`?s:s*3,u=0,d=0,f=0;for(let t=0;t<4;t++){let n=(l+t)*3;u+=i[t]*e[n],d+=i[t]*e[n+1],f+=i[t]*e[n+2]}a[o]=u,a[o+1]=d,a[o+2]=f}function dw(e,t,n){let r=lw(e,t);if(r<1)return null;let i=Math.max(1,Math.round(n*r)),a=new Float64Array((i+1)*3),o=[0,0,0,0];for(let n=0;n<=i;n++)uw(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function fw(e,t,n,r,i){let a=e[t*3],o=e[t*3+1],s=e[t*3+2],c=n[r*3],l=n[r*3+1],u=n[r*3+2],d=n[i*3]-c,f=n[i*3+1]-l,p=n[i*3+2]-u,m=d*d+f*f+p*p,h=m>0?((a-c)*d+(o-l)*f+(s-u)*p)/m:0;return h=h<0?0:h>1?1:h,Math.hypot(a-c-h*d,o-l-h*f,s-u-h*p)}function pw(e,t,n,r,i,a){let{points:o,count:s,spans:c}=n;if(s<3)return null;let l=new Float64Array((s-1)*3),u=[0,0,0,0],d=s-1;for(let n=0;n<d;n++)uw(e,t,c,(n+.5)/d*c,u,l,n*3);let f=0;for(let e=0;e<d;e++)f=Math.max(f,fw(l,e,o,e,e+1));let p=e=>Math.max(f,r*.5*(i+(a-i)*(e/d))),m=(e,t)=>{for(let n=e+1;n<t;n++)if(fw(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(fw(l,n,o,e,t)>p(n+.5))return!1;return!0},h=new Int32Array(s),g=0;h[g++]=0;for(let e=0;e<d;){let t=e+1;for(;t<d&&m(e,t+1);)t++;h[g++]=t,e=t}return g===s?null:h.subarray(0,g)}function mw(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??iw)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=dw(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?pw(t,n,c,e.tolerance,r,i):null,f=d?d.length:u,p=s>=3?s:s*2,m=new Float32Array(f*p*3),h=[0,0,0],g=[0,0,0],_=[0,0,0],v=[0,0,0],y=!1,b=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(h[0]=l[n*3]-l[t*3],h[1]=l[n*3+1]-l[t*3+1],h[2]=l[n*3+2]-l[t*3+2],sw(h),y){let e=g[0]*h[0]+g[1]*h[1]+g[2]*h[2];g[0]-=e*h[0],g[1]-=e*h[1],g[2]-=e*h[2],Math.hypot(g[0],g[1],g[2])<1e-9&&cw(h,[0,1,0],g),sw(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],cw(h,g,v),g[0]=v[0],g[1]=v[1],g[2]=v[2];else{let e=Math.abs(h[0]),t=Math.abs(h[1]),n=Math.abs(h[2]);cw(h,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],g)}Math.hypot(g[0],g[1],g[2])<1e-9&&cw(h,[0,1,0],g),sw(g),y=!0}if(d&&d[b]!==e)continue;cw(h,g,_),sw(_);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,f=l[e*3],x=l[e*3+1],S=l[e*3+2];for(let e=0;e<p;e++){let t,n,r;if(s>=3){let i=e/s*Math.PI*2,a=Math.cos(i),o=Math.sin(i);t=g[0]*a+_[0]*o,n=g[1]*a+_[1]*o,r=g[2]*a+_[2]*o}else{let i=e<2?g:_,a=e%2==0?-1:1;t=i[0]*a,n=i[1]*a,r=i[2]*a}let i=(b*p+e)*3;m[i]=f+t*c,m[i+1]=x+n*c,m[i+2]=S+r*c}b++}let x=s,S=new Uint32Array((f-1)*x*6),C=0;for(let e=0;e<f-1;e++)for(let t=0;t<x;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*p+n,a=e*p+r,o=(e+1)*p+r,c=(e+1)*p+n;S[C++]=i,S[C++]=a,S[C++]=o,S[C++]=i,S[C++]=o,S[C++]=c}return{positions:m,indices:C===S.length?S:qS(S,C)}}var hw=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],gw=4096;function _w(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function vw(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return qS(e,n)}function yw(e){return e instanceof Float32Array?e:Float32Array.from(e)}var bw=1e3,xw=45e6,Sw=6e6,Cw=6e7,ww=8e6,Tw=256,Ew=4096,Dw=5e5,Ow=2,kw={flat:1,ribbon:1,cylinder:2},Aw=.05;function jw(e,t){if(e.count!==t.count)return!1;for(let n=0,r=e.count*16;n<r;n++)if(e.matrices[n]!==t.matrices[n])return!1;return!0}function Mw(e,t){let n=Math.min(e.width,gw),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function Nw(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var Pw=class{constructor(e={}){this.maxTriangles=e.maxTriangles??xw,this.maxPlacements=e.maxPlacements??Sw,this.mergeShapesAbove=e.mergeShapesAbove??Tw,this.curveSteps=e.curveSteps??Ow,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??Aw,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._keepShapes=new Set;for(let{name:t}of e.animatedInstances??[])for(let n of e.objects.get(t)??[])this._keepShapes.add(n);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=UC(t.params,`filename`,null);this._plyUsers.set(e,(this._plyUsers.get(e)??0)+1)}for(let t of e.objects.values())for(let e of t)e.type===`plymesh`&&this._plyHeld.add(UC(e.params,`filename`,null));this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0,this._animated=[];for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;if(this._batches&&!r.motion&&i.getAttribute(`position`).count<=Ew){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(UC(r.params,`filename`,null));let o=this._meshFromGeometry(r,i,a,r.ctm,`shape_${n}`);o&&(t.add(o),r.motion&&this._animate(o,r.motion))}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),await this._buildAnimatedPlacements(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=e.animation?this._buildClip(e,n):[],a=await this._buildEnvironment(e.lights);return this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:a,animations:i,report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4,o=(e,o,s,c,l,u,d)=>{let f=Math.max(0,this.maxPlacements-this.placementCount),p=Math.min(e.count,f);if(p<e.count&&(this.skippedForBudget+=e.count-p),p===0)return;let m=new r.InstancedMesh(o,s,p);m.name=`instance_${n++}`,m.frustumCulled=!1;for(let t=0;t<p;t++){if(c)xC(i,e.matrices,t*16,c);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];m.setMatrixAt(t,a.fromArray(this.convertHandedness?SC(hw,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<bw&&this.report.push({mesh:`${m.name} ×${p}`,shape:l,material:u,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o.getAttribute(`uv`)?`yes`:`NO`,normals:o.getAttribute(`normal`)?`yes`:`NO`,emissive:s.emissiveIntensity>0?`#${s.emissive.getHexString()}×${s.emissiveIntensity}`:`-`,size:`instanced`,tris:d})},s=(e,t)=>{t&&t.triangles>0&&o(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:t,list:n,template:r}of this._samePlacementGroups(e)){if(!r){this.droppedNoTemplate+=n.count,this.warn(`ObjectInstance "${t}" has no template — ${n.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of r)t.type!==`plymesh`&&e++;let i=e>=2?new Map:null;for(let e of r){if(this._overBudget()){this.skippedForBudget+=n.count;continue}let[r,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!r)continue;if(i&&e.type!==`plymesh`&&r.getAttribute(`position`).count<=Ew){this._geometryCache.delete(e);let t=this._appendToBatch(i,e,r,a,e.relativeCTM||e.ctm);this._releaseMerged(e,r),s(n,t);continue}let c=this._accountGeometry(r);o(n,r,this._materialForGeometry(e,r,a,`instances_${t}`),e.relativeCTM||e.ctm,e.type,e.material?.type||`diffuse`,c)}if(i)for(let e of i.values())s(n,e[0]),s(n,e[1]);KS(n.matrices),KS(n.matricesEnd)}}_samePlacementGroups(e){let t=[],n=new Map;for(let[r,i]of e.instances){let a=e.objects.get(r);if(!a||i.matricesEnd){t.push({name:r,list:i,template:a});continue}let o=`${i.count}:${Array.prototype.join.call(i.matrices.subarray(0,16),`,`)}`,s=n.get(o);s||n.set(o,s=[]);let c=s.find(e=>jw(e.list,i));if(c){c.template===e.objects.get(c.name)&&(c.template=c.template.slice());for(let e of a)c.template.push(e);KS(i.matrices);continue}let l={name:r,list:i,template:a};s.push(l),t.push(l)}return t}async _buildAnimatedPlacements(e,t){let n=e.animatedInstances??[];for(let i=0;i<n.length;i++){let{name:a,motion:o}=n[i],s=e.objects.get(a);if(!s){this.droppedNoTemplate++;continue}if(this._overBudget()){this.skippedForBudget+=n.length-i;break}let c=new r.Group;c.name=`placement_${i}`;let l=Array.from(o.matrices.subarray(0,16));new r.Matrix4().fromArray(this.convertHandedness?SC(hw,l):l).decompose(c.position,c.quaternion,c.scale);for(let e=0;e<s.length;e++){let t=s[e],[n,r]=await Promise.all([this._buildGeometry(t),this._getMaterial(t)]);if(!n)continue;let i=this._meshFromGeometry(t,n,r,t.relativeCTM||t.ctm,`${c.name}_${e}`,!0);i&&c.add(i)}c.children.length!==0&&(t.add(c),this._animate(c,o))}}_animate(e,t){t.visible&&(e.visible=t.visible[0]===1),this._animated.push({node:e,motion:t})}_buildClip(e,t){let n=[];for(let{node:e,motion:t}of this._animated)if(this._transformTracks(n,e.name,t,(e,t)=>{let n=Array.from(e.subarray(t,t+16));return this.convertHandedness?SC(hw,n):n}),t.visible){let i=t.times,a=i.map((e,t)=>t===0?0:(i[t-1]+e)/2);n.push(new r.BooleanKeyframeTrack(`${e.name}.visible`,a,Array.from(t.visible,e=>e===1)))}let i=e.camera?.motion;if(t&&i){let e=new r.PerspectiveCamera;if(this._transformTracks(n,t.name,i,(t,n)=>(this._poseCamera(e,t.subarray(n,n+16)),e.updateMatrix(),e.matrix.elements)),i.fov&&t.isPerspectiveCamera){let e=Array.from(i.fov,e=>this._verticalFov({fov:{type:`float`,value:[e]}},t.aspect));n.push(new r.NumberKeyframeTrack(`${t.name}.fov`,i.times.slice(),e))}}for(let e of n)e.optimize();return n.length===0?[]:[new r.AnimationClip(e.animation.name,e.animation.duration,n)]}_transformTracks(e,t,n,i){let a=n.times.length,o=new Float32Array(a*3),s=new Float32Array(a*4),c=new Float32Array(a*3),l=new r.Matrix4,u=new r.Vector3,d=new r.Quaternion,f=new r.Vector3;for(let e=0;e<a;e++)l.fromArray(i(n.matrices,e*16)).decompose(u,d,f),e>0&&d.x*s[e*4-4]+d.y*s[e*4-3]+d.z*s[e*4-2]+d.w*s[e*4-1]<0&&d.set(-d.x,-d.y,-d.z,-d.w),u.toArray(o,e*3),d.toArray(s,e*4),f.toArray(c,e*3);let p=(e,t)=>{for(let n=t;n<e.length;n++)if(e[n]!==e[n%t])return!0;return!1};p(o,3)&&e.push(new r.VectorKeyframeTrack(`${t}.position`,n.times.slice(),o)),p(s,4)&&e.push(new r.QuaternionKeyframeTrack(`${t}.quaternion`,n.times.slice(),s)),p(c,3)&&e.push(new r.VectorKeyframeTrack(`${t}.scale`,n.times.slice(),c))}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a,o=!1){let s=!!t.getAttribute(`uv`),c=this._materialForGeometry(e,t,n,a),l=new r.Mesh(t,c);l.name=a;let u=this.convertHandedness&&!o?SC(hw,i):i;new r.Matrix4().fromArray(u).decompose(l.position,l.quaternion,l.scale),l.updateMatrix(),t.boundingBox||t.computeBoundingBox();let d=t.boundingBox?t.boundingBox.clone().applyMatrix4(l.matrix).getSize(new r.Vector3):new r.Vector3,f=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<bw&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`${d.x.toFixed(2)}×${d.y.toFixed(2)}×${d.z.toFixed(2)}`,tris:f}),l}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=n.clone(),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?SC(hw,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,t,n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(UC(e.params,`filename`,null)))){for(let e in t.attributes)KS(t.attributes[e].array);KS(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&KS(e.params[t].value)}}_lastPlyUse(e){let t=(this._plyUsers.get(e)??1)-1;return this._plyUsers.set(e,t),t>0||this._plyHeld.has(e)?!1:(this._plyCache.delete(e),!0)}_appendToBatch(e,t,n,r,i){let a=this._materialForGeometry(t,n,r,`merged shape`),o=n.getAttribute(`position`),s=n.getAttribute(`normal`),c=n.getAttribute(`uv`),l=n.index,u=o.count;this.triangleCount+=(l?l.count:u)/3,this.mergedShapes++;let d=e.get(a);d||e.set(a,d=[null,null]);let f=+!!c,p=d[f];p||(d[f]=p={material:a,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:c?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let m=i,h=AC(m),g=p.vertexCount;p.positions=vw(p.positions,(g+u)*3),p.normals=vw(p.normals,(g+u)*3),c&&(p.uvs=vw(p.uvs,(g+u)*2));let _=o.array,v=p.positions,y=s?s.array:null,b=p.normals;for(let e=0;e<u;e++){let t=e*3,n=(g+e)*3,r=_[t],i=_[t+1],a=_[t+2];if(v[n]=m[0]*r+m[4]*i+m[8]*a+m[12],v[n+1]=m[1]*r+m[5]*i+m[9]*a+m[13],v[n+2]=m[2]*r+m[6]*i+m[10]*a+m[14],!y)continue;let o=y[t],s=y[t+1],c=y[t+2],l=h[0]*o+h[1]*s+h[2]*c,u=h[4]*o+h[5]*s+h[6]*c,d=h[8]*o+h[9]*s+h[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),b[n]=l,b[n+1]=u,b[n+2]=d}c&&p.uvs.set(c.array.subarray(0,u*2),g*2);let x=l?l.count:u;p.indices=vw(p.indices,p.indexCount+x);let S=p.indices,C=l?l.array:null;for(let e=0;e<x;e++)S[p.indexCount+e]=g+(C?C[e]:e);return p.vertexCount+=u,p.indexCount+=x,p.triangles+=x/3,p.triangles>=Dw?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(qS(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(qS(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(qS(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(qS(e.indices,e.indexCount),1)),e.positions=e.normals=e.uvs=e.indices=null,t}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.Mesh(this._batchGeometry(e),e.material);n.name=`merged_${this._mergedBatches++}`,n.frustumCulled=!1,t.add(n),this.placementCount++,this.report.length<bw&&this.report.push({mesh:n.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles})}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(yw(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(yw(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(yw(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(_w(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(HC(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=UC(e,`type`,`flat`),a=HC(e,`width`,1),o=mw({P:t,basis:UC(e,`basis`,`bezier`),width0:HC(e,`width0`,a),width1:HC(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??kw[i]??1,tolerance:this.curveTolerance});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(HC(e,`levels`,3)))),{positions:a,indices:o,levels:s}=$C(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value;if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=[];for(let e=0;e+3<n.length;e+=4){let[t,r,a,o]=[n[e],n[e+1],n[e+2],n[e+3]];i.push(t,r,a,t,a,o)}let a=new r.BufferGeometry;return a.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),a.setIndex(i),a.computeVertexNormals(),a}_plyMesh(e){let t=UC(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)||t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){return new r.SphereGeometry(HC(e,`radius`,1),48,32)}_disk(e){let t=HC(e,`radius`,1),n=HC(e,`innerradius`,0),i=HC(e,`height`,0),a=[],o=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2,s=(e+1)/48*Math.PI*2,c=a.length/3;a.push(Math.cos(r)*n,Math.sin(r)*n,i),a.push(Math.cos(r)*t,Math.sin(r)*t,i),a.push(Math.cos(s)*t,Math.sin(s)*t,i),a.push(Math.cos(s)*n,Math.sin(s)*n,i),o.push(c,c+1,c+2,c,c+2,c+3)}let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(a),3)),s.setIndex(o),s.computeVertexNormals(),s}async _getMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e)},r=await qC(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.opacity}|${e.side}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}async _applyAreaLight(e,t,n){let r=await WC(t.params,`L`,n,[1,1,1]),i=HC(t.params,`scale`,1),a=r.rgb||[1,1,1];e.emissive.setRGB(a[0],a[1],a[2]),e.emissiveIntensity=i}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`){let r=UC(t.params,`filename`,null);if(r)try{let t=await this.resolveImage(r);t?n={texture:t}:this.warn(`image not found for texture "${e}": ${r}`)}catch(t){this.warn(`failed to load texture "${e}" (${r}): ${t.message}`)}}else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}_colorFromLikeNamedMaterial(e){for(let t of Nw(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=t&&t.yresolution?t.xresolution/t.yresolution:16/9,i;if(e.type===`orthographic`){let t=e.params?.screenwindow?.value,a=t?.length===4?(t[3]-t[2])/2:Math.max(1,1/n);i=new r.OrthographicCamera(-a*n,a*n,a,-a,.01,1e4)}else i=new r.PerspectiveCamera(this._verticalFov(e.params,n),n,.01,1e4);return i.name=`PBRT Camera`,this._poseCamera(i,e.cameraToWorld),i.updateMatrixWorld(!0),i}_poseCamera(e,t){let n=t,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1),e.up.copy(o.normalize()),e.position.copy(i),e.scale.set(1,1,1),e.lookAt(i.clone().add(a)),bC(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=HC(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=Mw(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=rw(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=HC(t.params,`scale`,1),i=UC(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=((await WC(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)},[1,1,1])).rgb||[1,1,1]).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&this.warn(`light "${t.type}" not supported (only infinite lights and emissive area lights are mapped)`)}},Fw=1e3,Iw=2048,Lw=1e5;function Rw(e){let t=e[0],n=e=>{let t=e.lastIndexOf(`/`),n=/^(.*?)(\d+)\.pbrt$/i.exec(e.slice(t+1));return n?{group:e.slice(0,t+1)+`\0`+n[1].toLowerCase(),number:parseInt(n[2],10)}:null},r=t?n(t):null;if(!r)return null;let i=new Map;for(let t of e){let e=n(t);e&&e.group===r.group&&!i.has(e.number)&&i.set(e.number,t)}return i.size<2?null:[...i].sort((e,t)=>e[0]-t[0]).slice(0,Fw).map(([e,t])=>({path:t,number:e}))}function zw(e){let t=e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array?new Uint32Array(e.buffer,e.byteOffset,e.length):null;t||=new Uint32Array(Float32Array.from(e).buffer);let n=2166136261;for(let e=0;e<t.length;e++)n=Math.imul(n^t[e],16777619),n^=n>>>15;return(n>>>0).toString(36)+`:`+e.length}function Bw(e){let t=``;for(let n of Object.keys(e).sort()){let{type:r,value:i}=e[n],a=ArrayBuffer.isView(i)||i.length>16&&typeof i[0]==`number`;t+=`${r} ${n}=${a?`#`+zw(i):i.join(`,`)};`}return t}var Vw=class{constructor(e){this.materialNames=new Map;for(let[t,n]of e.namedMaterials)this.materialNames.set(n,t);this.cache=new Map}of(e){return`${e.type}|${+!!e.reverseOrientation}|${Bw(e.params)}|${this._material(e.material)}|${this._light(e.areaLight)}`}_material(e){if(!e)return`-`;let t=this.cache.get(e);if(t===void 0){let n=this.materialNames.get(e)??e._missingRef;t=n===void 0?`I:`+e.type+`:`+Bw(e.params):`N:`+n,this.cache.set(e,t)}return t}_light(e){if(!e)return`-`;let t=this.cache.get(e);return t===void 0&&this.cache.set(e,t=`L:`+e.type+`:`+Bw(e.params)),t}};function Hw(e,t){let n=new Int32Array(t.length).fill(-1),r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)n[r]=r,r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)n[--a]=--i;return r<i&&r<a&&!Uw(e,r,i,t,r,a,n)&&Gw(e,r,i,t,r,a,n),n}function Uw(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,Iw),u=l+1,d=new Int32Array(2*l+3),f=[];for(let n=0;n<=l;n++){for(let a=-n;a<=n;a+=2){let l=a===-n||a!==n&&d[u+a-1]<d[u+a+1]?d[u+a+1]:d[u+a-1]+1,p=l-a;for(;l<s&&p<c&&e[t+l]===r[i+p];)l++,p++;if(d[u+a]=l,l>=s&&p>=c)return f.push(d.slice(u-n,u+n+1)),Ww(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function Ww(e,t,n,r,i,a){let o=t,s=n;for(let t=e.length-1;t>0;t--){let n=e[t-1],c=e=>n[e+t-1],l=o-s,u=l===-t||l!==t&&c(l-1)<c(l+1)?l+1:l-1,d=c(u),f=d-u;for(;o>d&&s>f;)a[i+--s]=r+--o;o=d,s=f}for(;o>0&&s>0;)a[i+--s]=r+--o}function Gw(e,t,n,r,i,a,o){let s=new Map;for(let r=t;r<n;r++){let t=s.get(e[r]);t?t.push(r):s.set(e[r],[r])}let c=new Map;for(let e=i;e<a;e++){let t=s.get(r[e]);if(!t)continue;let n=c.get(r[e])??0;n<t.length&&(o[e]=t[n],c.set(r[e],n+1))}}function Kw(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function qw(e,t,n){let r=e.length,i=new Float32Array(16*r),a=null,o=-1;for(let e=0;e<r;e++)if(t(e)){if(i.set(n(e),e*16),o<0)for(let t=0;t<e;t++)i.copyWithin(t*16,e*16,e*16+16);o=e}else a??=new Uint8Array(r).fill(1),a[e]=0,o>=0&&i.copyWithin(e*16,o*16,o*16+16);return{times:e,matrices:i,visible:a}}function Jw(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!Kw(t,0,t,e))return!1;return!0}var Yw=class{constructor(e,t){this.times=Float32Array.from(e),this.name=t,this.base=null,this.frame=-1,this.keyIds=new Map,this.tracks=[],this.prev=null,this.placements=new Map,this.templates=new Map,this.cameras=[],this.warnings=new Set}addFrame(e){let t=++this.frame;t===0?this.base=e:this._adoptDefinitions(e);for(let t of e.warnings)this.warnings.add(t);let n=new Vw(e),r=new Int32Array(e.shapes.length);for(let t=0;t<r.length;t++){let i=n.of(e.shapes[t]),a=this.keyIds.get(i);a===void 0&&this.keyIds.set(i,a=this.keyIds.size),r[t]=a}let i=this.prev?Hw(this.prev.keys,r):null,a=Array(r.length);for(let o=0;o<r.length;o++){let r=e.shapes[o],s=i&&i[o]>=0?this.prev.tracks[i[o]]:null;s?(s.last=t,s.ctms?s.ctms.push(r.ctm):r.ctm!==s.shape.ctm&&!Kw(r.ctm,0,s.shape.ctm,0)&&(s.ctms=Array(t-s.first).fill(s.shape.ctm),s.ctms.push(r.ctm))):(s={shape:r,first:t,last:t,ctms:null},t>0&&this._adoptMaterial(r,n.materialNames),this.tracks.push(s)),a[o]=s}this.prev={keys:r,tracks:a},this._addPlacements(e,t,this._resolveTemplates(e,t,n)),this.cameras.push(e.camera?{cameraToWorld:e.camera.cameraToWorld,fov:e.camera.params?.fov?.value?.[0]}:null)}_adoptDefinitions(e){for(let[t,n]of e.namedMaterials)this.base.namedMaterials.has(t)||this.base.namedMaterials.set(t,n);for(let[t,n]of e.namedTextures)this.base.namedTextures.has(t)||this.base.namedTextures.set(t,n)}_resolveTemplates(e,t,n){let r=new Map;for(let[i,a]of e.objects){let e=``;for(let t of a)e+=n.of(t)+`@`+Array.prototype.join.call(t.relativeCTM||t.ctm,`,`)+`;`;let o=i+`\0`+e,s=this.templates.get(o);if(s===void 0&&(s=t===0||!this.base.objects.has(i)?i:`${i} @${t}`,this.templates.set(o,s),t>0)){for(let e of a)this._adoptMaterial(e,n.materialNames);this.base.objects.set(s,a)}r.set(i,s)}return r}_adoptMaterial(e,t){let n=e.material&&t.get(e.material);n!==void 0&&(e.material=this.base.namedMaterials.get(n)??e.material)}_addPlacements(e,t,n){for(let[r,i]of e.instances){let e=n.get(r)??r,a=this.placements.get(e);if(a||this.placements.set(e,a={counts:new Int32Array(this.times.length),diffs:new Map}),a.counts[t]=i.count,t===0)continue;let o=this.base.instances.get(e),s=o?.count??0;for(let e=0;e<i.count;e++){let n=e*16;if(e<s&&Kw(i.matrices,n,o.matrices,n))continue;let r=a.diffs.get(e);r||a.diffs.set(e,r=new Map),r.set(t,i.matrices.slice(n,n+16))}}}finish(){let e=this.base,t=this.times,n=this.frame+1;e.shapes=this.tracks.map(e=>{let{shape:r,first:i,last:a,ctms:o}=e;return(i>0||a<n-1||o)&&(r.motion=qw(t,e=>e>=i&&e<=a,e=>o?o[e-i]:r.ctm)),r}),e.warnings=[...this.warnings],e.animatedInstances=this._finishPlacements(e,t,n);let r=this.cameras;if(r[0]&&r.every(Boolean)){let n=qw(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!Jw(n)||a)&&(e.camera.motion={...n,fov:a?Float32Array.from(i):null})}return e.animation={name:this.name,duration:t[n-1],frames:n},e}_finishPlacements(e,t,n){let r=[],i=0;for(let[a,{counts:o,diffs:s}]of this.placements){let c=e.instances.get(a),l=c?.count??0,u=Math.max(...o.subarray(0,n)),d=[];for(let e=0;e<u;e++){let u=s.get(e),f=!!u;for(let t=0;t<n&&!f;t++)f=e>=o[t];if(f&&r.length<Lw){let n=qw(t,t=>e<o[t],t=>u?.get(t)??c.matrices.subarray(e*16,e*16+16));r.push({name:a,motion:n})}else f&&i++,e<l&&d.push(e)}if(c&&d.length!==l){let t=new Float32Array(d.length*16);d.forEach((e,n)=>t.set(c.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=l-d.length,c.matrices=t,c.matricesEnd=null,c.count=d.length}}return i>0&&e.warnings.push(`${i.toLocaleString()} moving placement(s) past ${Lw.toLocaleString()} left static`),r}};function Xw(e){if(!e.hasMotion)return e;let{start:t,end:n}=e.transformTimes,r=n-t;if(!(r>0))return e;let i=Float32Array.of(0,r),a=(e,t,n,r)=>{let a=new Float32Array(32);for(let i=0;i<16;i++)a[i]=e[t+i],a[16+i]=n[r+i];return{times:i,matrices:a,visible:null}};for(let t of e.shapes)t.ctmEnd&&(t.motion=a(t.ctm,0,t.ctmEnd,0));e.animatedInstances=[];for(let t of e.instances.values()){if(!t.matricesEnd)continue;let n=[];for(let r=0;r<t.count;r++){let i=r*16;Kw(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=Lw?n.push(r):e.animatedInstances.push({name:t.name,motion:a(t.matrices,i,t.matricesEnd,i)})}if(n.length!==t.count){let r=new Float32Array(n.length*16);n.forEach((e,n)=>r.set(t.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=t.count-n.length,t.matrices=r,t.count=n.length}t.matricesEnd=null}return e.camera?.cameraToWorldEnd&&(e.camera.motion={...a(e.camera.cameraToWorld,0,e.camera.cameraToWorldEnd,0),fov:null}),e.animation={name:`Shutter motion`,duration:r,frames:2},e}var Zw=2e6,Qw=new TextDecoder;function $w(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function eT(e,t){return!e||t.startsWith(`/`)?$w(t):$w(`${e}/${t}`)}var tT=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=$w(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readHead(e,t){return e?e.bytes?e.bytes.subarray(0,t):!e.lazy||!this.source?null:this.source.readHead?this.source.readHead(e.key,t):this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(eT(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null,n=null){let r=t!==null&&this.findRecord(eT(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),KS(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=$w(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}};function nT(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}var rT=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),iT=4*1024*1024,aT=rT(`WorldBegin`),oT=[rT(`Include`),rT(`Import`)];function sT(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function cT(e){for(let t=nT(e,aT);t>=0;t=nT(e,aT,t+1))if(sT(e,t))return!0;return!1}function lT(e,t){for(let n of oT)for(let r=nT(e,n);r>=0;r=nT(e,n,r+1)){if(!sT(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=Qw.decode(e.subarray(a,i));t.add($w(o).toLowerCase().split(`/`).pop())}}function uT(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,cT(t)),lT(t,n)}return dT(t,r,n)}function dT(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function fT(e){return uT(e)[0]||null}async function pT(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=async n=>{let r=new Set,i=new Map,a=!1;for(let o of t){let t=await n(o);t&&(i.set(o.key,cT(t)),lT(t,r),t.length>=iT&&(a=!0),o.lazy&&(e.release(o),KS(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,iT)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return dT(t.map(e=>e.key),a,i)}async function mT(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new tT(t,n),c=[],l=await pT(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new RC({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},p=performance.now(),m=!u&&e.animation!==!1?Rw(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>Zw)c.push(`${m.length} animation frames found, but the scene is too large to parse once per frame — loaded "${m[0].path}" only`),m=null,h=Xw(e);else{let t=new Yw(m.map(e=>(e.number-m[0].number)/30),hT(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=Xw(await f(d));let g=performance.now()-p;s.releaseScenes();let _=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),v=new Map,y=async e=>{let t=await s.read(e);return t?(s.release(e),r(_(t))):null},b=new Pw({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,resolvePLY:async e=>{let t=s.findRecord(e);return t?(v.has(t.norm)||v.set(t.norm,await y(t)),v.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),x=performance.now(),S=await b.build(h);return{...S,entryPath:m?m[0].path:d,frames:m?m.map(e=>e.path):null,candidates:l,warnings:[...c,...S.warnings??[]],parseMs:g,buildMs:performance.now()-x}}function hT(e){let t=e[0].path.split(`/`);return`${t.length>1?t[t.length-2]:t[0].replace(/\d+\.pbrt$/i,``)||`frames`} · frames ${e[0].number}–${e[e.length-1].number}`}var gT=[`sourceFile`,`url`,`file`];function _T(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function vT(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function yT(e){let t=_T(e);if(!t)return null;let n=_T(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function bT(e){let t=_T(e);if(!t)return null;let n=gT.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=vT(t.rotation),i=vT(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function xT(e){let t=yT(e);if(!t)return null;let n=bT(t.environment);return n?{environment:n}:null}function ST(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=xT(e);if(t)return t}return null}Ys();var CT={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usd:{type:`model`,name:`USD (Universal Scene Description)`},usda:{type:`model`,name:`USDA (USD ASCII)`},usdc:{type:`model`,name:`USDC (USD Crate)`},usdz:{type:`model`,name:`USDZ (USD Archive)`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`},gz:{type:`archive`,name:`Gzipped TAR Archive`},tgz:{type:`archive`,name:`Gzipped TAR Archive`},tar:{type:`archive`,name:`TAR Archive`}},wT=/\.(usd|usda|usdc)$/i,TT=/\.(png|jpg|jpeg|avif)$/i,ET=3e4,DT=4e9;function OT(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var kT=683;function AT(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var jT=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,profile:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this._issues=i,this._profile=a??xe(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Y.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await ox(t,{downloads:this.downloads,key:i,policy:a,name:$b(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}:${this._profile?.name??``}:${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new rx(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,f.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this._pendingGraph=null,this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return CT[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await this.loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadAssetFromUrl(t,n={}){let{filename:r=$b(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw Error(`Unsupported file format: ${r}`);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,Rn(await Ln(e))):null,r=await this._loadModelFileByExtension(e,t);return this._sourceKey=n,r}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usd`:case`usda`:case`usdc`:case`usdz`:return await this.loadUSDFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return Lu(r,Rn(await Ln(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&Lu(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n){let i=e._isNetworkUrl(t),a=`Downloading Environment...`,o=await this._viaCache(t,a,i),c=o.cached?void 0:this._downloadProgress(a,i),l;try{n===`hdr`||n===`exr`?l=await(n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader(this._loadingManager).setDataType(r.FloatType))).loadAsync(o.url,c):ti().decodeImage?(l=await US(o.url,`image/${n===`jpg`?`jpeg`:n}`),l.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),l=await this.loaderCache.texture.loadAsync(o.url,c),l.colorSpace=r.SRGBColorSpace)}finally{o.release()}return this._downloadComplete(`Processing Environment...`,62),l.mapping=r.EquirectangularReflectionMapping,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=Ex(await this._readHead(e)),n=e=>z({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4}),r;if(t===`gzip`){let t=await this._unpackGzip(e,e.name);t?(r=t.index.listing,t.release()):{listing:r}=await zx(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await uS(e,this.storage))?.listing??await Vx(e,{onProgress:n}):(await nS(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=Gx(r);return{kind:t??`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async _unpackGzip(e,t){try{return await lS(e,{storage:this.storage,label:t,onProgress:e=>z({isLoading:!0,status:`Unpacking archive… ${(e/1e9).toFixed(1)} GB`,progress:4})})}catch(e){return console.warn(`Unpacking "${t}" to storage failed, reading it in memory: ${e.message}`),null}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=Ex(await this._readHead(e)),c=this.storage?Rn(await Ln(e)):null,l={element:r,promptBytes:a,pbrtEntry:n,pbrt:o,archiveId:c};if(s===`tar`)return await this._loadSeekable(e,t,l);if(s===`gzip`){let a=await this._unpackGzip(e,t);if(a)try{return await this._loadSeekable(a.file,t,{...l,index:a.index})}finally{a.release()}let u=await this._readStreamedArchive(e,t,s,r,i);if(fT(u))return await this.loadPBRTFromZip(u,t,n,o);let d=await this._loadNonPBRTArchive(u,t);return this._sourceKey=this._keyed(`archive`,c),d}return await this._loadSeekable(e,t,{...l,zip:!0})}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _loadSeekable(e,t,{element:n,promptBytes:r,pbrtEntry:i,pbrt:a,index:o=null,zip:s=!1,archiveId:c=null}){let l=await this._openSeekableArchive(e,t,n,r,{index:o,zip:s});if(l.archiveId=c,l.elements=(Array.isArray(n)?n:[n]).filter(Boolean),l.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,i,a,l);for(let e of l.listing)e.offset!==void 0&&(l.entries[e.path]??=await l.read(e.path));let u=await this._loadNonPBRTArchive(l.entries,t);return this._sourceKey=this._keyed(`archive`,c),u}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.storage?.area(Wn.SCENES),a=i?await i.open(e):null;if(!a)return null;let o=performance.now(),s=null;try{z({isLoading:!0,status:`Opening the stored scene...`,progress:6});let e=await a.json(`graph.json`),i=await a.file(`data.bin`),s=new tT({},t),c=await IS(e,i,{loadTexture:async(e,t)=>{let i=await s.readPath(e);return i?t===`environment`?r(i,e):n(i,e):null}});return{...c.stats,group:c.root,environment:c.environment?{texture:c.environment}:null,animations:c.animations,report:null,parseMs:0,buildMs:performance.now()-o,fromStorage:!0}}catch(e){return s=e,null}finally{a.release(),s&&(console.warn(`The stored scene could not be used, parsing the archive instead: ${s.message}`),this._issues?.warn(Y.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.storage?.area(Wn.SCENES);if(!r)return;let i;try{i=kS(t.group,{environment:t.environment?.texture??null,animations:t.animations??[],stats:{meshCount:t.meshCount,entryPath:t.entryPath,candidates:t.candidates,frames:t.frames,warnings:t.warnings,triangleCount:t.triangleCount,placementCount:t.placementCount,mergedShapes:t.mergedShapes,skippedForBudget:t.skippedForBudget,droppedNoTemplate:t.droppedNoTemplate}})}catch(e){e instanceof bS?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a={key:e,encoded:i,label:n,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null};eg(a.parseMs,i.byteLength)?this._writeGraph(r,a):this._pendingGraph=a}flushPendingGraph(e){let t=this._pendingGraph;this._pendingGraph=null;let n=this.storage?.area(Wn.SCENES);!t||!n||!eg(t.parseMs+e,t.encoded.byteLength)||this._writeGraph(n,t)}_writeGraph(e,t){(async()=>{let n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength});if(n)try{await AS(n,t.encoded,{release:!0}),await n.commit({triangles:t.triangles})}catch(e){await n.abort(),console.warn(`Storing the scene failed:`,e)}})().catch(e=>console.warn(`Storing the scene failed:`,e))}async _openSeekableArchive(e,t,n,r,{index:i=null,zip:a=!1}={}){let o=Array.isArray(n)?n.filter(Boolean):n?[n]:[],s=o.length?Wx(o):null,c;if(a)c=await aS(e,{filter:s});else{let t=i??await uS(e,this.storage);c=await Ux(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||dS(e,this.storage,c.index).catch(()=>{})}let l=c.listing.reduce((e,t)=>e+t.size,0);return o.length===0&&this._requireElementChoice(t,c.listing,l,r),console.info(`Archive "${t}": indexed ${c.indexed} entries, ${(l/1e9).toFixed(1)} GB, none resident`+(o.length?`, ${o.length} part${o.length>1?`s`:``} selected.`:`.`)),c}_requireElementChoice(e,t,n,r=DT){if(n<r)return;let{root:i,elements:a}=Gx(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},fn.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await zx(e,{filter:a.length?Wx(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>z({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=Gx(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},fn.WARNING),i}if(l){let e=Wx(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`${t} files of the chosen parts were left out: they did not fit the ${((i??15e8)/1e9).toFixed(1)} GB in-memory read budget`,{elements:a,missing:t,retainedBytes:c},fn.WARNING)}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,r={},i=null){if(z({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let a=e=>this.loaderCache.ply.parse(e),o=async(e,t)=>{let n=await this._pbrtTextureFromBytes(e,t);return n&&(n.userData[fS]=t),n},s=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),r=new Blob([e]),i=URL.createObjectURL(r);try{let e=await this.loadEnvironmentByExtension(i,n);return Lu(e,`bytes:${await In(r)}`),e.userData[fS]=t,e.userData[pS]=`environment`,e}finally{URL.revokeObjectURL(i)}},c=performance.now(),l={animation:r.animation,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides,curveTolerance:r.curveTolerance,instanceIncludes:r.instanceIncludes},u=i?.archiveId?this._keyed(`pbrt:2.4:${Zh}`,`${i.archiveId}|${n??``}|${[...i.elements??[]].sort().join(`,`)}|${JSON.stringify(l)}`):null,d=u?await this._loadStoredGraph(u,i,{imageFromBytes:o,envFromBytes:s}):null,f=d??await mT({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,...l}),{group:p,environment:m,animations:h,report:g,warnings:_,meshCount:v,entryPath:y,candidates:b,frames:x,parseMs:S,buildMs:C,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O}=f;d&&console.info(`PBRT scene "${y}" opened from storage in ${(C/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:S,buildMs:C,loaderMs:performance.now()-c,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,meshCount:v,frames:x?.length??1};let k=new Set(x??[y]),A=b.filter(e=>!k.has(e));if(A.length>0&&(console.warn(`PBRT archive holds ${b.length} scenes; loaded "${y}". Others: ${A.join(`, `)}`),this._issues?.record(Y.ASSET_AMBIGUOUS_ENTRY,`archive holds ${b.length} pbrt scenes; loaded "${y}"`,{loaded:y,alternatives:A},fn.WARNING)),g&&g.length&&typeof console.table==`function`){let e=g.length<v?` (first ${g.length} of ${v})`:``;console.groupCollapsed(`PBRT loader: ${v} mesh(es) from "${y}"${e}`),console.table(g),console.groupEnd()}return _&&_.length&&(console.warn(`PBRT loader: ${_.length} warning(s) parsing "${y}"`),_.forEach(e=>console.warn(` •`,e))),m?.texture&&(m.texture.generateMipmaps=!0,this.applyEnvironmentToScene(m.texture)),p.name=y||t,this.releaseTargetModel(),this._sourceKey=u,u&&!d&&this._storeGraph(u,f,t),this.targetModel=p,this.animations=h??[],m?.texture&&(this.sceneMetadata={environment:{rotation:0,intensity:1}}),z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:p,filename:`${y} (from ZIP)`}),p}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader().setDataType(r.FloatType));i=await this._loadViaObjectURL(t,e)}else if(n===`tga`){if(!this.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(CT[n]&&CT[n].type===`model`)return wT.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>wT.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(wT.test(e)||TT.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,m.zipSync)(i),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(wT,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usd`:case`usda`:case`usdc`:case`usdz`:o=await this.loadUSDFromArrayBuffer(e,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{try{this._throwDeferred()}catch(e){n(e);return}this.releaseTargetModel(),this.targetModel=e.scene,this.sceneMetadata=ST(e),this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}finally{this._disposeGLTFLoader(s)}}else return await this.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.releaseTargetModel(),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),ET))]);return clearTimeout(r),i||this._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${ET}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.releaseTargetModel(),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){let{dracoDecoderPath:e,ktx2TranscoderPath:t}=Ks(),n=new c.DRACOLoader;n.setDecoderConfig({type:`js`}),n.setDecoderPath(e);let r=new l.KTX2Loader;r.setTranscoderPath(t),this.renderer&&(r.detectSupport(this.renderer),r.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1});let i=new o.GLTFLoader(this._loadingManager);return i.setDRACOLoader(n),i.setKTX2Loader(r),i.setMeshoptDecoder(p.MeshoptDecoder),ti().decodeImage&&i.register(e=>WS(e,(e,t)=>this._reportImageFailure(e,t))),i}_reportImageFailure(e,t){try{this._issues?.record(Y.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=ST(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(le(e),e.parent?.remove(e)):ce(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=ST(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let n=this.loaderCache.ply.parse(e),i;if(n.index!==null)i=new r.Mesh(n,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=n.hasAttribute(`color`),i=new r.Points(n,e)}return i.name=t,this.releaseTargetModel(),this.targetModel=i,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(z({isLoading:!0,status:`Processing USD Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usd){let{USDLoader:e}=await import(`three/examples/jsm/loaders/USDLoader.js`);this.loaderCache.usd=new e}let n=await new Promise((t,n)=>{this.loaderCache.usd.parse(e,``,t,n)});return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new jh(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=AT(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/kT,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=kT,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*AT(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._profile.areaLightIntensityScale,i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(Y.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=OT(e.geometry));let t=(0,d.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(CT))r.type===e&&(t[n]=r);return t}return CT}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this._pendingGraph=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},MT={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},NT=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function PT(e=1,t=1){let n={...MT,defaultView:null},r={...MT,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new NT(r);return r}var FT=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},IT=8,LT=4,RT=.25,zT=r.MathUtils.degToRad(89),BT=.25,VT={KeyD:[1,0,0],ArrowRight:[1,0,0],KeyA:[-1,0,0],ArrowLeft:[-1,0,0],KeyW:[0,1,0],ArrowUp:[0,1,0],KeyS:[0,-1,0],ArrowDown:[0,-1,0],KeyE:[0,0,1],KeyQ:[0,0,-1]},HT=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,UT=e=>e.shiftKey?LT:e.altKey?RT:1,WT={type:`change`},GT={type:`start`},KT=new r.Vector3,qT=new r.Vector3,JT=new r.Vector3,YT=new r.Vector3,XT=new r.Quaternion,ZT=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/IT,this._held=new Set,this._factor=1,this._lastTime=0,this._drag=null,this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this.release=this.release.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),t&&this.connect(t)}get active(){return this.enabled&&this.orbit.enabled}fitSpeed(e){this.speed=(e>0?e:1)/IT}connect(e){super.connect(e);let t=e.ownerDocument;t?.addEventListener(`keydown`,this._onKeyDown),t?.addEventListener(`keyup`,this._onKeyUp),t?.addEventListener(`visibilitychange`,this.release),t?.defaultView?.addEventListener(`blur`,this.release),e.addEventListener(`pointerdown`,this._onPointerDown),e.addEventListener(`pointermove`,this._onPointerMove),e.addEventListener(`pointerup`,this._onPointerUp),e.addEventListener(`pointercancel`,this._onPointerUp)}disconnect(){let e=this.domElement;if(!e)return;let t=e.ownerDocument;t?.removeEventListener(`keydown`,this._onKeyDown),t?.removeEventListener(`keyup`,this._onKeyUp),t?.removeEventListener(`visibilitychange`,this.release),t?.defaultView?.removeEventListener(`blur`,this.release),e.removeEventListener(`pointerdown`,this._onPointerDown),e.removeEventListener(`pointermove`,this._onPointerMove),e.removeEventListener(`pointerup`,this._onPointerUp),e.removeEventListener(`pointercancel`,this._onPointerUp)}dispose(){this.disconnect()}update(e=this._elapsed()){if(!this._held.size||!this.active)return!1;let t=0,n=0,r=0;for(let e of this._held){let[i,a,o]=VT[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return qT.set(1,0,0).applyQuaternion(i.quaternion),KT.crossVectors(i.up,qT).normalize(),qT.crossVectors(KT,i.up),JT.set(0,0,0).addScaledVector(qT,t).addScaledVector(KT,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(JT),this.orbit.target.add(JT),i.updateMatrixWorld(),this.dispatchEvent(WT),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,BT);return this._lastTime=e,t}_look(e,t){let n=this.object,i=this.orbit.target,a=n.position.distanceTo(i)||1,o=r.MathUtils.degToRad(n.fov)/(this.domElement.clientHeight||1);n.quaternion.premultiply(XT.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(KT);let s=Math.asin(r.MathUtils.clamp(KT.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-zT,zT);n.quaternion.multiply(XT.setFromAxisAngle(YT.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(KT),a),this.dispatchEvent(WT)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(HT))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=UT(e),VT[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(GT))))}}_onKeyUp(e){this._factor=UT(e),this._held.delete(e.code)}release(){this._held.clear(),this._factor=1}_onPointerDown(e){!this.active||e.button!==0||!e.isPrimary||(this._drag={id:e.pointerId,x:e.clientX,y:e.clientY},this.domElement.setPointerCapture?.(e.pointerId))}_onPointerMove(e){let t=this._drag;if(!t||e.pointerId!==t.id)return;let n=e.clientX-t.x,r=e.clientY-t.y;t.x=e.clientX,t.y=e.clientY,this.active&&(n||r)&&this._look(n,r)}_onPointerUp(e){this._drag?.id===e.pointerId&&(this._drag=null,this.domElement.releasePointerCapture?.(e.pointerId))}};R();var QT=Object.freeze(new r.Vector3(1,1,1)),$T=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,eE=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new FT(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this._reportedOrthoHeight=null,this._reportOrthoHeight=this._reportOrthoHeight.bind(this),this.controls.addEventListener(`change`,this._reportOrthoHeight),this.walkControls=new ZT(this.camera,e,this.controls),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Ie.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Ie.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0,this.resetAutoFocus()}addCameraFromView(e){let t=this.camera,n=t.orthographic?new r.OrthographicCamera(t.left,t.right,t.top,t.bottom,t.near,t.far):new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.zoom=t.zoom,n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),dofBlur:e(`dofBlur`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint},orthoHeight:this.orthoHeight}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio,dofBlur:e.dofBlur}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}switchCamera(e,t,n,i){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,i??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let a=this.cameras[this.currentCameraIndex];if(a&&(a.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??QT),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let n=this.cameras[e];if(this.camera.position.copy(n.position),this.camera.quaternion.copy(n.quaternion),this.camera.scale.copy(n.scale),n.isPerspectiveCamera&&(this.camera.fov=n.fov),this.camera.near=n.near,this.camera.far=n.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=n.userData?.__rayzeeOrbitTarget;if(e)this.controls.target.copy(e);else{let e=new r.Vector3(0,0,-1).applyQuaternion(n.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i)}this.controls.update()}}this.resetAutoFocus();let o=this.cameras[e],s=o?.userData?.__rayzeeEffects;this._showOrthographic(s?s.orthoHeight:$T(o)),this._applyEffects(s),n?.(),i?.(),this.dispatchEvent({type:I.CAMERA_SWITCHED,cameraIndex:e,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)})}_showOrthographic(e){e>0?this._setView(!0,e/2):this._setView(!1);let t=this._getSettings?.(`cameraProjection`),n=e>0?`orthographic`:t===`orthographic`?`perspective`:t;n!==t&&this._applySettings?.({cameraProjection:n})}applyProjection(e){let t=this.camera,n=e===`orthographic`;if(t.orthographic!==n){if(n)this._setView(!0,this._fittedHalfHeight());else{let e=this.controls.target,n=this.orthoHeight/2/Math.tan(r.MathUtils.degToRad(t.fov)/2);t.position.sub(e).setLength(n).add(e),this._setView(!1)}this.controls.update()}}get orthoHeight(){return $T(this.camera)}setOrthoHeight(e){e>0&&(this._setView(this.camera.orthographic,e/2),this._onReset?.())}fitOrthographic(){this.camera.orthographic&&this.setOrthoHeight(2*this._fittedHalfHeight())}_setView(e,t=this.camera.orthoHalfHeight){let n=this.camera;n.orthographic=e,n.orthoHalfHeight=t,n.zoom=1,n.updateProjectionMatrix(),this._reportOrthoHeight()}_fittedHalfHeight(){return this.camera.position.distanceTo(this.controls.target)*Math.tan(r.MathUtils.degToRad(this.camera.fov)/2)}_reportOrthoHeight(){if(!this.camera.orthographic)return;let e=this.orthoHeight;e!==this._reportedOrthoHeight&&(this._reportedOrthoHeight=e,this.dispatchEvent({type:I.ORTHO_HEIGHT_UPDATED,height:e}))}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}setNavigationMode(e){let t=e===`walk`;if(this.walkControls.enabled===t)return;let n=this.controls;if(n.enableRotate=n.enablePan=n.enableZoom=!t,this.walkControls.enabled=t,t)return;this.walkControls.release();let i=this.interactionManager?.pickSurface(0,0);if(!i)return;let a=r.MathUtils.clamp(i.distance,n.minDistance,n.maxDistance);n.target.copy(this.camera.position).addScaledVector(this.camera.getWorldDirection(new r.Vector3),a),n.update()}get navigationMode(){return this.walkControls.enabled?`walk`:`orbit`}updateControls(){this.walkControls.update(),this.controls.update()}captureView(){let e=this.camera,t=this.orthoHeight??2*this._fittedHalfHeight();return{position:e.position.clone(),target:this.controls.target.clone(),fov:e.fov,orthoHeight:t}}applyPose(e){let t=this.camera;t.position.copy(e.position),t.lookAt(e.target),this.controls.target.copy(e.target),t.orthographic?this._setView(!0,e.orthoHeight/2):(t.fov=e.fov,t.updateProjectionMatrix()),t.updateMatrixWorld()}serialize(){let e=this.camera,t=this._defaultCameraState;return{current:this.currentCameraIndex,view:{position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),fov:e.fov,near:e.near,far:e.far,zoom:e.zoom,orthographic:!!e.orthographic,orthoHalfHeight:e.orthoHalfHeight,target:this.controls.target.toArray()},defaultView:t?{position:t.position.toArray(),quaternion:t.quaternion.toArray(),scale:t.scale.toArray(),fov:t.fov,near:t.near,far:t.far,target:t.target?.toArray()??null}:null,navigationMode:this.navigationMode,autoFocus:{mode:this.autoFocusMode,point:{...this.afScreenPoint}},cameras:this.cameras.map((e,t)=>{let n={index:t,name:e.name??``,effects:zr(e.userData?.__rayzeeEffects)??null};return t===0||!e.userData?.__rayzeeUserCamera?n:{...n,user:!0,orthographic:!!e.isOrthographicCamera,frustum:e.isOrthographicCamera?[e.left,e.right,e.top,e.bottom]:null,fov:e.fov??null,aspect:e.aspect??null,near:e.near,far:e.far,zoom:e.zoom,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),orbitTarget:e.userData.__rayzeeOrbitTarget?.toArray()??null}})}}restore(e){let t=[];if(!e)return{mismatched:t};this.cameras=this.cameras.filter(e=>!e.userData?.__rayzeeUserCamera);let n=new Map;for(let i of e.cameras??[]){if(i.user){let e=i.orthographic?new r.OrthographicCamera(...i.frustum,i.near,i.far):new r.PerspectiveCamera(i.fov,i.aspect,i.near,i.far);e.name=i.name,e.zoom=i.zoom??1,e.position.fromArray(i.position),e.quaternion.fromArray(i.quaternion),e.scale.fromArray(i.scale),e.updateProjectionMatrix(),e.updateMatrixWorld(!0),e.userData.__rayzeeUserCamera=!0,e.userData.__rayzeeEffects=Br(i.effects),i.orbitTarget&&(e.userData.__rayzeeOrbitTarget=new r.Vector3().fromArray(i.orbitTarget)),n.set(i.index,this.cameras.length),this.cameras.push(e);continue}let e=this.cameras[i.index];if(!e||i.index>0&&(e.name??``)!==i.name){t.push(i.name);continue}n.set(i.index,i.index),i.effects&&(e.userData.__rayzeeEffects=Br(i.effects))}this._userCameraCounter=this.cameras.filter(e=>e.userData?.__rayzeeUserCamera).length,this.currentCameraIndex=n.get(e.current)??0;let i=e.defaultView;this._defaultCameraState=i?{position:new r.Vector3().fromArray(i.position),quaternion:new r.Quaternion().fromArray(i.quaternion),scale:new r.Vector3().fromArray(i.scale),fov:i.fov,near:i.near,far:i.far,target:i.target?new r.Vector3().fromArray(i.target):null}:null,e.navigationMode&&this.setNavigationMode(e.navigationMode);let a=e.view;if(a){let e=this.camera;e.position.fromArray(a.position),e.quaternion.fromArray(a.quaternion),e.scale.fromArray(a.scale),e.fov=a.fov,e.near=a.near,e.far=a.far,this._setView(a.orthographic,a.orthoHalfHeight),e.zoom=a.zoom??1,e.updateProjectionMatrix(),e.updateMatrixWorld(!0),this.controls.target.fromArray(a.target),this.controls.update()}return e.autoFocus&&(this.setAutoFocusMode(e.autoFocus.mode),this.setAFScreenPoint(e.autoFocus.point.x,e.autoFocus.point.y)),this.resetAutoFocus(),this._reportOrthoHeight(),this.dispatchEvent({type:I.CAMERA_SWITCHED,cameraIndex:this.currentCameraIndex,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)}),{mismatched:t}}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}resetAutoFocus(){this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!0}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let t=e||this._afContext;if(!t||!this.interactionManager)return;let{assetLoader:n,currentFocusDistance:r,pathTracer:i,setFocusDistance:a,softReset:o,hardReset:s}=t;if(this.autoFocusMode===`manual`)return;if(!i?.enableDOF?.value||i.cameraProjection?.value===Se.equirectangular){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let c=i;if(c?.isReady&&c.renderMode?.value===1&&c.frameCount>0&&!c.isComplete)return;let l=this.interactionManager.pickSurface(this.afScreenPoint.x*2-1,1-this.afScreenPoint.y*2),u;if(l)u=Ib(l.point,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?Ib(this.controls.target,this.camera):0;u=e>0?e:Ie.FALLBACK_DISTANCE*(n?.getSceneScale()||1),this._lastValidFocusDistance=u}let d=this._afPointDirty;this._afPointDirty=!1,d||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(u-this._smoothedFocusDistance)/this._smoothedFocusDistance>Ie.SNAP_THRESHOLD?this._smoothedFocusDistance=u:this._smoothedFocusDistance+=this.afSmoothingFactor*(u-this._smoothedFocusDistance);let f=r,p=this._smoothedFocusDistance;if(d||f===0||Math.abs(p-f)/Math.max(f,.001)>.001){a(p);let e=n?.getSceneScale()||1;this.dispatchEvent({type:I.AUTO_FOCUS_UPDATED,distance:p/e,worldDistance:p});let t=Math.abs(p-f)/Math.max(f,.001);d?s?.():t>Ie.RESET_THRESHOLD&&o?.()}}setInteractionManager(e){this.interactionManager=e}initAutoFocus({assetLoader:e,pathTracer:t,settings:n,softReset:r,hardReset:i}){this._afContext={assetLoader:e,pathTracer:t,setFocusDistance:e=>n.set(`focusDistance`,e,{silent:!0}),softReset:r,hardReset:i},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>n.get(`focusDistance`)})}dispose(){this.walkControls?.dispose(),this.controls?.removeEventListener(`change`,this._reportOrthoHeight),this.controls?.dispose()}},tE=.001,nE=2,rE=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),iE=class{constructor(e,t){this._cameraManager=e,this._onChange=t,this.keys=[],this._nextId=1,this._interpolants=null}get animates(){return this.keys.length>1}get duration(){return this.keys.length?this.keys[this.keys.length-1].time:0}addKey(e=this.keys.length?this.duration+nE:0){return this.add(this._cameraManager.captureView(),e)}updateKey(e){this.update(e,this._cameraManager.captureView())}seek(e){let t=this.sample(e);return t&&this._cameraManager.applyPose(t),!!t}add(e,t){let n={id:this._nextId++,time:t,...aE(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,aE(t)),this._changed())}setTime(e,t){let n=this.get(e);!n||!(t>=0)||(n.time=t,this._changed())}remove(e){let t=this.keys.length;this.keys=this.keys.filter(t=>t.id!==e),this.keys.length!==t&&this._changed()}clear(){this.keys.length&&(this.keys=[],this._changed())}serialize(){return this.keys.map(({time:e,position:t,target:n,fov:r,orthoHeight:i})=>({time:e,position:t.toArray(),target:n.toArray(),fov:r,orthoHeight:i}))}restore(e){this.keys=(e??[]).map(e=>({id:this._nextId++,time:e.time,position:new r.Vector3().fromArray(e.position),target:new r.Vector3().fromArray(e.target),fov:e.fov,orthoHeight:e.orthoHeight})),this._changed()}dispose(){this._cameraManager=this._onChange=null}get(e){return this.keys.find(t=>t.id===e)}sample(e,t={position:new r.Vector3,target:new r.Vector3,fov:0,orthoHeight:0}){if(!this.keys.length)return null;let{position:n,target:i,fov:a,logHeight:o,start:s,end:c}=this._interpolants??=this._build(),l=r.MathUtils.clamp(e,s,c);return t.position.fromArray(n.evaluate(l)),t.target.fromArray(i.evaluate(l)),t.fov=a.evaluate(l)[0],t.orthoHeight=Math.exp(o.evaluate(l)[0]),t}_build(){let e=[];for(let t of this.keys)e.push(e.length?Math.max(t.time,e[e.length-1]+tE):t.time);let t=e[0],n=e[e.length-1],i=this.keys;if(i.length>1){let r=i.length;e.unshift(2*t-e[1]),e.push(2*n-e[r-1]),i=[i[1],...i,i[r-2]]}let a=e=>i.flatMap(t=>e(t).toArray());return{start:t,end:n,position:rE(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:rE(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:rE(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:rE(r.NumberKeyframeTrack,`.orthoHeight`,e,i.map(e=>Math.log(e.orthoHeight)))}}_changed(){this.keys.sort((e,t)=>e.time-t.time),this._interpolants=null,this._onChange?.()}};function aE({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}R();var oE=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new iE(e,()=>this._changed(`camera`)),this._playback=null,this._timer=new r.Timer,typeof document<`u`&&this._timer.connect(document)}get duration(){return this.camera.duration}get animates(){return this.camera.animates}seek(e){return this.camera.seek(e)}play(){return this.stop(),new Promise(e=>{let t=this._cameraManager.controls;this._playback={elapsed:0,resolve:e,controlsEnabled:t.enabled},t.enabled=!1,this._timer.reset(),this._changed(),this._onReset?.()})}stop(){let e=this._playback;e&&(this._playback=null,this._cameraManager.controls.enabled=e.controlsEnabled,this._changed(),e.resolve())}get isPlaying(){return!!this._playback}update(){let e=this._playback;if(!e)return;this._timer.update(),e.elapsed+=this._timer.getDelta();let t=r.MathUtils.clamp(e.elapsed,0,this.duration);this.seek(t),t>=this.duration&&this.stop()}serialize(){return{camera:this.camera.serialize()}}restore(e){this.stop(),this.camera.restore(e?.camera)}clear(){this.stop(),this.camera.clear()}dispose(){this.stop(),this._timer.dispose(),this.camera.dispose(),this._cameraManager=this._onReset=null}_changed(e){this.dispatchEvent({type:I.TIMELINE_CHANGED,track:e})}},sE=`__rayzeeUserLight`,cE={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},lE=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[sE]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[sE]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:zr(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=cE[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=Br(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}},uE=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>dE(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0});for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4)}let u=new r.DataArrayTexture(s,i,a,o);u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.format=r.RGBAFormat,u.type=r.UnsignedByteType,u.generateMipmaps=!1,u.needsUpdate=!0;let d=this.texture;return this.texture=u,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=u,this.pathTracer.shaderBuilder?.updateGoboMaps?.(u),d?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Y.ASSET_UNREACHABLE,`no gobo named "${t}" is loaded — the light projects without one`,{name:t,asset:`gobo`}),!1;o.userData.gobo={name:e.name,index:e.index,intensity:fE(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};async function dE(e){let t=await ox(e);try{return await new Promise((n,r)=>{let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>n(i),i.onerror=()=>r(Error(`Failed to load gobo image: ${e}`)),i.src=t.url})}finally{t.release()}}function fE(e){return Math.max(0,Math.min(1,e))}function pE(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
1014
- `,n);if(r<0)throw Error(`IES (${t}): truncated TILT line`);let i=e.slice(n,r).match(/TILT\s*=\s*(\w+)/i),a=i?i[1].toUpperCase():`NONE`,o=e.slice(r);if(a===`INCLUDE`){let e=_E(o),t=2+2*Number(e[1]);o=vE(o,t)}let s=_E(o),c=0,l=()=>Number(s[c++]),u=l(),d=l(),f=l(),p=l(),m=l(),h=l();l(),l(),l(),l();let g=l();if(l(),l(),!Number.isFinite(p)||p<=0)throw Error(`IES (${t}): invalid vertical angle count ${p}`);if(!Number.isFinite(m)||m<=0)throw Error(`IES (${t}): invalid horizontal angle count ${m}`);let _=Array(p);for(let e=0;e<p;e++)_[e]=l();let v=Array(m);for(let e=0;e<m;e++)v[e]=l();let y=Array(p);for(let e=0;e<p;e++)y[e]=new Float32Array(m);let b=f*g,x=0;for(let e=0;e<m;e++)for(let t=0;t<p;t++){let n=l()*b;y[t][e]=n,n>x&&(x=n)}return{verticalAngles:_,horizontalAngles:v,candela:y,maxCandela:x,lumens:d*u,photometricType:h,name:t}}function mE(e,t,n){let r=new Uint8Array(t*n),{verticalAngles:i,horizontalAngles:a,candela:o,maxCandela:s}=e;if(s<=0)return r;let c=i[i.length-1],l=a[a.length-1],u=a[0],d=a.length===1||l===u;for(let e=0;e<n;e++){let f=(e+.5)/n*c,p=yE(i,f),m=Math.min(p+1,i.length-1),h=i[m]-i[p],g=h>0?(f-i[p])/h:0;for(let n=0;n<t;n++){let i;if(d)i=bE(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=yE(a,e),s=Math.min(r+1,a.length-1),c=a[s]-a[r],d=c>0?(e-a[r])/c:0,f=o[p][r],h=o[p][s],_=o[m][r],v=o[m][s];i=bE(bE(f,h,d),bE(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function hE(e,t=.1){let{verticalAngles:n,horizontalAngles:r,candela:i,maxCandela:a}=e,o=Math.PI/4;if(a<=0||!n?.length)return o;let s=a*t,c=r.length,l=n[n.length-1],u=!1;for(let e=0;e<n.length;e++){let t=0;for(let n=0;n<c;n++)t+=i[e][n];if(t/=c,t>=s&&(u=!0),u&&t<s){l=n[e];break}}let d=l*Math.PI/180;return Math.min(Math.max(d,5*Math.PI/180),89*Math.PI/180)}function gE(e,t,n=.7){let{verticalAngles:r,horizontalAngles:i,candela:a,maxCandela:o}=e;if(o<=0||!r?.length||t<=0)return 0;let s=o*n,c=i.length,l=0;for(let e=0;e<r.length;e++){let t=0;for(let n=0;n<c;n++)t+=a[e][n];if(t/=c,t>=s)l=r[e];else break}let u=t*180/Math.PI,d=u>0?1-l/u:0;return Math.min(Math.max(d,0),1)}function _E(e){return e.split(/\s+/).filter(e=>e.length>0)}function vE(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function yE(e,t){if(t<=e[0])return 0;if(t>=e[e.length-1])return e.length-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function bE(e,t,n){return e+(t-e)*n}var xE=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._gridWidth=128,this._gridHeight=128}async loadLibrary(e,{gridWidth:t=128,gridHeight:n=128}={}){if(!Array.isArray(e)||e.length===0)return[];this._gridWidth=t,this._gridHeight=n;let i=(await Promise.all(e.map(async e=>{try{let{file:r,release:i}=await ax().fetch(e.url),a=pE(await r.text().finally(i),e.name);return{it:e,profile:a,grid:mE(a,t,n)}}catch(t){return this._issues?.warn(Y.ASSET_UNREACHABLE,`IES profile "${e.name}" could not be loaded: ${t.message}`,{url:e.url,asset:`ies`,cause:t.message}),null}}))).filter(e=>e!==null);if(i.length===0)return[];let a=i.length,o=t*n,s=new Uint8Array(o*4*a),c=[];for(let e=0;e<a;e++){let t=i[e].grid,n=e*o*4;for(let e=0;e<o;e++){let r=t[e];s[n+e*4+0]=r,s[n+e*4+1]=r,s[n+e*4+2]=r,s[n+e*4+3]=255}let r=i[e].profile,a=hE(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:gE(r,a),lumens:r.lumens})}let l=new r.DataArrayTexture(s,t,n,a);l.format=r.RGBAFormat,l.type=r.UnsignedByteType,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l.generateMipmaps=!1,l.needsUpdate=!0;let u=this.texture;return this.texture=l,this.entries=c,this.pathTracer.iesProfiles=l,this.pathTracer.shaderBuilder?.updateIESProfiles?.(l),u?.dispose?.(),this.entries.map(({name:e,index:t})=>({name:e,index:t}))}getEntries(){return this.entries.slice()}setSpotLightProfile(e,t,n=1,{applyAutoCone:r=!0}={}){let i=this._findSpotLight(e),a={applied:!1,suggestedAngle:null,suggestedPenumbra:null,suggestedDecay:null,fixtureLumens:null};if(!i)return a;i.userData=i.userData||{};let o=null,s=null,c=null,l=null;if(t==null)delete i.userData.ies;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Y.ASSET_UNREACHABLE,`no IES profile named "${t}" is loaded — the light keeps its plain distribution`,{name:t,asset:`ies`}),a;l=Number.isFinite(e.lumens)?e.lumens:null,i.userData.ies={name:e.name,index:e.index,intensity:SE(n),fixtureLumens:l},r&&(Number.isFinite(e.suggestedAngle)&&(i.angle=e.suggestedAngle,o=e.suggestedAngle),Number.isFinite(e.suggestedPenumbra)&&(i.penumbra=e.suggestedPenumbra,s=e.suggestedPenumbra),i.decay=2,c=2)}return this.pathTracer.updateLights(),this._onReset?.(),{applied:!0,suggestedAngle:o,suggestedPenumbra:s,suggestedDecay:c,fixtureLumens:l}}getSpotLightProfile(e){return this._findSpotLight(e)?.userData?.ies||null}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function SE(e){return Math.max(0,Math.min(1,e))}jt(),Ys();var CE=vt(`oidn`),wE=16,TE=null;async function EE(){return TE||=(await import(`oidn-web/dist/oidn.js`)).initUNetFromBuffer,TE}var DE={QUALITY_MODELS:{fast:{model:`rt_hdr_alb_nrm_small`,cleanAux:!1},"fast-clean":{model:`rt_hdr_calb_cnrm_small`,cleanAux:!0},balance:{model:`rt_hdr_calb_cnrm`,cleanAux:!0},high:{model:`rt_hdr_calb_cnrm_large`,cleanAux:!0}},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,tileSize:1024}},OE=.18,kE=256,AE=256,jE=`
1015
- const WG: u32 = ${kE}u;
1016
- const GROUPS: u32 = ${AE}u;
1031
+ `,vx=32,yx=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`,output:r=`rgba8`}={}){this.device=e,this.label=t,this.input=n,this.output=r,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(vx),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=dx();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:_x(e,this.input,this.output)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*gx[this.output];this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:vx,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,t){return new Uint8ClampedArray(await this._run(e,t))}async toPlanar(e,t){return new Float32Array(await this._run(e,t))}async _run(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:o,height:s}=this,c=o*s*gx[this.output];this._paramU32[0]=o,this._paramU32[1]=s,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this.device.queue.writeBuffer(this._params,0,this._paramData);let l=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),u=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...l,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:o*s*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),d=this.device.createCommandEncoder({label:this.label}),f=d.beginComputePass();f.setPipeline(this._pipeline),f.setBindGroup(0,u),f.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(s/8)),f.end(),d.copyBufferToBuffer(this._storage,0,this._map,0,c),this.device.queue.submit([d.finish()]),await this._map.mapAsync(GPUMapMode.READ);let p=this._map.getMappedRange().slice(0);return this._map.unmap(),p}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}}));bx();var xx=512,Sx=4<<20,Cx=15e8,wx=new TextDecoder;function Tx(e){return e.length>=2&&e[0]===31&&e[1]===139}function Ex(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Dx(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function Ox(e){return Tx(e)?`gzip`:Ex(e)?`zip`:Dx(e)?`tar`:null}function kx(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return wx.decode(e.subarray(t,r))}function Ax(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=kx(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function jx(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function Mx(e){let t=wx.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var Nx=e=>e+(xx-e%xx)%xx,Px=e=>e===`L`||e===`x`||e===`X`;function Fx(e){let t=kx(e,345,155),n=kx(e,0,100);return{type:String.fromCharCode(e[156]||48),size:Ax(e,124,12),name:t?`${t}/${n}`:n}}function Ix(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:jx(t)||null}function Lx(e){for(let t=0;t<xx;t++)if(e[t]!==0)return!1;return!0}var Rx=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Cx,onEntry:r=null}={}){this.filter=e,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(xx),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(xx-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===xx&&(this._headerLen=0,this._bodyStart=t+n,this._readHeader())}else{let t=Math.min(this._remaining,e.length-n);if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<xx;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=Fx(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=Nx(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,Px(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=Ix(n,a);o&&(this.listing.push({path:o,size:r}),this._indexed=this.filter?this.filter(o,r):!0,this._indexed&&!(this.retain&&!this.retain(o,r))&&(this.retainedBytes+r>this.byteBudget?this.truncated=!0:(this._dst=new Uint8Array(r),this.retainedBytes+=r)),this._remaining===0&&this._endBody())}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=kx(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=Mx(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}};async function zx(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await Bx(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function Bx(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=Sx){let r=Math.min(n+Sx,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=Sx){let i=Math.min(r+Sx,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function Vx(e,t={}){let{onProgress:n,...r}=t,i=new Rx(r),a=0,o=0;return await zx(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}var Hx=1<<20;async function Ux(e,{onProgress:t=null}={}){let n=e.size,r=[],i=null,a=0,o=null,s=0,c=0,l=async(t,r)=>{if(i&&t>=a&&t+r<=a+i.length)return i.subarray(t-a,t-a+r);let o=Math.min(n,t+Math.max(r,Hx));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+xx<=n;){let e=await l(s,xx);if(Lx(e))break;let{type:n,size:i,name:a}=Fx(e),u=o??a;o=null;let d=s+xx;if(Px(n)){let e=await l(d,i);o=n===`L`?kx(e,0,e.length):Mx(e)}else{let e=Ix(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+Nx(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function Wx(){let e=new Rx({retain:()=>!1});return{push:t=>e.push(t),finish:()=>(e.end(),e.listing.filter(e=>e.offset!==void 0))}}async function Gx(e,t={}){let{index:n=null,headersOnly:r=!1,onProgress:i=null,...a}=t,o,s,c,l,u=null;if(n||r){u=n?.listing??await Ux(e,{onProgress:i});let{filter:t}=a;s=u.map(e=>!t||t(e.path,e.size)?{...e}:{path:e.path,size:e.size}),o=Object.create(null),c=0,l=!1}else{let t=new Rx({...a});await Bx(e,e=>t.push(e)),t.end(),{entries:o,listing:s,retainedBytes:c,truncated:l}=t.result()}let d=new Map;for(let e of s)e.offset!==void 0&&d.set(e.path,e);return{entries:o,listing:s,read:async t=>{if(o[t])return o[t];let n=d.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},readHead:async(t,n)=>{if(o[t])return o[t].subarray(0,n);let r=d.get(t);return r?new Uint8Array(await e.slice(r.offset,r.offset+Math.min(r.size,n)).arrayBuffer()):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function Kx(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=jx(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function qx(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var Jx=101010256,Yx=117853008,Xx=101075792,Zx=33639248,Qx=67324752,$x=65557,eS=new TextDecoder;async function tS(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function nS(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function rS(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function iS(e){let t=e.size,n=await tS(e,Math.max(0,t-$x-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===Jx){i=e;break}if(i<0)throw Error(`zip: end of central directory not found`);let a=r.getUint16(i+10,!0),o=r.getUint32(i+12,!0),s=r.getUint32(i+16,!0);if(a===65535||o===4294967295||s===4294967295){let t=i-20;if(t<0||r.getUint32(t,!0)!==Yx)throw Error(`zip: ZIP64 locator missing`);let n=nS(r,t+8),c=new DataView((await tS(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==Xx)throw Error(`zip: ZIP64 end record missing`);a=nS(c,32),o=nS(c,40),s=nS(c,48)}let c=await tS(e,s,s+o),l=new DataView(c.buffer),u=[],d=0;for(let e=0;e<a&&d+46<=c.length;e++){if(l.getUint32(d,!0)!==Zx)throw Error(`zip: corrupt central directory`);let e=l.getUint16(d+8,!0),t=l.getUint16(d+10,!0),n=l.getUint32(d+20,!0),r=l.getUint32(d+24,!0),i=l.getUint16(d+28,!0),a=l.getUint16(d+30,!0),o=l.getUint16(d+32,!0),s=l.getUint32(d+42,!0),f=c.subarray(d+46,d+46+i),p=e&2048?eS.decode(f):rS(f);for(let e=d+46+i,t=e+a;e+4<=t;){let t=l.getUint16(e,!0),i=l.getUint16(e+2,!0);if(t===1){let t=e+4;r===4294967295&&(r=nS(l,t),t+=8),n===4294967295&&(n=nS(l,t),t+=8),s===4294967295&&(s=nS(l,t))}e+=4+i}p.endsWith(`/`)||u.push({name:p,size:r,compSize:n,method:t,local:s,encrypted:(e&1)!=0}),d+=46+i+a+o}return u}async function aS(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await tS(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==Qx)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function oS(e,t){let n=await aS(e,t),r=await tS(e,n,n+t.compSize);if(t.method===0)return r;if(t.method===8)return t.size===0?new Uint8Array:(0,m.inflateSync)(r,{out:new Uint8Array(t.size)});throw Error(`zip: "${t.name}" uses compression method ${t.method}, which is not supported`)}async function sS(e,{filter:t=null}={}){let n=await iS(e),r=new Map,i=n.map(e=>t&&!t(e.name,e.size)?{path:e.name,size:e.size}:(r.set(e.name,e),{path:e.name,size:e.size,offset:e.local})),a=async t=>{let n=r.get(t);return n?oS(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await oS(e,n)]);let i=await aS(e,n);return e.slice(i,i+n.compSize)};return{entries:Object.create(null),listing:i,read:a,readHead:async(e,t)=>{let n=await o(e);return n?new Uint8Array(await n.slice(0,t).arrayBuffer()):null},slice:o,retainedBytes:0,truncated:!1,indexed:r.size}}var cS=1,lS=3;async function uS(e,t){return`${e}:${Rn(await Ln(t))}`}async function dS(e,{storage:t,label:n=e.name,onProgress:r=null}){if(!t||typeof DecompressionStream>`u`)return null;let i=t.area(Wn.ARCHIVES),a=await uS(`gunzip`,e),o=await i.open(a),s=!!o;if(!o){let s=await i.create(a,{label:n,expectedBytes:e.size*lS});if(!s)return null;let c=Wx(),l=new TransformStream({transform(e,t){c.push(e),t.enqueue(e)}});try{let t=e.stream().pipeThrough(new DecompressionStream(`gzip`)).pipeThrough(l),n=await s.writeStream(`data.tar`,t,{onProgress:r});await s.writeJSON(`index.json`,{v:cS,listing:c.finish()}),await s.commit({compressedBytes:e.size,tarBytes:n})}catch(e){if(await s.abort(),e?.name!==`QuotaExceededError`)throw e;return t._issue(Y.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:Wn.ARCHIVES}),null}if(o=await i.open(a,{wait:!0}),!o)return null}let c=await o.file(`data.tar`),l=await o.json(`index.json`);return!c||l?.v!==cS?(o.release(),null):{file:c,index:l,release:()=>o.release(),cached:s}}async function fS(e,t){if(!t)return null;let n=await t.area(Wn.ARCHIVES).open(await uS(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===cS?e:null}finally{n.release()}}async function pS(e,t,n){if(!t||!n)return!1;let r=await t.area(Wn.ARCHIVES).create(await uS(`tarindex`,e),{label:`${e.name} (index)`});if(!r)return!1;try{return await r.writeJSON(`index.json`,n),await r.commit(),!0}catch{return await r.abort(),!1}}var mS=`__rayzeeArchivePath`,hS=`__rayzeeArchiveLoader`,gS=64,_S=32<<20,vS=64<<20,yS={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},bS=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],xS=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],SS=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}};function CS(e){return e.isInstancedMesh?`InstancedMesh`:e.isSkinnedMesh||e.isBatchedMesh?null:e.isMesh?`Mesh`:e.isPerspectiveCamera?`PerspectiveCamera`:e.isOrthographicCamera?`OrthographicCamera`:e.isLight||e.isPoints||e.isLine||e.isSprite||e.isLOD?null:e.isGroup?`Group`:e.constructor===r.Object3D?`Object3D`:null}function wS(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[mS],delete t[hS],t}catch{throw new SS(`${t}: userData is not plain JSON`)}}var TS=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/gS)*gS;return this.sections.push({offset:t,array:e}),this.length=t+e.byteLength,{offset:t,byteLength:e.byteLength,type:e.constructor.name,length:e.length}}};function ES(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new SS(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function DS(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new SS(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=ES(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?ES(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:wS(e.userData,n)}}function OS(e,t){let n={uuid:e.uuid,userData:wS(e.userData,`texture ${e.uuid}`)};for(let t of bS)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[mS];if(r)n.path=r,n.loader=e.userData.__rayzeeArchiveLoader??`image`;else if(e.isDataTexture&&ArrayBuffer.isView(e.image?.data))n.data={section:t.add(e.image.data),width:e.image.width,height:e.image.height};else throw new SS(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function kS(e,t){let n=e.toJSON(t);n.exactColors={};for(let[t,r]of Object.entries(e))r?.isColor&&(n.exactColors[t]=[r.r,r.g,r.b]);return e.ior!==void 0&&(n.exactIor=e.ior),n}function AS(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function jS(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new TS,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=CS(e);if(!n)throw new SS(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:wS(e.userData,`${n} "${e.name}"`)};for(let t of xS)r[t]=e[t];if(r.position=e.position.toArray(),r.quaternion=e.quaternion.toArray(),r.scale=e.scale.toArray(),r.layers=e.layers.mask,e.matrixAutoUpdate||(r.matrix=e.matrix.toArray()),e.isMesh){s.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)c.set(e.uuid,e),AS(e,l);r.geometry=e.geometry.uuid,r.material=Array.isArray(e.material)?t.map(e=>e.uuid):e.material.uuid}if(e.isInstancedMesh&&(r.count=e.count,r.instanceMatrix=a.add(e.instanceMatrix.array),r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null),e.isCamera)for(let t of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])e[t]!==void 0&&(r[t]=e[t]);let i=o.push(r)-1;for(let t of e.children)u(t,i)};u(e,-1),t&&l.set(t.uuid,t);let d={textures:{},images:{}};for(let e of l.keys())d.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...s.values()].map(e=>DS(e,a)),textures:[...l.values()].map(e=>OS(e,a)),materials:[...c.values()].map(e=>kS(e,d)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function MS(e,{manifest:t,sections:n},{release:r=!1}={}){for(let t of n){let{offset:n,array:i}=t,a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<a.length;t+=_S)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+_S)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function NS(e){let t=yS[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function PS(e,t){let n=new Map,r=[...t].sort((e,t)=>e.offset-t.offset),i=null,a=0;for(let t of r){let{offset:r,byteLength:o,type:s}=t,c=NS(s),l=r+o;if(o>vS){n.set(r,new c(await e.slice(r,l).arrayBuffer()));continue}(!i||r<a||l>a+i.byteLength)&&(a=r,i=await e.slice(r,Math.min(e.size,r+vS)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function FS(e){let t=[];for(let n of e.nodes)n.instanceMatrix&&t.push(n.instanceMatrix),n.instanceColor&&t.push(n.instanceColor);for(let n of e.geometries){for(let e of Object.values(n.attributes))t.push(e.section);n.index&&t.push(n.index.section)}for(let n of e.textures)n.data&&t.push(n.data.section);return t}function IS(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function LS(e,t){for(let n of bS)t[n]!==void 0&&(e[n]=t[n]);e.repeat.fromArray(t.repeat),e.offset.fromArray(t.offset),e.center.fromArray(t.center),e.rotation=t.rotation,e.uuid=t.uuid,Object.assign(e.userData,t.userData),e.needsUpdate=!0}async function RS(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await PS(t,FS(e)),a=e=>i.get(e.offset),o={};for(let t of e.textures){let e;if(t.path){if(e=await n(t.path,t.loader),!e)throw Error(`scene graph: "${t.path}" is missing from the archive`);e.userData[mS]=t.path,e.userData[hS]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);LS(e,t),o[t.uuid]=e}let s=new r.MaterialLoader().setTextures(o),c={};for(let t of e.materials){let e=s.parse(t);for(let[n,r]of Object.entries(t.exactColors??{}))e[n]?.setRGB(r[0],r[1],r[2]);t.exactIor!==void 0&&(e.ior=t.exactIor),c[t.uuid]=e}let l={};for(let t of e.geometries){let e=new r.BufferGeometry;e.uuid=t.uuid,e.name=t.name;for(let[n,r]of Object.entries(t.attributes))e.setAttribute(n,IS(i,r));t.index&&e.setIndex(IS(i,t.index));for(let n of t.groups)e.addGroup(n.start,n.count,n.materialIndex);e.setDrawRange(t.drawRange.start,t.drawRange.count),e.userData=t.userData,l[t.uuid]=e}let u=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>c[e]):c[t.material],n;switch(t.type){case`InstancedMesh`:n=new r.InstancedMesh(l[t.geometry],e,1),n.instanceMatrix=new r.InstancedBufferAttribute(a(t.instanceMatrix),16),n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break;case`Mesh`:n=new r.Mesh(l[t.geometry],e);break;case`PerspectiveCamera`:n=new r.PerspectiveCamera;break;case`OrthographicCamera`:n=new r.OrthographicCamera;break;case`Group`:n=new r.Group;break;default:n=new r.Object3D}n.uuid=t.uuid;for(let e of xS)n[e]=t[e];if(n.position.fromArray(t.position),n.quaternion.fromArray(t.quaternion),n.scale.fromArray(t.scale),n.layers.mask=t.layers,n.userData=t.userData,t.matrix&&n.matrix.fromArray(t.matrix),n.isCamera){for(let e of[`fov`,`aspect`,`near`,`far`,`zoom`,`focus`,`filmGauge`,`filmOffset`,`left`,`right`,`top`,`bottom`])t[e]!==void 0&&(n[e]=t[e]);n.updateProjectionMatrix()}u.push(n),t.parent>=0&&u[t.parent].add(n)}return{root:u[0],environment:e.environment?o[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var zS=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function BS(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):zS.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function VS(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function HS({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function US(e,t){return ti().decodeImage(t===`image/png`?VS(e):e,t)}async function WS(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}async function GS(e,t=BS({uri:e})){let n=HS(await US(await WS(e),t));return n.flipY=!0,n}function KS(e,t=null){return e.loadImageSource=function(e){if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let n=this.json.images[e],i=BS(n),a=n.uri??`bufferView ${n.bufferView}`,o=(n.bufferView===void 0?WS(this.options.manager.resolveURL(r.LoaderUtils.resolveURL(n.uri,this.options.path))):this.getDependency(`bufferView`,n.bufferView).then(e=>new Uint8Array(e))).then(e=>US(e,i)).then(e=>{let t=HS(e,{shared:!0});return n.extras&&typeof n.extras==`object`&&Object.assign(t.userData,n.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var qS=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer);function JS(e){e&&qS(e)&&e.buffer.transfer(0)}function YS(e,t){let n=e.constructor;if(qS(e))return new n(e.buffer.transfer(t*n.BYTES_PER_ELEMENT));let r=new n(t);return r.set(t<e.length?e.subarray(0,t):e),r}var XS={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},ZS=9,QS=10,$S=12,eC=13,tC=32,nC=34,rC=35,iC=43,aC=45,oC=46,sC=48,cC=57,lC=91,uC=93,dC=69,fC=101,pC=e=>e===tC||e===ZS||e===QS||e===eC||e===$S,mC=e=>e>=sC&&e<=cC,hC=15,gC=22,_C=(()=>{let e=new Float64Array(gC+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),vC=new TextDecoder;function yC(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return vC.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var bC=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&pC(e[t]);)t++;if(t<n&&e[t]===rC){for(;t<n&&e[t]!==QS;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===lC)return this.i=t+1,{type:XS.LBRACKET};if(r===uC)return this.i=t+1,{type:XS.RBRACKET};if(r===nC){let r=++t;for(;t<n&&e[t]!==nC;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:XS.STRING,value:yC(e,r,t)}}if(mC(r)||r===oC&&mC(e[t+1])||(r===aC||r===iC)&&(mC(e[t+1])||e[t+1]===oC&&mC(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(pC(n)||n===nC||n===lC||n===uC||n===rC)break;t++}return this.i=t,{type:XS.WORD,value:yC(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===aC?(i=!0,r++):t[r]===iC&&r++;let a=0,o=0,s=0;for(;r<n&&mC(t[r]);)a=a*10+(t[r]-sC),o++,r++;if(r<n&&t[r]===oC)for(r++;r<n&&mC(t[r]);)a=a*10+(t[r]-sC),o++,s++,r++;let c=0;if(r<n&&(t[r]===fC||t[r]===dC)){let e=r+1,i=!1;if(e<n&&(t[e]===aC||t[e]===iC)&&(i=t[e]===aC,e++),e<n&&mC(t[e])){let a=0;for(;e<n&&mC(t[e]);)a=a*10+(t[e]-sC),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${yC(t,e,r)}"`);let l=c-s;if(!(o<=hC&&l>=-gC&&l<=gC)){let n=Number(yC(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${yC(t,e,r)}"`);return{type:XS.NUMBER,value:n}}let u=l===0?a:l>0?a*_C[l]:a/_C[-l];return i&&(u=-u),{type:XS.NUMBER,value:u}}};function xC(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function SC(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function CC(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function wC(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function TC(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function EC(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function DC(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function OC(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function kC(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function AC(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function jC(e,t,n){let r=AC(OC(t,e)),i=AC(kC(AC(n),r)),a=kC(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function MC(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return xC();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var NC=8,PC=1,FC=2,IC=3,LC=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]);function RC(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var zC={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},BC=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.instanceIncludes=e.instanceIncludes!==!1,this._includes=new Map,this._stateIds=new WeakMap,this._nextStateId=1,this._effects=0,this._movedShapes=!1,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,transformTimes:{start:0,end:1},hasMotion:!1,warnings:[]},this.ctm=xC(),this.ctmEnd=null,this.activeTransform=IC,this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.objectBeginCTM=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){this.dirStack=[t],await this._run(new bC(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=YS(e.matrices,e.count*16),e.matricesEnd&&=YS(e.matricesEnd,e.count*16);return this.ir}_addInstance(e,t=this.ctm){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let n=this.ir.instances.get(e);n||this.ir.instances.set(e,n={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let r=(n.count+1)*16;if(r>n.matrices.length){let e=Math.max(r,n.matrices.length*2);n.matrices=YS(n.matrices,e),n.matricesEnd&&=YS(n.matricesEnd,e)}let i=n.count*16;for(let e=0;e<16;e++)n.matrices[i+e]=t[e];let a=this._ctmEndSnapshot();if(a&&!n.matricesEnd&&(n.matricesEnd=n.matrices.slice()),n.matricesEnd){let e=a||t;for(let t=0;t<16;t++)n.matricesEnd[i+t]=e[t]}n.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_ctmEndSnapshot(){return this.ctmEnd===null||RC(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===IC&&this.ctmEnd===null){this.ctm=wC(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&FC?wC(t,e):t,this.activeTransform&PC&&(this.ctm=wC(this.ctm,e))}_setCTM(e){if(this.activeTransform===IC){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&FC?e:t,this.activeTransform&PC&&(this.ctm=e)}_pushGraphicsState(){this.attributeStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform,material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation})}_popGraphicsState(){let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation})}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==XS.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==XS.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===XS.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==XS.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===XS.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===XS.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==XS.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===XS.NUMBER){let t=[];for(;n()&&t.length<NC;){let e=this._next();if(e.type!==XS.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(zC[e]||Float64Array)(NC*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==XS.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=YS(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:YS(r,i)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==XS.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===XS.NUMBER||e.type===XS.STRING)return e.value;if(e.type===XS.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==XS.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);LC.has(e.value)&&this._effects++;let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this._setCTM(xC());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(TC(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(EC(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(DC(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=jC([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(MC(t));break}case`Transform`:this._setCTM(this._readBracketedOrBareNumbers(16));break;case`ConcatTransform`:this._concat(this._readBracketedOrBareNumbers(16));break;case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),{ctm:this.ctm,ctmEnd:this.ctmEnd});break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd);break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:MC(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=MC(n));break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),filename:this._str(e.filename,null)};break}case`Integrator`:case`Sampler`:case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=xC(),this.ctmEnd=null,this.activeTransform=IC,this.state={material:null,areaLight:null,reverseOrientation:!1};break;case`WorldEnd`:break;case`AttributeBegin`:this._pushGraphicsState();break;case`AttributeEnd`:this._popGraphicsState();break;case`TransformBegin`:this.transformStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform});break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=PC:e===`EndTime`?this.activeTransform=FC:e===`All`?this.activeTransform=IC:this._warn(`ActiveTransform "${e}" not recognised`);break}case`TransformTimes`:{let[e,t]=this._readNumbers(2);this.ir.transformTimes={start:e,end:t};break}case`MediumInterface`:this._peek()&&this._peek().type===XS.STRING&&this._next(),this._peek()&&this._peek().type===XS.STRING&&this._next();break;case`MakeNamedMedium`:this._skipNamedAndParams();break;case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ctmEnd!==null&&!RC(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-light`,`animated LightSource transforms are not supported — using the start transform`),this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation},t=this.currentObject===null?this._ctmEndSnapshot():null;t?e.ctmEnd=t:this.currentObject!==null&&this.ctmEnd!==null&&!RC(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-template`,`animated transforms inside ObjectBegin are not supported — using the start transform`),this._emitShape(e);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this._pushGraphicsState(),this.currentObject=e,this.objectBeginCTM=this.ctm.slice(),this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:this.currentObject=null,this.objectBeginCTM=null,this._popGraphicsState();break;case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=wC(MC(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=this._includeKey(e,t);if(n!==null&&this._placeRepeat(n,e))return;let r=await this.resolveInclude(e,t);if(r==null){this._warn(`Include target not found: ${e}`);return}let i=n===null?null:this._includeState(),a=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(a);try{await this._run(new bC(r))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t,r)}i&&this._sameIncludeState(i)&&!this._includes.has(n)&&this._includes.set(n,{start:i.shapes,end:this.ir.shapes.length,ctm:i.ctm.slice(),template:null})}_includeKey(e,t){return!this.instanceIncludes||this.currentObject!==null||this.ctmEnd!==null||this.activeTransform!==IC||this.state.areaLight?null:`${t}\0${e}\0${this._stateId(this.state.material)}\0${this.state.reverseOrientation}`}_stateId(e){if(!e)return 0;let t=this._stateIds.get(e);return t===void 0&&this._stateIds.set(e,t=this._nextStateId++),t}_includeState(){return{shapes:this.ir.shapes.length,effects:this._effects,ctm:this.ctm,attributes:this.attributeStack.length,transforms:this.transformStack.length,material:this.state.material,reverseOrientation:this.state.reverseOrientation}}_sameIncludeState(e){return this._effects===e.effects&&this.ctmEnd===null&&this.activeTransform===IC&&RC(this.ctm,e.ctm)&&this.attributeStack.length===e.attributes&&this.transformStack.length===e.transforms&&this.state.material===e.material&&this.state.areaLight===null&&this.state.reverseOrientation===e.reverseOrientation}_placeRepeat(e,t){let n=this._includes.get(e);if(!n)return!1;if(n.template===null){let{start:r,end:i}=n;if(i===r||this.ir.instanceCount+2>this.maxPlacements)return!1;for(let t=r;t<i;t++)if(!this.ir.shapes[t])return this._includes.delete(e),!1;let a=`${t}#${this.ir.objects.size}`,o=MC(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=wC(o,c=t.ctm)),t.relativeCTM=l,s.push(t),this.ir.shapes[e]=null}this.ir.objects.set(a,s),this._addInstance(a,n.ctm),n.template=a,this._movedShapes=!0}return this._addInstance(n.template),!0}_skipTypeAndParams(){this._peek()&&this._peek().type===XS.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===XS.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnOnce(e,t){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(t))}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}},VC={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},HC=[.92,.92,.92];function UC(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function WC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function GC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function KC(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:UC(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=qC(i.value[0]);return e&&VC[e]?{rgb:VC[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function qC(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(VC))if(e.toLowerCase().includes(t))return t;return null}function JC(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=WC(e,`uroughness`,null),r=WC(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function YC(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await KC(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await KC(i,`reflectance`,t,null),n=i.eta,r=i.k,c=n&&n.type===`spectrum`&&typeof n.value[0]==`string`;if(e.rgb||e.texture)s(e);else if(n&&r&&!c){let e=(await KC(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await KC(i,`k`,t,[3.9,2.45,2.14])).rgb,r=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);o([r(e[0],n[0]),r(e[1],n[1]),r(e[2],n[2])])}else o(n?(await KC(i,`eta`,t,HC)).rgb||HC:VC.cu);a.metalness=1,a.roughness=JC(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=WC(i,`eta`,1.5),a.roughness=JC(i,0),a.thickness=n===`thindielectric`?0:WC(i,`thickness`,0);break;case`coateddiffuse`:s(await KC(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=JC(i,0);break;case`diffusetransmission`:{let e=await KC(i,`transmittance`,t,[.25,.25,.25]);s(await KC(i,`reflectance`,t,[.25,.25,.25])),a.transmission=e.rgb?(e.rgb[0]+e.rgb[1]+e.rgb[2])/3:.5,a.roughness=1,a.ior=1;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,WC(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,r]=await Promise.all([YC(o,t),YC(s,t)]),i=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,r.color,n),a.roughness=i(e.roughness,r.roughness),a.metalness=i(e.metalness,r.metalness),a.ior=i(e.ior??1.5,r.ior??1.5),a.transmission=i(e.transmission??0,r.transmission??0),a.thickness=i(e.thickness??0,r.thickness??0),a.clearcoat=i(e.clearcoat??0,r.clearcoat??0),a.clearcoatRoughness=i(e.clearcoatRoughness??0,r.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,r.emissive,n),a.emissiveIntensity=i(e.emissiveIntensity??0,r.emissiveIntensity??0),a.map=(n<.5?e.map:r.map)||null;break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await KC(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}return a.roughness=Math.max(0,Math.min(1,a.roughness)),a}function XC(e){return e===3?3/16:3/(8*e)}function ZC(e){return 1/(e+3/(8*XC(e)))}function QC(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function $C(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function ew(e,t){let n=e.length/3,r=QC(n,t),i=r.edgeV0.length,a=$C(e,r,n,XC,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function tw(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=ew(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=$C(i,QC(s,a),s,ZC,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function nw(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}var rw=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})();function iw(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function aw(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?MC(t):null,c=e.srgb?rw:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=nw(f,p,m);iw(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var ow=2;function sw(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function cw(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function lw(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function uw(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function dw(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function fw(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?sw(c,i):cw(c,i);let l=t===`bspline`?s:s*3,u=0,d=0,f=0;for(let t=0;t<4;t++){let n=(l+t)*3;u+=i[t]*e[n],d+=i[t]*e[n+1],f+=i[t]*e[n+2]}a[o]=u,a[o+1]=d,a[o+2]=f}function pw(e,t,n){let r=dw(e,t);if(r<1)return null;let i=Math.max(1,Math.round(n*r)),a=new Float64Array((i+1)*3),o=[0,0,0,0];for(let n=0;n<=i;n++)fw(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function mw(e,t,n,r,i){let a=e[t*3],o=e[t*3+1],s=e[t*3+2],c=n[r*3],l=n[r*3+1],u=n[r*3+2],d=n[i*3]-c,f=n[i*3+1]-l,p=n[i*3+2]-u,m=d*d+f*f+p*p,h=m>0?((a-c)*d+(o-l)*f+(s-u)*p)/m:0;return h=h<0?0:h>1?1:h,Math.hypot(a-c-h*d,o-l-h*f,s-u-h*p)}function hw(e,t,n,r,i,a){let{points:o,count:s,spans:c}=n;if(s<3)return null;let l=new Float64Array((s-1)*3),u=[0,0,0,0],d=s-1;for(let n=0;n<d;n++)fw(e,t,c,(n+.5)/d*c,u,l,n*3);let f=0;for(let e=0;e<d;e++)f=Math.max(f,mw(l,e,o,e,e+1));let p=e=>Math.max(f,r*.5*(i+(a-i)*(e/d))),m=(e,t)=>{for(let n=e+1;n<t;n++)if(mw(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(mw(l,n,o,e,t)>p(n+.5))return!1;return!0},h=new Int32Array(s),g=0;h[g++]=0;for(let e=0;e<d;){let t=e+1;for(;t<d&&m(e,t+1);)t++;h[g++]=t,e=t}return g===s?null:h.subarray(0,g)}function gw(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??ow)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=pw(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?hw(t,n,c,e.tolerance,r,i):null,f=d?d.length:u,p=s>=3?s:s*2,m=new Float32Array(f*p*3),h=[0,0,0],g=[0,0,0],_=[0,0,0],v=[0,0,0],y=!1,b=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(h[0]=l[n*3]-l[t*3],h[1]=l[n*3+1]-l[t*3+1],h[2]=l[n*3+2]-l[t*3+2],lw(h),y){let e=g[0]*h[0]+g[1]*h[1]+g[2]*h[2];g[0]-=e*h[0],g[1]-=e*h[1],g[2]-=e*h[2],Math.hypot(g[0],g[1],g[2])<1e-9&&uw(h,[0,1,0],g),lw(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],uw(h,g,v),g[0]=v[0],g[1]=v[1],g[2]=v[2];else{let e=Math.abs(h[0]),t=Math.abs(h[1]),n=Math.abs(h[2]);uw(h,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],g)}Math.hypot(g[0],g[1],g[2])<1e-9&&uw(h,[0,1,0],g),lw(g),y=!0}if(d&&d[b]!==e)continue;uw(h,g,_),lw(_);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,f=l[e*3],x=l[e*3+1],S=l[e*3+2];for(let e=0;e<p;e++){let t,n,r;if(s>=3){let i=e/s*Math.PI*2,a=Math.cos(i),o=Math.sin(i);t=g[0]*a+_[0]*o,n=g[1]*a+_[1]*o,r=g[2]*a+_[2]*o}else{let i=e<2?g:_,a=e%2==0?-1:1;t=i[0]*a,n=i[1]*a,r=i[2]*a}let i=(b*p+e)*3;m[i]=f+t*c,m[i+1]=x+n*c,m[i+2]=S+r*c}b++}let x=s,S=new Uint32Array((f-1)*x*6),C=0;for(let e=0;e<f-1;e++)for(let t=0;t<x;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*p+n,a=e*p+r,o=(e+1)*p+r,c=(e+1)*p+n;S[C++]=i,S[C++]=a,S[C++]=o,S[C++]=i,S[C++]=o,S[C++]=c}return{positions:m,indices:C===S.length?S:YS(S,C)}}var _w=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],vw=4096;function yw(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function bw(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return YS(e,n)}function xw(e){return e instanceof Float32Array?e:Float32Array.from(e)}var Sw=1e3,Cw=45e6,ww=6e6,Tw=6e7,Ew=8e6,Dw=256,Ow=4096,kw=5e5,Aw=2,jw={flat:1,ribbon:1,cylinder:2},Mw=.05;function Nw(e,t){if(e.count!==t.count)return!1;for(let n=0,r=e.count*16;n<r;n++)if(e.matrices[n]!==t.matrices[n])return!1;return!0}function Pw(e,t){let n=Math.min(e.width,vw),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function Fw(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var Iw=class{constructor(e={}){this.maxTriangles=e.maxTriangles??Cw,this.maxPlacements=e.maxPlacements??ww,this.mergeShapesAbove=e.mergeShapesAbove??Dw,this.curveSteps=e.curveSteps??Aw,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??Mw,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._keepShapes=new Set;for(let{name:t}of e.animatedInstances??[])for(let n of e.objects.get(t)??[])this._keepShapes.add(n);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=GC(t.params,`filename`,null);this._plyUsers.set(e,(this._plyUsers.get(e)??0)+1)}for(let t of e.objects.values())for(let e of t)e.type===`plymesh`&&this._plyHeld.add(GC(e.params,`filename`,null));this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0,this._animated=[];for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;if(this._batches&&!r.motion&&i.getAttribute(`position`).count<=Ow){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(GC(r.params,`filename`,null));let o=this._meshFromGeometry(r,i,a,r.ctm,`shape_${n}`);o&&(t.add(o),r.motion&&this._animate(o,r.motion))}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),await this._buildAnimatedPlacements(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=e.animation?this._buildClip(e,n):[],a=await this._buildEnvironment(e.lights);return this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:a,animations:i,report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4,o=(e,o,s,c,l,u,d)=>{let f=Math.max(0,this.maxPlacements-this.placementCount),p=Math.min(e.count,f);if(p<e.count&&(this.skippedForBudget+=e.count-p),p===0)return;let m=new r.InstancedMesh(o,s,p);m.name=`instance_${n++}`,m.frustumCulled=!1;for(let t=0;t<p;t++){if(c)CC(i,e.matrices,t*16,c);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];m.setMatrixAt(t,a.fromArray(this.convertHandedness?wC(_w,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<Sw&&this.report.push({mesh:`${m.name} ×${p}`,shape:l,material:u,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o.getAttribute(`uv`)?`yes`:`NO`,normals:o.getAttribute(`normal`)?`yes`:`NO`,emissive:s.emissiveIntensity>0?`#${s.emissive.getHexString()}×${s.emissiveIntensity}`:`-`,size:`instanced`,tris:d})},s=(e,t)=>{t&&t.triangles>0&&o(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:t,list:n,template:r}of this._samePlacementGroups(e)){if(!r){this.droppedNoTemplate+=n.count,this.warn(`ObjectInstance "${t}" has no template — ${n.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of r)t.type!==`plymesh`&&e++;let i=e>=2?new Map:null;for(let e of r){if(this._overBudget()){this.skippedForBudget+=n.count;continue}let[r,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!r)continue;if(i&&e.type!==`plymesh`&&r.getAttribute(`position`).count<=Ow){this._geometryCache.delete(e);let t=this._appendToBatch(i,e,r,a,e.relativeCTM||e.ctm);this._releaseMerged(e,r),s(n,t);continue}let c=this._accountGeometry(r);o(n,r,this._materialForGeometry(e,r,a,`instances_${t}`),e.relativeCTM||e.ctm,e.type,e.material?.type||`diffuse`,c)}if(i)for(let e of i.values())s(n,e[0]),s(n,e[1]);JS(n.matrices),JS(n.matricesEnd)}}_samePlacementGroups(e){let t=[],n=new Map;for(let[r,i]of e.instances){let a=e.objects.get(r);if(!a||i.matricesEnd){t.push({name:r,list:i,template:a});continue}let o=`${i.count}:${Array.prototype.join.call(i.matrices.subarray(0,16),`,`)}`,s=n.get(o);s||n.set(o,s=[]);let c=s.find(e=>Nw(e.list,i));if(c){c.template===e.objects.get(c.name)&&(c.template=c.template.slice());for(let e of a)c.template.push(e);JS(i.matrices);continue}let l={name:r,list:i,template:a};s.push(l),t.push(l)}return t}async _buildAnimatedPlacements(e,t){let n=e.animatedInstances??[];for(let i=0;i<n.length;i++){let{name:a,motion:o}=n[i],s=e.objects.get(a);if(!s){this.droppedNoTemplate++;continue}if(this._overBudget()){this.skippedForBudget+=n.length-i;break}let c=new r.Group;c.name=`placement_${i}`;let l=Array.from(o.matrices.subarray(0,16));new r.Matrix4().fromArray(this.convertHandedness?wC(_w,l):l).decompose(c.position,c.quaternion,c.scale);for(let e=0;e<s.length;e++){let t=s[e],[n,r]=await Promise.all([this._buildGeometry(t),this._getMaterial(t)]);if(!n)continue;let i=this._meshFromGeometry(t,n,r,t.relativeCTM||t.ctm,`${c.name}_${e}`,!0);i&&c.add(i)}c.children.length!==0&&(t.add(c),this._animate(c,o))}}_animate(e,t){t.visible&&(e.visible=t.visible[0]===1),this._animated.push({node:e,motion:t})}_buildClip(e,t){let n=[];for(let{node:e,motion:t}of this._animated)if(this._transformTracks(n,e.name,t,(e,t)=>{let n=Array.from(e.subarray(t,t+16));return this.convertHandedness?wC(_w,n):n}),t.visible){let i=t.times,a=i.map((e,t)=>t===0?0:(i[t-1]+e)/2);n.push(new r.BooleanKeyframeTrack(`${e.name}.visible`,a,Array.from(t.visible,e=>e===1)))}let i=e.camera?.motion;if(t&&i){let e=new r.PerspectiveCamera;if(this._transformTracks(n,t.name,i,(t,n)=>(this._poseCamera(e,t.subarray(n,n+16)),e.updateMatrix(),e.matrix.elements)),i.fov&&t.isPerspectiveCamera){let e=Array.from(i.fov,e=>this._verticalFov({fov:{type:`float`,value:[e]}},t.aspect));n.push(new r.NumberKeyframeTrack(`${t.name}.fov`,i.times.slice(),e))}}for(let e of n)e.optimize();return n.length===0?[]:[new r.AnimationClip(e.animation.name,e.animation.duration,n)]}_transformTracks(e,t,n,i){let a=n.times.length,o=new Float32Array(a*3),s=new Float32Array(a*4),c=new Float32Array(a*3),l=new r.Matrix4,u=new r.Vector3,d=new r.Quaternion,f=new r.Vector3;for(let e=0;e<a;e++)l.fromArray(i(n.matrices,e*16)).decompose(u,d,f),e>0&&d.x*s[e*4-4]+d.y*s[e*4-3]+d.z*s[e*4-2]+d.w*s[e*4-1]<0&&d.set(-d.x,-d.y,-d.z,-d.w),u.toArray(o,e*3),d.toArray(s,e*4),f.toArray(c,e*3);let p=(e,t)=>{for(let n=t;n<e.length;n++)if(e[n]!==e[n%t])return!0;return!1};p(o,3)&&e.push(new r.VectorKeyframeTrack(`${t}.position`,n.times.slice(),o)),p(s,4)&&e.push(new r.QuaternionKeyframeTrack(`${t}.quaternion`,n.times.slice(),s)),p(c,3)&&e.push(new r.VectorKeyframeTrack(`${t}.scale`,n.times.slice(),c))}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a,o=!1){let s=!!t.getAttribute(`uv`),c=this._materialForGeometry(e,t,n,a),l=new r.Mesh(t,c);l.name=a;let u=this.convertHandedness&&!o?wC(_w,i):i;new r.Matrix4().fromArray(u).decompose(l.position,l.quaternion,l.scale),l.updateMatrix(),t.boundingBox||t.computeBoundingBox();let d=t.boundingBox?t.boundingBox.clone().applyMatrix4(l.matrix).getSize(new r.Vector3):new r.Vector3,f=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<Sw&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`${d.x.toFixed(2)}×${d.y.toFixed(2)}×${d.z.toFixed(2)}`,tris:f}),l}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=n.clone(),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?wC(_w,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,t,n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(GC(e.params,`filename`,null)))){for(let e in t.attributes)JS(t.attributes[e].array);JS(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&JS(e.params[t].value)}}_lastPlyUse(e){let t=(this._plyUsers.get(e)??1)-1;return this._plyUsers.set(e,t),t>0||this._plyHeld.has(e)?!1:(this._plyCache.delete(e),!0)}_appendToBatch(e,t,n,r,i){let a=this._materialForGeometry(t,n,r,`merged shape`),o=n.getAttribute(`position`),s=n.getAttribute(`normal`),c=n.getAttribute(`uv`),l=n.index,u=o.count;this.triangleCount+=(l?l.count:u)/3,this.mergedShapes++;let d=e.get(a);d||e.set(a,d=[null,null]);let f=+!!c,p=d[f];p||(d[f]=p={material:a,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:c?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let m=i,h=MC(m),g=p.vertexCount;p.positions=bw(p.positions,(g+u)*3),p.normals=bw(p.normals,(g+u)*3),c&&(p.uvs=bw(p.uvs,(g+u)*2));let _=o.array,v=p.positions,y=s?s.array:null,b=p.normals;for(let e=0;e<u;e++){let t=e*3,n=(g+e)*3,r=_[t],i=_[t+1],a=_[t+2];if(v[n]=m[0]*r+m[4]*i+m[8]*a+m[12],v[n+1]=m[1]*r+m[5]*i+m[9]*a+m[13],v[n+2]=m[2]*r+m[6]*i+m[10]*a+m[14],!y)continue;let o=y[t],s=y[t+1],c=y[t+2],l=h[0]*o+h[1]*s+h[2]*c,u=h[4]*o+h[5]*s+h[6]*c,d=h[8]*o+h[9]*s+h[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),b[n]=l,b[n+1]=u,b[n+2]=d}c&&p.uvs.set(c.array.subarray(0,u*2),g*2);let x=l?l.count:u;p.indices=bw(p.indices,p.indexCount+x);let S=p.indices,C=l?l.array:null;for(let e=0;e<x;e++)S[p.indexCount+e]=g+(C?C[e]:e);return p.vertexCount+=u,p.indexCount+=x,p.triangles+=x/3,p.triangles>=kw?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(YS(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(YS(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(YS(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(YS(e.indices,e.indexCount),1)),e.positions=e.normals=e.uvs=e.indices=null,t}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.Mesh(this._batchGeometry(e),e.material);n.name=`merged_${this._mergedBatches++}`,n.frustumCulled=!1,t.add(n),this.placementCount++,this.report.length<Sw&&this.report.push({mesh:n.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles})}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(xw(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(xw(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(xw(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(yw(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(WC(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=GC(e,`type`,`flat`),a=WC(e,`width`,1),o=gw({P:t,basis:GC(e,`basis`,`bezier`),width0:WC(e,`width0`,a),width1:WC(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??jw[i]??1,tolerance:this.curveTolerance});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(WC(e,`levels`,3)))),{positions:a,indices:o,levels:s}=tw(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value;if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=[];for(let e=0;e+3<n.length;e+=4){let[t,r,a,o]=[n[e],n[e+1],n[e+2],n[e+3]];i.push(t,r,a,t,a,o)}let a=new r.BufferGeometry;return a.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),a.setIndex(i),a.computeVertexNormals(),a}_plyMesh(e){let t=GC(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)||t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){return new r.SphereGeometry(WC(e,`radius`,1),48,32)}_disk(e){let t=WC(e,`radius`,1),n=WC(e,`innerradius`,0),i=WC(e,`height`,0),a=[],o=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2,s=(e+1)/48*Math.PI*2,c=a.length/3;a.push(Math.cos(r)*n,Math.sin(r)*n,i),a.push(Math.cos(r)*t,Math.sin(r)*t,i),a.push(Math.cos(s)*t,Math.sin(s)*t,i),a.push(Math.cos(s)*n,Math.sin(s)*n,i),o.push(c,c+1,c+2,c,c+2,c+3)}let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(a),3)),s.setIndex(o),s.computeVertexNormals(),s}async _getMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e)},r=await YC(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.opacity}|${e.side}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}async _applyAreaLight(e,t,n){let r=await KC(t.params,`L`,n,[1,1,1]),i=WC(t.params,`scale`,1),a=r.rgb||[1,1,1];e.emissive.setRGB(a[0],a[1],a[2]),e.emissiveIntensity=i}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`){let r=GC(t.params,`filename`,null);if(r)try{let t=await this.resolveImage(r);t?n={texture:t}:this.warn(`image not found for texture "${e}": ${r}`)}catch(t){this.warn(`failed to load texture "${e}" (${r}): ${t.message}`)}}else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}_colorFromLikeNamedMaterial(e){for(let t of Fw(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=t&&t.yresolution?t.xresolution/t.yresolution:16/9,i;if(e.type===`orthographic`){let t=e.params?.screenwindow?.value,a=t?.length===4?(t[3]-t[2])/2:Math.max(1,1/n);i=new r.OrthographicCamera(-a*n,a*n,a,-a,.01,1e4)}else i=new r.PerspectiveCamera(this._verticalFov(e.params,n),n,.01,1e4);return i.name=`PBRT Camera`,this._poseCamera(i,e.cameraToWorld),i.updateMatrixWorld(!0),i}_poseCamera(e,t){let n=t,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1),e.up.copy(o.normalize()),e.position.copy(i),e.scale.set(1,1,1),e.lookAt(i.clone().add(a)),SC(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=WC(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=Pw(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=aw(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=WC(t.params,`scale`,1),i=GC(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=((await KC(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)},[1,1,1])).rgb||[1,1,1]).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&this.warn(`light "${t.type}" not supported (only infinite lights and emissive area lights are mapped)`)}},Lw=1e3,Rw=2048,zw=1e5;function Bw(e){let t=e[0],n=e=>{let t=e.lastIndexOf(`/`),n=/^(.*?)(\d+)\.pbrt$/i.exec(e.slice(t+1));return n?{group:e.slice(0,t+1)+`\0`+n[1].toLowerCase(),number:parseInt(n[2],10)}:null},r=t?n(t):null;if(!r)return null;let i=new Map;for(let t of e){let e=n(t);e&&e.group===r.group&&!i.has(e.number)&&i.set(e.number,t)}return i.size<2?null:[...i].sort((e,t)=>e[0]-t[0]).slice(0,Lw).map(([e,t])=>({path:t,number:e}))}function Vw(e){let t=e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array?new Uint32Array(e.buffer,e.byteOffset,e.length):null;t||=new Uint32Array(Float32Array.from(e).buffer);let n=2166136261;for(let e=0;e<t.length;e++)n=Math.imul(n^t[e],16777619),n^=n>>>15;return(n>>>0).toString(36)+`:`+e.length}function Hw(e){let t=``;for(let n of Object.keys(e).sort()){let{type:r,value:i}=e[n],a=ArrayBuffer.isView(i)||i.length>16&&typeof i[0]==`number`;t+=`${r} ${n}=${a?`#`+Vw(i):i.join(`,`)};`}return t}var Uw=class{constructor(e){this.materialNames=new Map;for(let[t,n]of e.namedMaterials)this.materialNames.set(n,t);this.cache=new Map}of(e){return`${e.type}|${+!!e.reverseOrientation}|${Hw(e.params)}|${this._material(e.material)}|${this._light(e.areaLight)}`}_material(e){if(!e)return`-`;let t=this.cache.get(e);if(t===void 0){let n=this.materialNames.get(e)??e._missingRef;t=n===void 0?`I:`+e.type+`:`+Hw(e.params):`N:`+n,this.cache.set(e,t)}return t}_light(e){if(!e)return`-`;let t=this.cache.get(e);return t===void 0&&this.cache.set(e,t=`L:`+e.type+`:`+Hw(e.params)),t}};function Ww(e,t){let n=new Int32Array(t.length).fill(-1),r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)n[r]=r,r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)n[--a]=--i;return r<i&&r<a&&!Gw(e,r,i,t,r,a,n)&&qw(e,r,i,t,r,a,n),n}function Gw(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,Rw),u=l+1,d=new Int32Array(2*l+3),f=[];for(let n=0;n<=l;n++){for(let a=-n;a<=n;a+=2){let l=a===-n||a!==n&&d[u+a-1]<d[u+a+1]?d[u+a+1]:d[u+a-1]+1,p=l-a;for(;l<s&&p<c&&e[t+l]===r[i+p];)l++,p++;if(d[u+a]=l,l>=s&&p>=c)return f.push(d.slice(u-n,u+n+1)),Kw(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function Kw(e,t,n,r,i,a){let o=t,s=n;for(let t=e.length-1;t>0;t--){let n=e[t-1],c=e=>n[e+t-1],l=o-s,u=l===-t||l!==t&&c(l-1)<c(l+1)?l+1:l-1,d=c(u),f=d-u;for(;o>d&&s>f;)a[i+--s]=r+--o;o=d,s=f}for(;o>0&&s>0;)a[i+--s]=r+--o}function qw(e,t,n,r,i,a,o){let s=new Map;for(let r=t;r<n;r++){let t=s.get(e[r]);t?t.push(r):s.set(e[r],[r])}let c=new Map;for(let e=i;e<a;e++){let t=s.get(r[e]);if(!t)continue;let n=c.get(r[e])??0;n<t.length&&(o[e]=t[n],c.set(r[e],n+1))}}function Jw(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function Yw(e,t,n){let r=e.length,i=new Float32Array(16*r),a=null,o=-1;for(let e=0;e<r;e++)if(t(e)){if(i.set(n(e),e*16),o<0)for(let t=0;t<e;t++)i.copyWithin(t*16,e*16,e*16+16);o=e}else a??=new Uint8Array(r).fill(1),a[e]=0,o>=0&&i.copyWithin(e*16,o*16,o*16+16);return{times:e,matrices:i,visible:a}}function Xw(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!Jw(t,0,t,e))return!1;return!0}var Zw=class{constructor(e,t){this.times=Float32Array.from(e),this.name=t,this.base=null,this.frame=-1,this.keyIds=new Map,this.tracks=[],this.prev=null,this.placements=new Map,this.templates=new Map,this.cameras=[],this.warnings=new Set}addFrame(e){let t=++this.frame;t===0?this.base=e:this._adoptDefinitions(e);for(let t of e.warnings)this.warnings.add(t);let n=new Uw(e),r=new Int32Array(e.shapes.length);for(let t=0;t<r.length;t++){let i=n.of(e.shapes[t]),a=this.keyIds.get(i);a===void 0&&this.keyIds.set(i,a=this.keyIds.size),r[t]=a}let i=this.prev?Ww(this.prev.keys,r):null,a=Array(r.length);for(let o=0;o<r.length;o++){let r=e.shapes[o],s=i&&i[o]>=0?this.prev.tracks[i[o]]:null;s?(s.last=t,s.ctms?s.ctms.push(r.ctm):r.ctm!==s.shape.ctm&&!Jw(r.ctm,0,s.shape.ctm,0)&&(s.ctms=Array(t-s.first).fill(s.shape.ctm),s.ctms.push(r.ctm))):(s={shape:r,first:t,last:t,ctms:null},t>0&&this._adoptMaterial(r,n.materialNames),this.tracks.push(s)),a[o]=s}this.prev={keys:r,tracks:a},this._addPlacements(e,t,this._resolveTemplates(e,t,n)),this.cameras.push(e.camera?{cameraToWorld:e.camera.cameraToWorld,fov:e.camera.params?.fov?.value?.[0]}:null)}_adoptDefinitions(e){for(let[t,n]of e.namedMaterials)this.base.namedMaterials.has(t)||this.base.namedMaterials.set(t,n);for(let[t,n]of e.namedTextures)this.base.namedTextures.has(t)||this.base.namedTextures.set(t,n)}_resolveTemplates(e,t,n){let r=new Map;for(let[i,a]of e.objects){let e=``;for(let t of a)e+=n.of(t)+`@`+Array.prototype.join.call(t.relativeCTM||t.ctm,`,`)+`;`;let o=i+`\0`+e,s=this.templates.get(o);if(s===void 0&&(s=t===0||!this.base.objects.has(i)?i:`${i} @${t}`,this.templates.set(o,s),t>0)){for(let e of a)this._adoptMaterial(e,n.materialNames);this.base.objects.set(s,a)}r.set(i,s)}return r}_adoptMaterial(e,t){let n=e.material&&t.get(e.material);n!==void 0&&(e.material=this.base.namedMaterials.get(n)??e.material)}_addPlacements(e,t,n){for(let[r,i]of e.instances){let e=n.get(r)??r,a=this.placements.get(e);if(a||this.placements.set(e,a={counts:new Int32Array(this.times.length),diffs:new Map}),a.counts[t]=i.count,t===0)continue;let o=this.base.instances.get(e),s=o?.count??0;for(let e=0;e<i.count;e++){let n=e*16;if(e<s&&Jw(i.matrices,n,o.matrices,n))continue;let r=a.diffs.get(e);r||a.diffs.set(e,r=new Map),r.set(t,i.matrices.slice(n,n+16))}}}finish(){let e=this.base,t=this.times,n=this.frame+1;e.shapes=this.tracks.map(e=>{let{shape:r,first:i,last:a,ctms:o}=e;return(i>0||a<n-1||o)&&(r.motion=Yw(t,e=>e>=i&&e<=a,e=>o?o[e-i]:r.ctm)),r}),e.warnings=[...this.warnings],e.animatedInstances=this._finishPlacements(e,t,n);let r=this.cameras;if(r[0]&&r.every(Boolean)){let n=Yw(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!Xw(n)||a)&&(e.camera.motion={...n,fov:a?Float32Array.from(i):null})}return e.animation={name:this.name,duration:t[n-1],frames:n},e}_finishPlacements(e,t,n){let r=[],i=0;for(let[a,{counts:o,diffs:s}]of this.placements){let c=e.instances.get(a),l=c?.count??0,u=Math.max(...o.subarray(0,n)),d=[];for(let e=0;e<u;e++){let u=s.get(e),f=!!u;for(let t=0;t<n&&!f;t++)f=e>=o[t];if(f&&r.length<zw){let n=Yw(t,t=>e<o[t],t=>u?.get(t)??c.matrices.subarray(e*16,e*16+16));r.push({name:a,motion:n})}else f&&i++,e<l&&d.push(e)}if(c&&d.length!==l){let t=new Float32Array(d.length*16);d.forEach((e,n)=>t.set(c.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=l-d.length,c.matrices=t,c.matricesEnd=null,c.count=d.length}}return i>0&&e.warnings.push(`${i.toLocaleString()} moving placement(s) past ${zw.toLocaleString()} left static`),r}};function Qw(e){if(!e.hasMotion)return e;let{start:t,end:n}=e.transformTimes,r=n-t;if(!(r>0))return e;let i=Float32Array.of(0,r),a=(e,t,n,r)=>{let a=new Float32Array(32);for(let i=0;i<16;i++)a[i]=e[t+i],a[16+i]=n[r+i];return{times:i,matrices:a,visible:null}};for(let t of e.shapes)t.ctmEnd&&(t.motion=a(t.ctm,0,t.ctmEnd,0));e.animatedInstances=[];for(let t of e.instances.values()){if(!t.matricesEnd)continue;let n=[];for(let r=0;r<t.count;r++){let i=r*16;Jw(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=zw?n.push(r):e.animatedInstances.push({name:t.name,motion:a(t.matrices,i,t.matricesEnd,i)})}if(n.length!==t.count){let r=new Float32Array(n.length*16);n.forEach((e,n)=>r.set(t.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=t.count-n.length,t.matrices=r,t.count=n.length}t.matricesEnd=null}return e.camera?.cameraToWorldEnd&&(e.camera.motion={...a(e.camera.cameraToWorld,0,e.camera.cameraToWorldEnd,0),fov:null}),e.animation={name:`Shutter motion`,duration:r,frames:2},e}var $w=2e6,eT=new TextDecoder;function tT(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function nT(e,t){return!e||t.startsWith(`/`)?tT(t):tT(`${e}/${t}`)}var rT=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=tT(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readHead(e,t){return e?e.bytes?e.bytes.subarray(0,t):!e.lazy||!this.source?null:this.source.readHead?this.source.readHead(e.key,t):this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(nT(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null,n=null){let r=t!==null&&this.findRecord(nT(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),JS(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=tT(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}};function iT(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}var aT=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),oT=4*1024*1024,sT=aT(`WorldBegin`),cT=[aT(`Include`),aT(`Import`)];function lT(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function uT(e){for(let t=iT(e,sT);t>=0;t=iT(e,sT,t+1))if(lT(e,t))return!0;return!1}function dT(e,t){for(let n of cT)for(let r=iT(e,n);r>=0;r=iT(e,n,r+1)){if(!lT(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=eT.decode(e.subarray(a,i));t.add(tT(o).toLowerCase().split(`/`).pop())}}function fT(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,uT(t)),dT(t,n)}return pT(t,r,n)}function pT(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function mT(e){return fT(e)[0]||null}async function hT(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=async n=>{let r=new Set,i=new Map,a=!1;for(let o of t){let t=await n(o);t&&(i.set(o.key,uT(t)),dT(t,r),t.length>=oT&&(a=!0),o.lazy&&(e.release(o),JS(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,oT)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return pT(t.map(e=>e.key),a,i)}async function gT(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new rT(t,n),c=[],l=await hT(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new BC({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},p=performance.now(),m=!u&&e.animation!==!1?Bw(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>$w)c.push(`${m.length} animation frames found, but the scene is too large to parse once per frame — loaded "${m[0].path}" only`),m=null,h=Qw(e);else{let t=new Zw(m.map(e=>(e.number-m[0].number)/30),_T(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=Qw(await f(d));let g=performance.now()-p;s.releaseScenes();let _=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),v=new Map,y=async e=>{let t=await s.read(e);return t?(s.release(e),r(_(t))):null},b=new Iw({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,resolvePLY:async e=>{let t=s.findRecord(e);return t?(v.has(t.norm)||v.set(t.norm,await y(t)),v.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),x=performance.now(),S=await b.build(h);return{...S,entryPath:m?m[0].path:d,frames:m?m.map(e=>e.path):null,candidates:l,warnings:[...c,...S.warnings??[]],parseMs:g,buildMs:performance.now()-x}}function _T(e){let t=e[0].path.split(`/`);return`${t.length>1?t[t.length-2]:t[0].replace(/\d+\.pbrt$/i,``)||`frames`} · frames ${e[0].number}–${e[e.length-1].number}`}var vT=[`sourceFile`,`url`,`file`];function yT(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function bT(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function xT(e){let t=yT(e);if(!t)return null;let n=yT(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function ST(e){let t=yT(e);if(!t)return null;let n=vT.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=bT(t.rotation),i=bT(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function CT(e){let t=xT(e);if(!t)return null;let n=ST(t.environment);return n?{environment:n}:null}function wT(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=CT(e);if(t)return t}return null}Ys();var TT={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usd:{type:`model`,name:`USD (Universal Scene Description)`},usda:{type:`model`,name:`USDA (USD ASCII)`},usdc:{type:`model`,name:`USDC (USD Crate)`},usdz:{type:`model`,name:`USDZ (USD Archive)`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`},gz:{type:`archive`,name:`Gzipped TAR Archive`},tgz:{type:`archive`,name:`Gzipped TAR Archive`},tar:{type:`archive`,name:`TAR Archive`}},ET=/\.(usd|usda|usdc)$/i,DT=/\.(png|jpg|jpeg|avif)$/i,OT=3e4,kT=4e9;function AT(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var jT=683;function MT(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var NT=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,profile:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this._issues=i,this._profile=a??xe(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Y.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await ox(t,{downloads:this.downloads,key:i,policy:a,name:$b(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}:${this._profile?.name??``}:${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new rx(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,f.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this._pendingGraph=null,this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return TT[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await this.loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadAssetFromUrl(t,n={}){let{filename:r=$b(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw Error(`Unsupported file format: ${r}`);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,Rn(await Ln(e))):null,r=await this._loadModelFileByExtension(e,t);return this._sourceKey=n,r}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usd`:case`usda`:case`usdc`:case`usdz`:return await this.loadUSDFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return Lu(r,Rn(await Ln(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&Lu(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n){let i=e._isNetworkUrl(t),a=`Downloading Environment...`,o=await this._viaCache(t,a,i),c=o.cached?void 0:this._downloadProgress(a,i),l;try{n===`hdr`||n===`exr`?l=await(n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader(this._loadingManager).setDataType(r.FloatType))).loadAsync(o.url,c):ti().decodeImage?(l=await GS(o.url,`image/${n===`jpg`?`jpeg`:n}`),l.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),l=await this.loaderCache.texture.loadAsync(o.url,c),l.colorSpace=r.SRGBColorSpace)}finally{o.release()}return this._downloadComplete(`Processing Environment...`,62),l.mapping=r.EquirectangularReflectionMapping,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=Ox(await this._readHead(e)),n=e=>z({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4}),r;if(t===`gzip`){let t=await this._unpackGzip(e,e.name);t?(r=t.index.listing,t.release()):{listing:r}=await Vx(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await fS(e,this.storage))?.listing??await Ux(e,{onProgress:n}):(await iS(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=qx(r);return{kind:t??`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async _unpackGzip(e,t){try{return await dS(e,{storage:this.storage,label:t,onProgress:e=>z({isLoading:!0,status:`Unpacking archive… ${(e/1e9).toFixed(1)} GB`,progress:4})})}catch(e){return console.warn(`Unpacking "${t}" to storage failed, reading it in memory: ${e.message}`),null}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=Ox(await this._readHead(e)),c=this.storage?Rn(await Ln(e)):null,l={element:r,promptBytes:a,pbrtEntry:n,pbrt:o,archiveId:c};if(s===`tar`)return await this._loadSeekable(e,t,l);if(s===`gzip`){let a=await this._unpackGzip(e,t);if(a)try{return await this._loadSeekable(a.file,t,{...l,index:a.index})}finally{a.release()}let u=await this._readStreamedArchive(e,t,s,r,i);if(mT(u))return await this.loadPBRTFromZip(u,t,n,o);let d=await this._loadNonPBRTArchive(u,t);return this._sourceKey=this._keyed(`archive`,c),d}return await this._loadSeekable(e,t,{...l,zip:!0})}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _loadSeekable(e,t,{element:n,promptBytes:r,pbrtEntry:i,pbrt:a,index:o=null,zip:s=!1,archiveId:c=null}){let l=await this._openSeekableArchive(e,t,n,r,{index:o,zip:s});if(l.archiveId=c,l.elements=(Array.isArray(n)?n:[n]).filter(Boolean),l.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,i,a,l);for(let e of l.listing)e.offset!==void 0&&(l.entries[e.path]??=await l.read(e.path));let u=await this._loadNonPBRTArchive(l.entries,t);return this._sourceKey=this._keyed(`archive`,c),u}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.storage?.area(Wn.SCENES),a=i?await i.open(e):null;if(!a)return null;let o=performance.now(),s=null;try{z({isLoading:!0,status:`Opening the stored scene...`,progress:6});let e=await a.json(`graph.json`),i=await a.file(`data.bin`),s=new rT({},t),c=await RS(e,i,{loadTexture:async(e,t)=>{let i=await s.readPath(e);return i?t===`environment`?r(i,e):n(i,e):null}});return{...c.stats,group:c.root,environment:c.environment?{texture:c.environment}:null,animations:c.animations,report:null,parseMs:0,buildMs:performance.now()-o,fromStorage:!0}}catch(e){return s=e,null}finally{a.release(),s&&(console.warn(`The stored scene could not be used, parsing the archive instead: ${s.message}`),this._issues?.warn(Y.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.storage?.area(Wn.SCENES);if(!r)return;let i;try{i=jS(t.group,{environment:t.environment?.texture??null,animations:t.animations??[],stats:{meshCount:t.meshCount,entryPath:t.entryPath,candidates:t.candidates,frames:t.frames,warnings:t.warnings,triangleCount:t.triangleCount,placementCount:t.placementCount,mergedShapes:t.mergedShapes,skippedForBudget:t.skippedForBudget,droppedNoTemplate:t.droppedNoTemplate}})}catch(e){e instanceof SS?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a={key:e,encoded:i,label:n,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null};eg(a.parseMs,i.byteLength)?this._writeGraph(r,a):this._pendingGraph=a}flushPendingGraph(e){let t=this._pendingGraph;this._pendingGraph=null;let n=this.storage?.area(Wn.SCENES);!t||!n||!eg(t.parseMs+e,t.encoded.byteLength)||this._writeGraph(n,t)}_writeGraph(e,t){(async()=>{let n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength});if(n)try{await MS(n,t.encoded,{release:!0}),await n.commit({triangles:t.triangles})}catch(e){await n.abort(),console.warn(`Storing the scene failed:`,e)}})().catch(e=>console.warn(`Storing the scene failed:`,e))}async _openSeekableArchive(e,t,n,r,{index:i=null,zip:a=!1}={}){let o=Array.isArray(n)?n.filter(Boolean):n?[n]:[],s=o.length?Kx(o):null,c;if(a)c=await sS(e,{filter:s});else{let t=i??await fS(e,this.storage);c=await Gx(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||pS(e,this.storage,c.index).catch(()=>{})}let l=c.listing.reduce((e,t)=>e+t.size,0);return o.length===0&&this._requireElementChoice(t,c.listing,l,r),console.info(`Archive "${t}": indexed ${c.indexed} entries, ${(l/1e9).toFixed(1)} GB, none resident`+(o.length?`, ${o.length} part${o.length>1?`s`:``} selected.`:`.`)),c}_requireElementChoice(e,t,n,r=kT){if(n<r)return;let{root:i,elements:a}=qx(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},fn.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await Vx(e,{filter:a.length?Kx(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>z({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=qx(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},fn.WARNING),i}if(l){let e=Kx(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this._issues?.record(Y.ASSET_ARCHIVE_TOO_LARGE,`${t} files of the chosen parts were left out: they did not fit the ${((i??15e8)/1e9).toFixed(1)} GB in-memory read budget`,{elements:a,missing:t,retainedBytes:c},fn.WARNING)}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,r={},i=null){if(z({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let a=e=>this.loaderCache.ply.parse(e),o=async(e,t)=>{let n=await this._pbrtTextureFromBytes(e,t);return n&&(n.userData[mS]=t),n},s=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),r=new Blob([e]),i=URL.createObjectURL(r);try{let e=await this.loadEnvironmentByExtension(i,n);return Lu(e,`bytes:${await In(r)}`),e.userData[mS]=t,e.userData[hS]=`environment`,e}finally{URL.revokeObjectURL(i)}},c=performance.now(),l={animation:r.animation,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides,curveTolerance:r.curveTolerance,instanceIncludes:r.instanceIncludes},u=i?.archiveId?this._keyed(`pbrt:2.4:${Zh}`,`${i.archiveId}|${n??``}|${[...i.elements??[]].sort().join(`,`)}|${JSON.stringify(l)}`):null,d=u?await this._loadStoredGraph(u,i,{imageFromBytes:o,envFromBytes:s}):null,f=d??await gT({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,...l}),{group:p,environment:m,animations:h,report:g,warnings:_,meshCount:v,entryPath:y,candidates:b,frames:x,parseMs:S,buildMs:C,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O}=f;d&&console.info(`PBRT scene "${y}" opened from storage in ${(C/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:S,buildMs:C,loaderMs:performance.now()-c,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,meshCount:v,frames:x?.length??1};let k=new Set(x??[y]),A=b.filter(e=>!k.has(e));if(A.length>0&&(console.warn(`PBRT archive holds ${b.length} scenes; loaded "${y}". Others: ${A.join(`, `)}`),this._issues?.record(Y.ASSET_AMBIGUOUS_ENTRY,`archive holds ${b.length} pbrt scenes; loaded "${y}"`,{loaded:y,alternatives:A},fn.WARNING)),g&&g.length&&typeof console.table==`function`){let e=g.length<v?` (first ${g.length} of ${v})`:``;console.groupCollapsed(`PBRT loader: ${v} mesh(es) from "${y}"${e}`),console.table(g),console.groupEnd()}return _&&_.length&&(console.warn(`PBRT loader: ${_.length} warning(s) parsing "${y}"`),_.forEach(e=>console.warn(` •`,e))),m?.texture&&(m.texture.generateMipmaps=!0,this.applyEnvironmentToScene(m.texture)),p.name=y||t,this.releaseTargetModel(),this._sourceKey=u,u&&!d&&this._storeGraph(u,f,t),this.targetModel=p,this.animations=h??[],m?.texture&&(this.sceneMetadata={environment:{rotation:0,intensity:1}}),z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:p,filename:`${y} (from ZIP)`}),p}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader().setDataType(r.FloatType));i=await this._loadViaObjectURL(t,e)}else if(n===`tga`){if(!this.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(TT[n]&&TT[n].type===`model`)return ET.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>ET.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(ET.test(e)||DT.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,m.zipSync)(i),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(ET,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usd`:case`usda`:case`usdc`:case`usdz`:o=await this.loadUSDFromArrayBuffer(e,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{try{this._throwDeferred()}catch(e){n(e);return}this.releaseTargetModel(),this.targetModel=e.scene,this.sceneMetadata=wT(e),this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}finally{this._disposeGLTFLoader(s)}}else return await this.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.releaseTargetModel(),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),OT))]);return clearTimeout(r),i||this._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${OT}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.releaseTargetModel(),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){let{dracoDecoderPath:e,ktx2TranscoderPath:t}=Ks(),n=new c.DRACOLoader;n.setDecoderConfig({type:`js`}),n.setDecoderPath(e);let r=new l.KTX2Loader;r.setTranscoderPath(t),this.renderer&&(r.detectSupport(this.renderer),r.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1});let i=new o.GLTFLoader(this._loadingManager);return i.setDRACOLoader(n),i.setKTX2Loader(r),i.setMeshoptDecoder(p.MeshoptDecoder),ti().decodeImage&&i.register(e=>KS(e,(e,t)=>this._reportImageFailure(e,t))),i}_reportImageFailure(e,t){try{this._issues?.record(Y.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=wT(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(le(e),e.parent?.remove(e)):ce(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=wT(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let n=this.loaderCache.ply.parse(e),i;if(n.index!==null)i=new r.Mesh(n,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=n.hasAttribute(`color`),i=new r.Points(n,e)}return i.name=t,this.releaseTargetModel(),this.targetModel=i,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(z({isLoading:!0,status:`Processing USD Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usd){let{USDLoader:e}=await import(`three/examples/jsm/loaders/USDLoader.js`);this.loaderCache.usd=new e}let n=await new Promise((t,n)=>{this.loaderCache.usd.parse(e,``,t,n)});return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new jh(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=MT(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/jT,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=jT,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*MT(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._profile.areaLightIntensityScale,i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(Y.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=AT(e.geometry));let t=(0,d.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(TT))r.type===e&&(t[n]=r);return t}return TT}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this._pendingGraph=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},PT={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},FT=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function IT(e=1,t=1){let n={...PT,defaultView:null},r={...PT,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new FT(r);return r}var LT=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},RT=8,zT=4,BT=.25,VT=r.MathUtils.degToRad(89),HT=.25,UT={KeyD:[1,0,0],ArrowRight:[1,0,0],KeyA:[-1,0,0],ArrowLeft:[-1,0,0],KeyW:[0,1,0],ArrowUp:[0,1,0],KeyS:[0,-1,0],ArrowDown:[0,-1,0],KeyE:[0,0,1],KeyQ:[0,0,-1]},WT=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,GT=e=>e.shiftKey?zT:e.altKey?BT:1,KT={type:`change`},qT={type:`start`},JT=new r.Vector3,YT=new r.Vector3,XT=new r.Vector3,ZT=new r.Vector3,QT=new r.Quaternion,$T=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/RT,this._held=new Set,this._factor=1,this._lastTime=0,this._drag=null,this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this.release=this.release.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),t&&this.connect(t)}get active(){return this.enabled&&this.orbit.enabled}fitSpeed(e){this.speed=(e>0?e:1)/RT}connect(e){super.connect(e);let t=e.ownerDocument;t?.addEventListener(`keydown`,this._onKeyDown),t?.addEventListener(`keyup`,this._onKeyUp),t?.addEventListener(`visibilitychange`,this.release),t?.defaultView?.addEventListener(`blur`,this.release),e.addEventListener(`pointerdown`,this._onPointerDown),e.addEventListener(`pointermove`,this._onPointerMove),e.addEventListener(`pointerup`,this._onPointerUp),e.addEventListener(`pointercancel`,this._onPointerUp)}disconnect(){let e=this.domElement;if(!e)return;let t=e.ownerDocument;t?.removeEventListener(`keydown`,this._onKeyDown),t?.removeEventListener(`keyup`,this._onKeyUp),t?.removeEventListener(`visibilitychange`,this.release),t?.defaultView?.removeEventListener(`blur`,this.release),e.removeEventListener(`pointerdown`,this._onPointerDown),e.removeEventListener(`pointermove`,this._onPointerMove),e.removeEventListener(`pointerup`,this._onPointerUp),e.removeEventListener(`pointercancel`,this._onPointerUp)}dispose(){this.disconnect()}update(e=this._elapsed()){if(!this._held.size||!this.active)return!1;let t=0,n=0,r=0;for(let e of this._held){let[i,a,o]=UT[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return YT.set(1,0,0).applyQuaternion(i.quaternion),JT.crossVectors(i.up,YT).normalize(),YT.crossVectors(JT,i.up),XT.set(0,0,0).addScaledVector(YT,t).addScaledVector(JT,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(XT),this.orbit.target.add(XT),i.updateMatrixWorld(),this.dispatchEvent(KT),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,HT);return this._lastTime=e,t}_look(e,t){let n=this.object,i=this.orbit.target,a=n.position.distanceTo(i)||1,o=r.MathUtils.degToRad(n.fov)/(this.domElement.clientHeight||1);n.quaternion.premultiply(QT.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(JT);let s=Math.asin(r.MathUtils.clamp(JT.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-VT,VT);n.quaternion.multiply(QT.setFromAxisAngle(ZT.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(JT),a),this.dispatchEvent(KT)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(WT))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=GT(e),UT[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(qT))))}}_onKeyUp(e){this._factor=GT(e),this._held.delete(e.code)}release(){this._held.clear(),this._factor=1}_onPointerDown(e){!this.active||e.button!==0||!e.isPrimary||(this._drag={id:e.pointerId,x:e.clientX,y:e.clientY},this.domElement.setPointerCapture?.(e.pointerId))}_onPointerMove(e){let t=this._drag;if(!t||e.pointerId!==t.id)return;let n=e.clientX-t.x,r=e.clientY-t.y;t.x=e.clientX,t.y=e.clientY,this.active&&(n||r)&&this._look(n,r)}_onPointerUp(e){this._drag?.id===e.pointerId&&(this._drag=null,this.domElement.releasePointerCapture?.(e.pointerId))}};R();var eE=Object.freeze(new r.Vector3(1,1,1)),tE=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,nE=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new LT(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this._reportedOrthoHeight=null,this._reportOrthoHeight=this._reportOrthoHeight.bind(this),this.controls.addEventListener(`change`,this._reportOrthoHeight),this.walkControls=new $T(this.camera,e,this.controls),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Ie.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Ie.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._afPick=null,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0,this.resetAutoFocus()}addCameraFromView(e){let t=this.camera,n=t.orthographic?new r.OrthographicCamera(t.left,t.right,t.top,t.bottom,t.near,t.far):new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.zoom=t.zoom,n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),dofBlur:e(`dofBlur`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint},orthoHeight:this.orthoHeight}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio,dofBlur:e.dofBlur}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}switchCamera(e,t,n,i){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,i??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let a=this.cameras[this.currentCameraIndex];if(a&&(a.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??eE),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let n=this.cameras[e];if(this.camera.position.copy(n.position),this.camera.quaternion.copy(n.quaternion),this.camera.scale.copy(n.scale),n.isPerspectiveCamera&&(this.camera.fov=n.fov),this.camera.near=n.near,this.camera.far=n.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=n.userData?.__rayzeeOrbitTarget;if(e)this.controls.target.copy(e);else{let e=new r.Vector3(0,0,-1).applyQuaternion(n.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i)}this.controls.update()}}this.resetAutoFocus();let o=this.cameras[e],s=o?.userData?.__rayzeeEffects;this._showOrthographic(s?s.orthoHeight:tE(o)),this._applyEffects(s),n?.(),i?.(),this.dispatchEvent({type:I.CAMERA_SWITCHED,cameraIndex:e,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)})}_showOrthographic(e){e>0?this._setView(!0,e/2):this._setView(!1);let t=this._getSettings?.(`cameraProjection`),n=e>0?`orthographic`:t===`orthographic`?`perspective`:t;n!==t&&this._applySettings?.({cameraProjection:n})}applyProjection(e){let t=this.camera,n=e===`orthographic`;if(t.orthographic!==n){if(n)this._setView(!0,this._fittedHalfHeight());else{let e=this.controls.target,n=this.orthoHeight/2/Math.tan(r.MathUtils.degToRad(t.fov)/2);t.position.sub(e).setLength(n).add(e),this._setView(!1)}this.controls.update()}}get orthoHeight(){return tE(this.camera)}setOrthoHeight(e){e>0&&(this._setView(this.camera.orthographic,e/2),this._onReset?.())}fitOrthographic(){this.camera.orthographic&&this.setOrthoHeight(2*this._fittedHalfHeight())}_setView(e,t=this.camera.orthoHalfHeight){let n=this.camera;n.orthographic=e,n.orthoHalfHeight=t,n.zoom=1,n.updateProjectionMatrix(),this._reportOrthoHeight()}_fittedHalfHeight(){return this.camera.position.distanceTo(this.controls.target)*Math.tan(r.MathUtils.degToRad(this.camera.fov)/2)}_reportOrthoHeight(){if(!this.camera.orthographic)return;let e=this.orthoHeight;e!==this._reportedOrthoHeight&&(this._reportedOrthoHeight=e,this.dispatchEvent({type:I.ORTHO_HEIGHT_UPDATED,height:e}))}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}setNavigationMode(e){let t=e===`walk`;if(this.walkControls.enabled===t)return;let n=this.controls;if(n.enableRotate=n.enablePan=n.enableZoom=!t,this.walkControls.enabled=t,t)return;this.walkControls.release();let i=this.interactionManager?.pickSurface(0,0);if(!i)return;let a=r.MathUtils.clamp(i.distance,n.minDistance,n.maxDistance);n.target.copy(this.camera.position).addScaledVector(this.camera.getWorldDirection(new r.Vector3),a),n.update()}get navigationMode(){return this.walkControls.enabled?`walk`:`orbit`}updateControls(){this.walkControls.update(),this.controls.update()}captureView(){let e=this.camera,t=this.orthoHeight??2*this._fittedHalfHeight();return{position:e.position.clone(),target:this.controls.target.clone(),fov:e.fov,orthoHeight:t}}applyPose(e){let t=this.camera;t.position.copy(e.position),t.lookAt(e.target),this.controls.target.copy(e.target),t.orthographic?this._setView(!0,e.orthoHeight/2):(t.fov=e.fov,t.updateProjectionMatrix()),t.updateMatrixWorld()}serialize(){let e=this.camera,t=this._defaultCameraState;return{current:this.currentCameraIndex,view:{position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),fov:e.fov,near:e.near,far:e.far,zoom:e.zoom,orthographic:!!e.orthographic,orthoHalfHeight:e.orthoHalfHeight,target:this.controls.target.toArray()},defaultView:t?{position:t.position.toArray(),quaternion:t.quaternion.toArray(),scale:t.scale.toArray(),fov:t.fov,near:t.near,far:t.far,target:t.target?.toArray()??null}:null,navigationMode:this.navigationMode,autoFocus:{mode:this.autoFocusMode,point:{...this.afScreenPoint}},cameras:this.cameras.map((e,t)=>{let n={index:t,name:e.name??``,effects:zr(e.userData?.__rayzeeEffects)??null};return t===0||!e.userData?.__rayzeeUserCamera?n:{...n,user:!0,orthographic:!!e.isOrthographicCamera,frustum:e.isOrthographicCamera?[e.left,e.right,e.top,e.bottom]:null,fov:e.fov??null,aspect:e.aspect??null,near:e.near,far:e.far,zoom:e.zoom,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),orbitTarget:e.userData.__rayzeeOrbitTarget?.toArray()??null}})}}restore(e){let t=[];if(!e)return{mismatched:t};this.cameras=this.cameras.filter(e=>!e.userData?.__rayzeeUserCamera);let n=new Map;for(let i of e.cameras??[]){if(i.user){let e=i.orthographic?new r.OrthographicCamera(...i.frustum,i.near,i.far):new r.PerspectiveCamera(i.fov,i.aspect,i.near,i.far);e.name=i.name,e.zoom=i.zoom??1,e.position.fromArray(i.position),e.quaternion.fromArray(i.quaternion),e.scale.fromArray(i.scale),e.updateProjectionMatrix(),e.updateMatrixWorld(!0),e.userData.__rayzeeUserCamera=!0,e.userData.__rayzeeEffects=Br(i.effects),i.orbitTarget&&(e.userData.__rayzeeOrbitTarget=new r.Vector3().fromArray(i.orbitTarget)),n.set(i.index,this.cameras.length),this.cameras.push(e);continue}let e=this.cameras[i.index];if(!e||i.index>0&&(e.name??``)!==i.name){t.push(i.name);continue}n.set(i.index,i.index),i.effects&&(e.userData.__rayzeeEffects=Br(i.effects))}this._userCameraCounter=this.cameras.filter(e=>e.userData?.__rayzeeUserCamera).length,this.currentCameraIndex=n.get(e.current)??0;let i=e.defaultView;this._defaultCameraState=i?{position:new r.Vector3().fromArray(i.position),quaternion:new r.Quaternion().fromArray(i.quaternion),scale:new r.Vector3().fromArray(i.scale),fov:i.fov,near:i.near,far:i.far,target:i.target?new r.Vector3().fromArray(i.target):null}:null,e.navigationMode&&this.setNavigationMode(e.navigationMode);let a=e.view;if(a){let e=this.camera;e.position.fromArray(a.position),e.quaternion.fromArray(a.quaternion),e.scale.fromArray(a.scale),e.fov=a.fov,e.near=a.near,e.far=a.far,this._setView(a.orthographic,a.orthoHalfHeight),e.zoom=a.zoom??1,e.updateProjectionMatrix(),e.updateMatrixWorld(!0),this.controls.target.fromArray(a.target),this.controls.update()}return e.autoFocus&&(this.setAutoFocusMode(e.autoFocus.mode),this.setAFScreenPoint(e.autoFocus.point.x,e.autoFocus.point.y)),this.resetAutoFocus(),this._reportOrthoHeight(),this.dispatchEvent({type:I.CAMERA_SWITCHED,cameraIndex:this.currentCameraIndex,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)}),{mismatched:t}}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}resetAutoFocus(){this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!0}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let t=e||this._afContext;if(!t||!this.interactionManager)return;let{assetLoader:n,currentFocusDistance:r,pathTracer:i,setFocusDistance:a,softReset:o,hardReset:s}=t;if(this.autoFocusMode===`manual`)return;if(!i?.enableDOF?.value||i.cameraProjection?.value===Se.equirectangular){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let c=i;if(c?.isReady&&c.renderMode?.value===1&&c.frameCount>0&&!c.isComplete)return;let l=this._pickFocusPoint(c.resetCount),u;if(l)u=Ib(l,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?Ib(this.controls.target,this.camera):0;u=e>0?e:Ie.FALLBACK_DISTANCE*(n?.getSceneScale()||1),this._lastValidFocusDistance=u}let d=this._afPointDirty;this._afPointDirty=!1,d||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(u-this._smoothedFocusDistance)/this._smoothedFocusDistance>Ie.SNAP_THRESHOLD?this._smoothedFocusDistance=u:this._smoothedFocusDistance+=this.afSmoothingFactor*(u-this._smoothedFocusDistance);let f=r,p=this._smoothedFocusDistance;if(d||f===0||Math.abs(p-f)/Math.max(f,.001)>.001){a(p);let e=n?.getSceneScale()||1;this.dispatchEvent({type:I.AUTO_FOCUS_UPDATED,distance:p/e,worldDistance:p});let t=Math.abs(p-f)/Math.max(f,.001);d?s?.():t>Ie.RESET_THRESHOLD&&o?.()}}_pickFocusPoint(e){let t=this.camera,{x:n,y:i}=this.afScreenPoint,a=this._afPick??={point:new r.Vector3,hit:!1,resetCount:NaN,x:NaN,y:NaN,view:new r.Matrix4,projection:new r.Matrix4};if(this._afPointDirty||e!==a.resetCount||n!==a.x||i!==a.y||!a.view.equals(t.matrixWorld)||!a.projection.equals(t.projectionMatrix)){let r=this.interactionManager.pickSurface(n*2-1,1-i*2);a.hit=!!r,r&&a.point.copy(r.point),a.resetCount=e,a.x=n,a.y=i,a.view.copy(t.matrixWorld),a.projection.copy(t.projectionMatrix)}return a.hit?a.point:null}setInteractionManager(e){this.interactionManager=e}initAutoFocus({assetLoader:e,pathTracer:t,settings:n,softReset:r,hardReset:i}){this._afContext={assetLoader:e,pathTracer:t,setFocusDistance:e=>n.set(`focusDistance`,e,{silent:!0}),softReset:r,hardReset:i},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>n.get(`focusDistance`)})}dispose(){this.walkControls?.dispose(),this.controls?.removeEventListener(`change`,this._reportOrthoHeight),this.controls?.dispose()}},rE=.001,iE=2,aE=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),oE=class{constructor(e,t){this._cameraManager=e,this._onChange=t,this.keys=[],this._nextId=1,this._interpolants=null}get animates(){return this.keys.length>1}get duration(){return this.keys.length?this.keys[this.keys.length-1].time:0}addKey(e=this.keys.length?this.duration+iE:0){return this.add(this._cameraManager.captureView(),e)}updateKey(e){this.update(e,this._cameraManager.captureView())}seek(e){let t=this.sample(e);return t&&this._cameraManager.applyPose(t),!!t}add(e,t){let n={id:this._nextId++,time:t,...sE(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,sE(t)),this._changed())}setTime(e,t){let n=this.get(e);!n||!(t>=0)||(n.time=t,this._changed())}remove(e){let t=this.keys.length;this.keys=this.keys.filter(t=>t.id!==e),this.keys.length!==t&&this._changed()}clear(){this.keys.length&&(this.keys=[],this._changed())}serialize(){return this.keys.map(({time:e,position:t,target:n,fov:r,orthoHeight:i})=>({time:e,position:t.toArray(),target:n.toArray(),fov:r,orthoHeight:i}))}restore(e){this.keys=(e??[]).map(e=>({id:this._nextId++,time:e.time,position:new r.Vector3().fromArray(e.position),target:new r.Vector3().fromArray(e.target),fov:e.fov,orthoHeight:e.orthoHeight})),this._changed()}dispose(){this._cameraManager=this._onChange=null}get(e){return this.keys.find(t=>t.id===e)}sample(e,t={position:new r.Vector3,target:new r.Vector3,fov:0,orthoHeight:0}){if(!this.keys.length)return null;let{position:n,target:i,fov:a,logHeight:o,start:s,end:c}=this._interpolants??=this._build(),l=r.MathUtils.clamp(e,s,c);return t.position.fromArray(n.evaluate(l)),t.target.fromArray(i.evaluate(l)),t.fov=a.evaluate(l)[0],t.orthoHeight=Math.exp(o.evaluate(l)[0]),t}_build(){let e=[];for(let t of this.keys)e.push(e.length?Math.max(t.time,e[e.length-1]+rE):t.time);let t=e[0],n=e[e.length-1],i=this.keys;if(i.length>1){let r=i.length;e.unshift(2*t-e[1]),e.push(2*n-e[r-1]),i=[i[1],...i,i[r-2]]}let a=e=>i.flatMap(t=>e(t).toArray());return{start:t,end:n,position:aE(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:aE(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:aE(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:aE(r.NumberKeyframeTrack,`.orthoHeight`,e,i.map(e=>Math.log(e.orthoHeight)))}}_changed(){this.keys.sort((e,t)=>e.time-t.time),this._interpolants=null,this._onChange?.()}};function sE({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}R();var cE=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new oE(e,()=>this._changed(`camera`)),this._playback=null,this._timer=new r.Timer,typeof document<`u`&&this._timer.connect(document)}get duration(){return this.camera.duration}get animates(){return this.camera.animates}seek(e){return this.camera.seek(e)}play(){return this.stop(),new Promise(e=>{let t=this._cameraManager.controls;this._playback={elapsed:0,resolve:e,controlsEnabled:t.enabled},t.enabled=!1,this._timer.reset(),this._changed(),this._onReset?.()})}stop(){let e=this._playback;e&&(this._playback=null,this._cameraManager.controls.enabled=e.controlsEnabled,this._changed(),e.resolve())}get isPlaying(){return!!this._playback}update(){let e=this._playback;if(!e)return;this._timer.update(),e.elapsed+=this._timer.getDelta();let t=r.MathUtils.clamp(e.elapsed,0,this.duration);this.seek(t),t>=this.duration&&this.stop()}serialize(){return{camera:this.camera.serialize()}}restore(e){this.stop(),this.camera.restore(e?.camera)}clear(){this.stop(),this.camera.clear()}dispose(){this.stop(),this._timer.dispose(),this.camera.dispose(),this._cameraManager=this._onReset=null}_changed(e){this.dispatchEvent({type:I.TIMELINE_CHANGED,track:e})}},lE=`__rayzeeUserLight`,uE={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},dE=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[lE]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[lE]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:zr(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=uE[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=Br(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}},fE=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>pE(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0});for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4)}let u=new r.DataArrayTexture(s,i,a,o);u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.format=r.RGBAFormat,u.type=r.UnsignedByteType,u.generateMipmaps=!1,u.needsUpdate=!0;let d=this.texture;return this.texture=u,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=u,this.pathTracer.shaderBuilder?.updateGoboMaps?.(u),d?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Y.ASSET_UNREACHABLE,`no gobo named "${t}" is loaded — the light projects without one`,{name:t,asset:`gobo`}),!1;o.userData.gobo={name:e.name,index:e.index,intensity:mE(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};async function pE(e){let t=await ox(e);try{return await new Promise((n,r)=>{let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>n(i),i.onerror=()=>r(Error(`Failed to load gobo image: ${e}`)),i.src=t.url})}finally{t.release()}}function mE(e){return Math.max(0,Math.min(1,e))}function hE(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
1032
+ `,n);if(r<0)throw Error(`IES (${t}): truncated TILT line`);let i=e.slice(n,r).match(/TILT\s*=\s*(\w+)/i),a=i?i[1].toUpperCase():`NONE`,o=e.slice(r);if(a===`INCLUDE`){let e=yE(o),t=2+2*Number(e[1]);o=bE(o,t)}let s=yE(o),c=0,l=()=>Number(s[c++]),u=l(),d=l(),f=l(),p=l(),m=l(),h=l();l(),l(),l(),l();let g=l();if(l(),l(),!Number.isFinite(p)||p<=0)throw Error(`IES (${t}): invalid vertical angle count ${p}`);if(!Number.isFinite(m)||m<=0)throw Error(`IES (${t}): invalid horizontal angle count ${m}`);let _=Array(p);for(let e=0;e<p;e++)_[e]=l();let v=Array(m);for(let e=0;e<m;e++)v[e]=l();let y=Array(p);for(let e=0;e<p;e++)y[e]=new Float32Array(m);let b=f*g,x=0;for(let e=0;e<m;e++)for(let t=0;t<p;t++){let n=l()*b;y[t][e]=n,n>x&&(x=n)}return{verticalAngles:_,horizontalAngles:v,candela:y,maxCandela:x,lumens:d*u,photometricType:h,name:t}}function gE(e,t,n){let r=new Uint8Array(t*n),{verticalAngles:i,horizontalAngles:a,candela:o,maxCandela:s}=e;if(s<=0)return r;let c=i[i.length-1],l=a[a.length-1],u=a[0],d=a.length===1||l===u;for(let e=0;e<n;e++){let f=(e+.5)/n*c,p=xE(i,f),m=Math.min(p+1,i.length-1),h=i[m]-i[p],g=h>0?(f-i[p])/h:0;for(let n=0;n<t;n++){let i;if(d)i=SE(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=xE(a,e),s=Math.min(r+1,a.length-1),c=a[s]-a[r],d=c>0?(e-a[r])/c:0,f=o[p][r],h=o[p][s],_=o[m][r],v=o[m][s];i=SE(SE(f,h,d),SE(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function _E(e,t=.1){let{verticalAngles:n,horizontalAngles:r,candela:i,maxCandela:a}=e,o=Math.PI/4;if(a<=0||!n?.length)return o;let s=a*t,c=r.length,l=n[n.length-1],u=!1;for(let e=0;e<n.length;e++){let t=0;for(let n=0;n<c;n++)t+=i[e][n];if(t/=c,t>=s&&(u=!0),u&&t<s){l=n[e];break}}let d=l*Math.PI/180;return Math.min(Math.max(d,5*Math.PI/180),89*Math.PI/180)}function vE(e,t,n=.7){let{verticalAngles:r,horizontalAngles:i,candela:a,maxCandela:o}=e;if(o<=0||!r?.length||t<=0)return 0;let s=o*n,c=i.length,l=0;for(let e=0;e<r.length;e++){let t=0;for(let n=0;n<c;n++)t+=a[e][n];if(t/=c,t>=s)l=r[e];else break}let u=t*180/Math.PI,d=u>0?1-l/u:0;return Math.min(Math.max(d,0),1)}function yE(e){return e.split(/\s+/).filter(e=>e.length>0)}function bE(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function xE(e,t){if(t<=e[0])return 0;if(t>=e[e.length-1])return e.length-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function SE(e,t,n){return e+(t-e)*n}var CE=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._gridWidth=128,this._gridHeight=128}async loadLibrary(e,{gridWidth:t=128,gridHeight:n=128}={}){if(!Array.isArray(e)||e.length===0)return[];this._gridWidth=t,this._gridHeight=n;let i=(await Promise.all(e.map(async e=>{try{let{file:r,release:i}=await ax().fetch(e.url),a=hE(await r.text().finally(i),e.name);return{it:e,profile:a,grid:gE(a,t,n)}}catch(t){return this._issues?.warn(Y.ASSET_UNREACHABLE,`IES profile "${e.name}" could not be loaded: ${t.message}`,{url:e.url,asset:`ies`,cause:t.message}),null}}))).filter(e=>e!==null);if(i.length===0)return[];let a=i.length,o=t*n,s=new Uint8Array(o*4*a),c=[];for(let e=0;e<a;e++){let t=i[e].grid,n=e*o*4;for(let e=0;e<o;e++){let r=t[e];s[n+e*4+0]=r,s[n+e*4+1]=r,s[n+e*4+2]=r,s[n+e*4+3]=255}let r=i[e].profile,a=_E(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:vE(r,a),lumens:r.lumens})}let l=new r.DataArrayTexture(s,t,n,a);l.format=r.RGBAFormat,l.type=r.UnsignedByteType,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l.generateMipmaps=!1,l.needsUpdate=!0;let u=this.texture;return this.texture=l,this.entries=c,this.pathTracer.iesProfiles=l,this.pathTracer.shaderBuilder?.updateIESProfiles?.(l),u?.dispose?.(),this.entries.map(({name:e,index:t})=>({name:e,index:t}))}getEntries(){return this.entries.slice()}setSpotLightProfile(e,t,n=1,{applyAutoCone:r=!0}={}){let i=this._findSpotLight(e),a={applied:!1,suggestedAngle:null,suggestedPenumbra:null,suggestedDecay:null,fixtureLumens:null};if(!i)return a;i.userData=i.userData||{};let o=null,s=null,c=null,l=null;if(t==null)delete i.userData.ies;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Y.ASSET_UNREACHABLE,`no IES profile named "${t}" is loaded — the light keeps its plain distribution`,{name:t,asset:`ies`}),a;l=Number.isFinite(e.lumens)?e.lumens:null,i.userData.ies={name:e.name,index:e.index,intensity:wE(n),fixtureLumens:l},r&&(Number.isFinite(e.suggestedAngle)&&(i.angle=e.suggestedAngle,o=e.suggestedAngle),Number.isFinite(e.suggestedPenumbra)&&(i.penumbra=e.suggestedPenumbra,s=e.suggestedPenumbra),i.decay=2,c=2)}return this.pathTracer.updateLights(),this._onReset?.(),{applied:!0,suggestedAngle:o,suggestedPenumbra:s,suggestedDecay:c,fixtureLumens:l}}getSpotLightProfile(e){return this._findSpotLight(e)?.userData?.ies||null}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function wE(e){return Math.max(0,Math.min(1,e))}jt(),Ys();var TE=vt(`oidn`),EE=16,DE=null;async function OE(){return DE||=(await import(`oidn-web/dist/oidn.js`)).initUNetFromBuffer,DE}var kE={QUALITY_MODELS:{fast:{model:`rt_hdr_alb_nrm_small`,cleanAux:!1},"fast-clean":{model:`rt_hdr_calb_cnrm_small`,cleanAux:!0},balance:{model:`rt_hdr_calb_cnrm`,cleanAux:!0},high:{model:`rt_hdr_calb_cnrm_large`,cleanAux:!0}},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,tileSize:1024}},AE=.18,jE=256,ME=256,NE=`
1033
+ const WG: u32 = ${jE}u;
1034
+ const GROUPS: u32 = ${ME}u;
1017
1035
 
1018
1036
  @group(0) @binding(0) var<storage, read> col: array<vec4<f32>>;
1019
1037
  @group(0) @binding(1) var<storage, read_write> partials: array<f32>;
@@ -1032,7 +1050,7 @@ fn treeSum( lid: u32 ) {
1032
1050
  }
1033
1051
  }
1034
1052
 
1035
- @compute @workgroup_size(${kE})
1053
+ @compute @workgroup_size(${jE})
1036
1054
  fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
1037
1055
  @builtin(local_invocation_id) lid: vec3<u32>,
1038
1056
  @builtin(workgroup_id) wid: vec3<u32> ) {
@@ -1055,7 +1073,7 @@ fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
1055
1073
  if ( lid.x == 0u ) { partials[ wid.x ] = sdata[ 0 ]; }
1056
1074
  }
1057
1075
 
1058
- @compute @workgroup_size(${kE})
1076
+ @compute @workgroup_size(${jE})
1059
1077
  fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
1060
1078
 
1061
1079
  var v = 0.0;
@@ -1065,12 +1083,12 @@ fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
1065
1083
  treeSum( lid.x );
1066
1084
 
1067
1085
  if ( lid.x == 0u ) {
1068
- let scale = ${OE} / exp2( sdata[ 0 ] / f32( params.x ) );
1086
+ let scale = ${AE} / exp2( sdata[ 0 ] / f32( params.x ) );
1069
1087
  // Mirrors the CPU guard: a non-finite or non-positive scale means no scaling at all.
1070
1088
  scaleOut[ 0 ] = select( 1.0, scale, scale > 0.0 && scale < 3.4e38 );
1071
1089
  }
1072
1090
  }
1073
- `,ME=`
1091
+ `,PE=`
1074
1092
  @group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;
1075
1093
  @group(0) @binding(1) var<storage, read> scaleBuf: array<f32>;
1076
1094
 
@@ -1082,7 +1100,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32>,
1082
1100
  let c = col[ i ];
1083
1101
  col[ i ] = vec4<f32>( c.xyz * scaleBuf[ 0 ], c.w );
1084
1102
  }
1085
- `,NE=64,PE=32768,FE=16,IE=32,LE=`
1103
+ `,FE=64,IE=32768,LE=16,RE=32,zE=`
1086
1104
  struct UnpackParams {
1087
1105
  srcWidth: u32,
1088
1106
  tileX: u32,
@@ -1100,7 +1118,7 @@ struct UnpackParams {
1100
1118
  @group(0) @binding(3) var<storage, read> inColor: array<vec4<f32>>;
1101
1119
  @group(0) @binding(4) var dst: texture_storage_2d<rgba16float, write>;
1102
1120
 
1103
- @compute @workgroup_size(${FE}, ${FE})
1121
+ @compute @workgroup_size(${LE}, ${LE})
1104
1122
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1105
1123
 
1106
1124
  if ( gid.x >= P.tileW || gid.y >= P.tileH ) { return; }
@@ -1114,7 +1132,18 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1114
1132
  // survives the denoise.
1115
1133
  textureStore( dst, vec2<u32>( px, py ), vec4<f32>( src[ si ].xyz / scaleBuf[ 0 ], inColor[ si ].w ) );
1116
1134
  }
1117
- `,RE=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...DE.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._weights=new Map,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{CE.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=DE;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/wE)*wE;return t<=this.maxTileSize?t:Math.max(wE,Math.floor(this.maxTileSize/wE)*wE)}_setupUNetDenoiser(){return this.state.isLoading?(this._reloadPending=!0,Promise.resolve()):(this._loading=this._loadUNet(),this._loading)}whenLoaded(){return this.state.isLoading?this._loading:Promise.resolve()}async _loadUNet(){do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){CE.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`),url:this._generateTzaUrl()})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.state.isDenoising&&this.state.abortController?.abort(),await new Promise(e=>setTimeout(e,0)),this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await EE())(await this._fetchWeights(e),n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),CE.debug(`UNet weights loaded:`,e)}_fetchWeights(e){let t=this._weights.get(e);return t||(t=ax().fetch(e,{policy:Yb.IMMUTABLE}).then(({file:e,release:t})=>e.arrayBuffer().finally(t)),t.catch(()=>this._weights.delete(e)),this._weights.set(e,t)),t}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Ks(),{QUALITY_MODELS:t}=DE;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(DE.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(DE.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,CE.debug(`denoise complete in ${J.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?CE.debug(`denoise aborted`):CE.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return CE.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures({continuous:e});if(!r?.color)return CE.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return CE.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n);let a=i.createCommandEncoder({label:`oidn-tex-to-buf`}),o=t*16,s=this._gpuInputPaddedRowBytes,c=s>o,l=this._gpuInputPadBuffer,u=(e,r)=>{if(!c)a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:r,offset:0,bytesPerRow:o,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});else{a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:l,offset:0,bytesPerRow:s,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});for(let e=0;e<n;e++)a.copyBufferToBuffer(l,e*s,r,e*o,o)}};u(r.color,this._gpuInputBuffers.color),u(r.albedo,this._gpuInputBuffers.albedo),u(r.normal,this._gpuInputBuffers.normal),i.queue.submit([a.finish()]),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n),!e&&!this._hasOutput&&this._unpackToTexture(this._gpuInputBuffers.color,t,{x:0,y:0,width:t,height:n},!1);let d={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(d,e)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};let s=e*16,c=Math.ceil(s/256)*256;c===s?this._gpuInputPaddedRowBytes=s:(this._gpuInputPadBuffer=i.createBuffer({label:`oidn-in-pad`,size:c*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),this._gpuInputPaddedRowBytes=c)}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:jE}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:ME}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:LE}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:AE*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(AE,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/NE),r=Math.min(n,PE),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}gpuBytes(){let{color:e,albedo:t,normal:n}=this._gpuInputBuffers,r=this._outGPUTexture?this._outTexSize.width*this._outTexSize.height*8:0;return(e?.size??0)+(t?.size??0)+(n?.size??0)+(this._gpuInputPadBuffer?.size??0)+r}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n,r=!0){let i=this.gpuDevice;if(!i||!this._ensureScalePipelines(i))return;let{x:a,y:o,width:s,height:c}=n;if(this._ensureOutputTexture(i,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let l=i.createBuffer({label:`oidn-unpack-params`,size:IE,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{i.queue.writeBuffer(l,0,new Uint32Array([t,a,o,s,c,0,0,0]));let n=i.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),u=i.createCommandEncoder({label:`oidn-output-unpack`}),d=u.beginComputePass({label:`oidn-output-unpack`});d.setPipeline(this._unpackPipeline),d.setBindGroup(0,n),d.dispatchWorkgroups(Math.ceil(s/FE),Math.ceil(c/FE),1),d.end(),i.queue.submit([u.finish()]),r&&(this._hasOutput=!0)}finally{l.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){CE.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,CE.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{CE.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this._weights.clear(),this.state.abortController=null,this.removeAllListeners?.(),CE.debug(`disposed`)}},zE=Object.freeze({maxLength:8,smoothLength:2,roughStart:.45,roughEnd:.7,depthTolerance:.05,normalTolerance:.8,movedLength:2}),BE=8,VE=304,HE=16,UE=1,WE=2,GE=4,KE=1073741824,qE=`
1135
+ `,BE=8,VE=`
1136
+ @group(0) @binding(0) var src: texture_2d<f32>;
1137
+ @group(0) @binding(1) var<storage, read_write> dst: array<vec4<f32>>;
1138
+ @group(0) @binding(2) var<uniform> size: vec2<u32>;
1139
+
1140
+ @compute @workgroup_size(${BE}, ${BE})
1141
+ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1142
+
1143
+ if ( gid.x >= size.x || gid.y >= size.y ) { return; }
1144
+ dst[ gid.y * size.x + gid.x ] = textureLoad( src, gid.xy, 0 );
1145
+ }
1146
+ `,HE=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._packPipeline=null,this._packLayout=null,this._packParams=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...kE.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._weights=new Map,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{TE.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=kE;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/EE)*EE;return t<=this.maxTileSize?t:Math.max(EE,Math.floor(this.maxTileSize/EE)*EE)}_setupUNetDenoiser(){return this.state.isLoading?(this._reloadPending=!0,Promise.resolve()):(this._loading=this._loadUNet(),this._loading)}whenLoaded(){return this.state.isLoading?this._loading:Promise.resolve()}async _loadUNet(){do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){TE.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`),url:this._generateTzaUrl()})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.state.isDenoising&&this.state.abortController?.abort(),await new Promise(e=>setTimeout(e,0)),this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await OE())(await this._fetchWeights(e),n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),TE.debug(`UNet weights loaded:`,e)}_fetchWeights(e){let t=this._weights.get(e);return t||(t=ax().fetch(e,{policy:Yb.IMMUTABLE}).then(({file:e,release:t})=>e.arrayBuffer().finally(t)),t.catch(()=>this._weights.delete(e)),this._weights.set(e,t)),t}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Ks(),{QUALITY_MODELS:t}=kE;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(kE.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(kE.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,TE.debug(`denoise complete in ${J.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?TE.debug(`denoise aborted`):TE.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return TE.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures({continuous:e});if(!r?.color)return TE.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return TE.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n),this._copyInputs(i,r,t,n),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n),!e&&!this._hasOutput&&this._unpackToTexture(this._gpuInputBuffers.color,t,{x:0,y:0,width:t,height:n},!1);let a={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(a,e)}_copyInputs(e,t,n,r){let i=e.createCommandEncoder({label:`oidn-tex-to-buf`}),a=n*16,o=a%256==0?null:this._beginPack(e,i,n,r),s=(t,s)=>{o?(o.setBindGroup(0,e.createBindGroup({layout:this._packLayout,entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:s}},{binding:2,resource:{buffer:this._packParams}}]})),o.dispatchWorkgroups(Math.ceil(n/BE),Math.ceil(r/BE))):i.copyTextureToBuffer({texture:t,mipLevel:0},{buffer:s,offset:0,bytesPerRow:a,rowsPerImage:r},{width:n,height:r,depthOrArrayLayers:1})};s(t.color,this._gpuInputBuffers.color),s(t.albedo,this._gpuInputBuffers.albedo),s(t.normal,this._gpuInputBuffers.normal),o?.end(),e.queue.submit([i.finish()])}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t}}_beginPack(e,t,n,r){this._packPipeline||=(this._packLayout=e.createBindGroupLayout({label:`oidn-pack`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}}]}),e.createComputePipeline({label:`oidn-pack`,layout:e.createPipelineLayout({bindGroupLayouts:[this._packLayout]}),compute:{module:e.createShaderModule({label:`oidn-pack`,code:VE}),entryPoint:`main`}})),this._packParams||(this._packParams=e.createBuffer({label:`oidn-pack-size`,size:8,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._packParams,0,new Uint32Array([n,r])));let i=t.beginComputePass({label:`oidn-pack`});return i.setPipeline(this._packPipeline),i}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._packParams?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._packParams=null,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:NE}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:PE}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:zE}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:ME*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(ME,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/FE),r=Math.min(n,IE),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}gpuBytes(){let{color:e,albedo:t,normal:n}=this._gpuInputBuffers,r=this._outGPUTexture?this._outTexSize.width*this._outTexSize.height*8:0;return(e?.size??0)+(t?.size??0)+(n?.size??0)+r}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n,r=!0){let i=this.gpuDevice;if(!i||!this._ensureScalePipelines(i))return;let{x:a,y:o,width:s,height:c}=n;if(this._ensureOutputTexture(i,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let l=i.createBuffer({label:`oidn-unpack-params`,size:RE,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{i.queue.writeBuffer(l,0,new Uint32Array([t,a,o,s,c,0,0,0]));let n=i.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),u=i.createCommandEncoder({label:`oidn-output-unpack`}),d=u.beginComputePass({label:`oidn-output-unpack`});d.setPipeline(this._unpackPipeline),d.setBindGroup(0,n),d.dispatchWorkgroups(Math.ceil(s/LE),Math.ceil(c/LE),1),d.end(),i.queue.submit([u.finish()]),r&&(this._hasOutput=!0)}finally{l.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){TE.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,TE.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{TE.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this._weights.clear(),this.state.abortController=null,this.removeAllListeners?.(),TE.debug(`disposed`)}},UE=Object.freeze({maxLength:8,smoothLength:2,roughStart:.45,roughEnd:.7,depthTolerance:.05,normalTolerance:.8,movedLength:2}),WE=8,GE=304,KE=16,qE=1,JE=2,YE=4,XE=1073741824,ZE=`
1118
1147
  struct Params {
1119
1148
  size: vec2<u32>,
1120
1149
  reset: u32,
@@ -1149,7 +1178,7 @@ fn mixNormal( h: vec3<f32>, c: vec3<f32>, t: f32 ) -> vec3<f32> {
1149
1178
  let l = length( m );
1150
1179
  return select( c, m / l * 0.5 + 0.5, l > 1e-4 );
1151
1180
  }
1152
- `,JE=qE+`
1181
+ `,QE=ZE+`
1153
1182
  @group(0) @binding(1) var geoCur: texture_2d<f32>;
1154
1183
  @group(0) @binding(2) var geoPrev: texture_2d<f32>;
1155
1184
  @group(0) @binding(3) var<storage, read_write> picked: array<i32>;
@@ -1175,7 +1204,7 @@ fn movedIndex( leaf: u32 ) -> i32 {
1175
1204
 
1176
1205
  }
1177
1206
 
1178
- @compute @workgroup_size(${BE}, ${BE})
1207
+ @compute @workgroup_size(${WE}, ${WE})
1179
1208
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1180
1209
 
1181
1210
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -1190,7 +1219,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1190
1219
  let size = vec2<f32>( P.size );
1191
1220
  let uv = ( vec2<f32>( gid.xy ) + 0.5 ) / size;
1192
1221
  // Depth is along the ray: from the camera, or from its image plane when orthographic.
1193
- let ortho = ( P.flags & ${GE}u ) != 0u;
1222
+ let ortho = ( P.flags & ${YE}u ) != 0u;
1194
1223
  let ndc = vec2<f32>( uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0 );
1195
1224
  var origin = P.camWorld[ 3 ].xyz;
1196
1225
  var dir: vec3<f32>;
@@ -1214,7 +1243,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1214
1243
  let toPrev = movedToPrev[ u32( m ) ];
1215
1244
  wp = ( toPrev * vec4<f32>( wp, 1.0 ) ).xyz;
1216
1245
  n = normalize( ( toPrev * vec4<f32>( n, 0.0 ) ).xyz );
1217
- movedFlag = ${KE};
1246
+ movedFlag = ${XE};
1218
1247
 
1219
1248
  }
1220
1249
 
@@ -1251,7 +1280,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1251
1280
  if ( pick >= 0 ) { atomicAdd( &copies[ u32( pick ) ], 1u ); }
1252
1281
 
1253
1282
  }
1254
- `,YE=qE+`
1283
+ `,$E=ZE+`
1255
1284
  @group(0) @binding(1) var curColor: texture_2d<f32>;
1256
1285
  @group(0) @binding(2) var curAlbedo: texture_2d<f32>;
1257
1286
  @group(0) @binding(3) var curNormal: texture_2d<f32>;
@@ -1265,7 +1294,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1265
1294
  @group(0) @binding(11) var outAlbedo: texture_storage_2d<rgba32float, write>;
1266
1295
  @group(0) @binding(12) var outNormal: texture_storage_2d<rgba32float, write>;
1267
1296
 
1268
- @compute @workgroup_size(${BE}, ${BE})
1297
+ @compute @workgroup_size(${WE}, ${WE})
1269
1298
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1270
1299
 
1271
1300
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -1281,8 +1310,8 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1281
1310
  var ha = ca.xyz;
1282
1311
  var hn = cn.xyz;
1283
1312
  let raw = picked[ gid.y * P.size.x + gid.x ];
1284
- let movedPx = raw >= 0 && ( raw & ${KE} ) != 0;
1285
- let pick = select( raw, raw & ~${KE}, raw >= 0 );
1313
+ let movedPx = raw >= 0 && ( raw & ${XE} ) != 0;
1314
+ let pick = select( raw, raw & ~${XE}, raw >= 0 );
1286
1315
 
1287
1316
  if ( pick >= 0 ) {
1288
1317
 
@@ -1296,7 +1325,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1296
1325
  ha = a.xyz;
1297
1326
  hn = textureLoad( histNormal, q, 0 ).xyz;
1298
1327
  len = a.w;
1299
- if ( ( P.flags & ${WE}u ) != 0u ) { len = len / f32( max( copies[ u32( pick ) ], 1u ) ); }
1328
+ if ( ( P.flags & ${JE}u ) != 0u ) { len = len / f32( max( copies[ u32( pick ) ], 1u ) ); }
1300
1329
 
1301
1330
  }
1302
1331
 
@@ -1310,11 +1339,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1310
1339
 
1311
1340
  textureStore( outColor, p, vec4<f32>( mix( hc, cur.xyz, t ), cur.w ) );
1312
1341
  textureStore( outAlbedo, p, vec4<f32>( mix( ha, ca.xyz, t ), newLen ) );
1313
- let n = select( cn.xyz, mixNormal( hn, cn.xyz, t ), ( P.flags & ${UE}u ) != 0u );
1342
+ let n = select( cn.xyz, mixNormal( hn, cn.xyz, t ), ( P.flags & ${qE}u ) != 0u );
1314
1343
  textureStore( outNormal, p, vec4<f32>( n, cn.w ) );
1315
1344
 
1316
1345
  }
1317
- `,XE=qE+`
1346
+ `,eD=ZE+`
1318
1347
  @group(0) @binding(1) var accColor: texture_2d<f32>;
1319
1348
  @group(0) @binding(2) var accAlbedo: texture_2d<f32>;
1320
1349
  @group(0) @binding(3) var accNormal: texture_2d<f32>;
@@ -1325,7 +1354,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1325
1354
  @group(0) @binding(8) var outAlbedo: texture_storage_2d<rgba32float, write>;
1326
1355
  @group(0) @binding(9) var outNormal: texture_storage_2d<rgba32float, write>;
1327
1356
 
1328
- @compute @workgroup_size(${BE}, ${BE})
1357
+ @compute @workgroup_size(${WE}, ${WE})
1329
1358
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1330
1359
 
1331
1360
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -1359,11 +1388,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1359
1388
  let t = P.samples / max( k + P.samples, 1e-6 );
1360
1389
  textureStore( outColor, p, vec4<f32>( mix( hc, ac.xyz, t ), ac.w ) );
1361
1390
  textureStore( outAlbedo, p, vec4<f32>( mix( ha, aa.xyz, t ), min( k + P.samples, P.maxLength ) ) );
1362
- let n = select( an.xyz, mixNormal( hn, an.xyz, t ), ( P.flags & ${UE}u ) != 0u );
1391
+ let n = select( an.xyz, mixNormal( hn, an.xyz, t ), ( P.flags & ${qE}u ) != 0u );
1363
1392
  textureStore( outNormal, p, vec4<f32>( n, an.w ) );
1364
1393
 
1365
1394
  }
1366
- `,ZE=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),QE=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),$E=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),eD=class{constructor(e){this.device=e,this.settings={...zE,cleanAux:!1,splitCopies:!0},this.valid=!1,this.width=0,this.height=0,this._sets=null,this._current=0,this._picked=null,this._copies=null,this._paramsBuffer=null,this._pipelines=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._movedCount=0,this._paramData=new ArrayBuffer(VE),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._prevViewProj=new Float32Array(16),this._prevCamPos=new Float32Array(4),this._prevCamDir=new Float32Array(4)}get textures(){return this.valid?this._sets[this._current]:null}invalidate(){this.valid=!1}accumulate(e,t,n=null){if(!this._ensure(e.width,e.height))return;this._uploadMoved(n),this._writeParams(t,!this.valid,0,1);let r=this._sets[this._current],i=this._sets[1-this._current],{select:a,blend:o}=this._pipelines,s=this.device.createCommandEncoder({label:`oidn-history`});s.clearBuffer(this._copies),this._dispatch(s,a,[{buffer:this._paramsBuffer},e.geo,e.geoPrev,{buffer:this._picked},{buffer:this._copies},e.leaf,{buffer:this._movedLeaves},{buffer:this._movedToPrev}]),this._dispatch(s,o,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,e.shading,r.color,r.albedo,r.normal,{buffer:this._picked},{buffer:this._copies},i.color,i.albedo,i.normal]),this.device.queue.submit([s.finish()]),this._current=1-this._current,this.valid=!0,this._rememberCamera(t)}merge(e,t,n,{commit:r=!1,keepHistory:i=!0,historyScale:a=1}={}){if(!this._ensure(e.width,e.height))return null;this._writeParams(n,!this.valid||!i,t,a);let o=this._sets[this._current],s=this._sets[1-this._current],c=this.device.createCommandEncoder({label:`oidn-history-merge`});return this._dispatch(c,this._pipelines.merge,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,o.color,o.albedo,o.normal,s.color,s.albedo,s.normal]),this.device.queue.submit([c.finish()]),r&&(this._current=1-this._current,this.valid=!0,this._rememberCamera(n)),s}dispose(){this._releaseTextures(),this._paramsBuffer?.destroy(),this._movedLeaves?.destroy(),this._movedToPrev?.destroy(),this._paramsBuffer=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._pipelines=null}gpuBytes(){return this._sets?this._sets.length*3*this.width*this.height*16+this._picked.size+this._copies.size:0}_ensure(e,t){if(!e||!t)return!1;if(this._ensurePipelines(),this._sets&&this.width===e&&this.height===t)return!0;this._releaseTextures();let n=this.device,r=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,i=i=>n.createTexture({label:i,size:{width:e,height:t},format:`rgba32float`,usage:r});return this._sets=[0,1].map(e=>({color:i(`oidn-history-color-${e}`),albedo:i(`oidn-history-albedo-${e}`),normal:i(`oidn-history-normal-${e}`)})),this._picked=n.createBuffer({label:`oidn-history-picked`,size:e*t*4,usage:GPUBufferUsage.STORAGE}),this._copies=n.createBuffer({label:`oidn-history-copies`,size:e*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t,this._current=0,this.valid=!1,!0}_ensurePipelines(){if(this._pipelines)return;let e=this.device,t=(t,n,r)=>{let i=e.createBindGroupLayout({label:t,entries:r});return{pipeline:e.createComputePipeline({label:t,layout:e.createPipelineLayout({bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t,code:n}),entryPoint:`main`}}),layout:i}},n=$E(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,JE,[n,ZE(1),ZE(2),$E(3,`storage`),$E(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},$E(6,`read-only-storage`),$E(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,YE,[n,...[1,2,3,4,5,6,7].map(ZE),$E(8,`read-only-storage`),$E(9,`read-only-storage`),QE(10),QE(11),QE(12)]),merge:t(`oidn-history-merge`,XE,[n,...[1,2,3,4,5,6].map(ZE),QE(7),QE(8),QE(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:VE,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(HE)}_growMoved(e){this._movedLeaves?.destroy(),this._movedToPrev?.destroy();let t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST;this._movedLeaves=this.device.createBuffer({label:`oidn-history-moved-leaves`,size:e*4,usage:t}),this._movedToPrev=this.device.createBuffer({label:`oidn-history-moved-matrices`,size:e*64,usage:t}),this._movedCapacity=e}_uploadMoved(e){this._movedCount=e?.count??0,this._movedCount&&(this._movedCount>this._movedCapacity&&this._growMoved(Math.max(this._movedCount,this._movedCapacity*2)),this.device.queue.writeBuffer(this._movedLeaves,0,e.leaves,0,this._movedCount),this.device.queue.writeBuffer(this._movedToPrev,0,e.toPrev,0,this._movedCount*16))}_dispatch(e,{pipeline:t,layout:n},r){let i=r.map((e,t)=>({binding:t,resource:e.buffer?e:e.createView()})),a=e.beginComputePass();a.setPipeline(t),a.setBindGroup(0,this.device.createBindGroup({layout:n,entries:i})),a.dispatchWorkgroups(Math.ceil(this.width/BE),Math.ceil(this.height/BE)),a.end()}_writeParams(e,t,n,r){let i=this.settings,a=this._paramU32,o=this._paramF32;a[0]=this.width,a[1]=this.height,a[2]=+!!t,a[3]=(i.cleanAux?UE:0)|(i.splitCopies?WE:0)|(e.orthographic?GE:0),o[4]=i.maxLength,o[5]=i.smoothLength,o[6]=i.depthTolerance,o[7]=i.normalTolerance,o[8]=i.roughStart,o[9]=i.roughEnd,o[10]=n,o[11]=r,o.set(e.world,12),o.set(e.projInv,28),o.set(this._prevViewProj,44),o.set(this._prevCamPos,60),a[64]=this._movedCount,o[68]=i.movedLength,o.set(this._prevCamDir,72),this.device.queue.writeBuffer(this._paramsBuffer,0,this._paramData)}_rememberCamera(e){this._prevViewProj.set(e.viewProj),this._prevCamPos[0]=e.world[12],this._prevCamPos[1]=e.world[13],this._prevCamPos[2]=e.world[14];let t=Math.hypot(e.world[8],e.world[9],e.world[10]);this._prevCamDir[0]=-e.world[8]/t,this._prevCamDir[1]=-e.world[9]/t,this._prevCamDir[2]=-e.world[10]/t}_releaseTextures(){this._sets?.forEach(e=>Object.values(e).forEach(e=>e.destroy())),this._picked?.destroy(),this._copies?.destroy(),this._sets=null,this._picked=null,this._copies=null,this.width=0,this.height=0,this.valid=!1}},tD='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},p=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},E=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:S(t,{copy:!0,transfer:r}))??S(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=S(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=b}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=4&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:1,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},D=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await C(e,_);if(!n||n.v!==1||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new E(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await d(e))}async removeById(e){let t=await o(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of w(e)){let e=await C(r,_);e?.v===1&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null;for(let e of Object.values(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area "${e}" is already defined as ${n.kind}`);return n}let r=new D(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area "${e}"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*.3,v)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===h.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===h.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=t.reduce((e,t)=>e+(t.meta.bytes??0),0),i=e??Math.max(0,r-n);if(i<=0)return 0;let a=await s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.CACHE?{free:i,budget:(await this._cacheEntries()).reduce((e,t)=>e+(t.meta.bytes??0),0)+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===h.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};',nD=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,tD],{type:`text/javascript;charset=utf-8`});function rD(e){let t;try{if(t=nD&&(self.URL||self.webkitURL).createObjectURL(nD),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(tD),{type:`module`,name:e?.name})}}Ys();var iD=e=>ih(e)?(e=>e>1?1:e<0?0:e):(e=>e**+ah),aD={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function oD(){let{upscalerModelBaseUrl:e}=Ks(),t={};for(let n in aD){t[n]={};for(let r in aD[n])t[n][r]=e+aD[n][r]}return t}var sD={get QUALITY_PRESETS(){return oD()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},cD=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||sD.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0}async _ensureSession(){let e=sD.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new rD,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s}=Ks();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:sD.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*a,i*a),t.isHDR&&(this._hdrToneMapFn=nh.get(this.getToneMapping())||nh.get(r.ACESFilmicToneMapping),this._hdrEncode=iD(this.getToneMapping()),this._hdrExposure=sh(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=sD.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,dh(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut);let s=this._hdrEncode;l[d]=s(this._tmOut[0]),l[c+d]=s(this._tmOut[1]),l[2*c+d]=s(this._tmOut[2])}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:n,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=nh.get(this.getToneMapping())||nh.get(r.ACESFilmicToneMapping),l=sh(this.getExposure(),this.getToneMapping()),u=iD(this.getToneMapping()),d=this.getSaturation(),f=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,r=n[t]*l,i=n[t+1]*l,a=n[t+2]*l;d!==1&&(f[0]=r,f[1]=i,f[2]=a,dh(f,d),r=f[0],i=f[1],a=f[2]),c(r,i,a,1,f),s[t]=u(f[0])*255+.5|0,s[t+1]=u(f[1])*255+.5|0,s[t+2]=u(f[2])*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!sD.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0,console.log(`AIUpscaler disposed`)}},lD=b({NeuralSuperRes:()=>wD,SR_MAX_INPUT:()=>bD,SR_SCALE:()=>2,presentRGBA8:()=>_D,readDenoisedHalf:()=>pD,releaseDenoisedReader:()=>fD,renderUpscaled:()=>hD});function uD(){if(xD)return xD;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Ks();return t?(globalThis.__NEURAL_ASSET_BASE__=t,xD=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),xD):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function dD(e,t,n){if(CD&&(CD.device!==e||CD.width!==t||CD.height!==n)&&fD(),CD)return CD;let r=t*n*8;return CD={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:SD}),entryPoint:`main`}})},CD}function fD(){CD?.storage.destroy(),CD?.map.destroy(),CD=null}async function pD(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=dD(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function mD(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(I.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(I.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function hD(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await wD.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.set(`maxSamples`,r);let u=mD(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await pD(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&gD(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function gD(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function _D(e,t,n,r){return gD(e,t,n,r)}var vD,yD,bD,xD,SD,CD,wD,TD=y((()=>{R(),jt(),Ys(),vD=2,yD=vt(`neural`),bD=2048,xD=null,SD=`
1395
+ `,tD=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),nD=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),rD=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),iD=class{constructor(e){this.device=e,this.settings={...UE,cleanAux:!1,splitCopies:!0},this.valid=!1,this.width=0,this.height=0,this._sets=null,this._current=0,this._picked=null,this._copies=null,this._paramsBuffer=null,this._pipelines=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._movedCount=0,this._paramData=new ArrayBuffer(GE),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._prevViewProj=new Float32Array(16),this._prevCamPos=new Float32Array(4),this._prevCamDir=new Float32Array(4)}get textures(){return this.valid?this._sets[this._current]:null}invalidate(){this.valid=!1}accumulate(e,t,n=null){if(!this._ensure(e.width,e.height))return;this._uploadMoved(n),this._writeParams(t,!this.valid,0,1);let r=this._sets[this._current],i=this._sets[1-this._current],{select:a,blend:o}=this._pipelines,s=this.device.createCommandEncoder({label:`oidn-history`});s.clearBuffer(this._copies),this._dispatch(s,a,[{buffer:this._paramsBuffer},e.geo,e.geoPrev,{buffer:this._picked},{buffer:this._copies},e.leaf,{buffer:this._movedLeaves},{buffer:this._movedToPrev}]),this._dispatch(s,o,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,e.shading,r.color,r.albedo,r.normal,{buffer:this._picked},{buffer:this._copies},i.color,i.albedo,i.normal]),this.device.queue.submit([s.finish()]),this._current=1-this._current,this.valid=!0,this._rememberCamera(t)}merge(e,t,n,{commit:r=!1,keepHistory:i=!0,historyScale:a=1}={}){if(!this._ensure(e.width,e.height))return null;this._writeParams(n,!this.valid||!i,t,a);let o=this._sets[this._current],s=this._sets[1-this._current],c=this.device.createCommandEncoder({label:`oidn-history-merge`});return this._dispatch(c,this._pipelines.merge,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,o.color,o.albedo,o.normal,s.color,s.albedo,s.normal]),this.device.queue.submit([c.finish()]),r&&(this._current=1-this._current,this.valid=!0,this._rememberCamera(n)),s}dispose(){this._releaseTextures(),this._paramsBuffer?.destroy(),this._movedLeaves?.destroy(),this._movedToPrev?.destroy(),this._paramsBuffer=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._pipelines=null}gpuBytes(){return this._sets?this._sets.length*3*this.width*this.height*16+this._picked.size+this._copies.size:0}_ensure(e,t){if(!e||!t)return!1;if(this._ensurePipelines(),this._sets&&this.width===e&&this.height===t)return!0;this._releaseTextures();let n=this.device,r=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,i=i=>n.createTexture({label:i,size:{width:e,height:t},format:`rgba32float`,usage:r});return this._sets=[0,1].map(e=>({color:i(`oidn-history-color-${e}`),albedo:i(`oidn-history-albedo-${e}`),normal:i(`oidn-history-normal-${e}`)})),this._picked=n.createBuffer({label:`oidn-history-picked`,size:e*t*4,usage:GPUBufferUsage.STORAGE}),this._copies=n.createBuffer({label:`oidn-history-copies`,size:e*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t,this._current=0,this.valid=!1,!0}_ensurePipelines(){if(this._pipelines)return;let e=this.device,t=(t,n,r)=>{let i=e.createBindGroupLayout({label:t,entries:r});return{pipeline:e.createComputePipeline({label:t,layout:e.createPipelineLayout({bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t,code:n}),entryPoint:`main`}}),layout:i}},n=rD(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,QE,[n,tD(1),tD(2),rD(3,`storage`),rD(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},rD(6,`read-only-storage`),rD(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,$E,[n,...[1,2,3,4,5,6,7].map(tD),rD(8,`read-only-storage`),rD(9,`read-only-storage`),nD(10),nD(11),nD(12)]),merge:t(`oidn-history-merge`,eD,[n,...[1,2,3,4,5,6].map(tD),nD(7),nD(8),nD(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:GE,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(KE)}_growMoved(e){this._movedLeaves?.destroy(),this._movedToPrev?.destroy();let t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST;this._movedLeaves=this.device.createBuffer({label:`oidn-history-moved-leaves`,size:e*4,usage:t}),this._movedToPrev=this.device.createBuffer({label:`oidn-history-moved-matrices`,size:e*64,usage:t}),this._movedCapacity=e}_uploadMoved(e){this._movedCount=e?.count??0,this._movedCount&&(this._movedCount>this._movedCapacity&&this._growMoved(Math.max(this._movedCount,this._movedCapacity*2)),this.device.queue.writeBuffer(this._movedLeaves,0,e.leaves,0,this._movedCount),this.device.queue.writeBuffer(this._movedToPrev,0,e.toPrev,0,this._movedCount*16))}_dispatch(e,{pipeline:t,layout:n},r){let i=r.map((e,t)=>({binding:t,resource:e.buffer?e:e.createView()})),a=e.beginComputePass();a.setPipeline(t),a.setBindGroup(0,this.device.createBindGroup({layout:n,entries:i})),a.dispatchWorkgroups(Math.ceil(this.width/WE),Math.ceil(this.height/WE)),a.end()}_writeParams(e,t,n,r){let i=this.settings,a=this._paramU32,o=this._paramF32;a[0]=this.width,a[1]=this.height,a[2]=+!!t,a[3]=(i.cleanAux?qE:0)|(i.splitCopies?JE:0)|(e.orthographic?YE:0),o[4]=i.maxLength,o[5]=i.smoothLength,o[6]=i.depthTolerance,o[7]=i.normalTolerance,o[8]=i.roughStart,o[9]=i.roughEnd,o[10]=n,o[11]=r,o.set(e.world,12),o.set(e.projInv,28),o.set(this._prevViewProj,44),o.set(this._prevCamPos,60),a[64]=this._movedCount,o[68]=i.movedLength,o.set(this._prevCamDir,72),this.device.queue.writeBuffer(this._paramsBuffer,0,this._paramData)}_rememberCamera(e){this._prevViewProj.set(e.viewProj),this._prevCamPos[0]=e.world[12],this._prevCamPos[1]=e.world[13],this._prevCamPos[2]=e.world[14];let t=Math.hypot(e.world[8],e.world[9],e.world[10]);this._prevCamDir[0]=-e.world[8]/t,this._prevCamDir[1]=-e.world[9]/t,this._prevCamDir[2]=-e.world[10]/t}_releaseTextures(){this._sets?.forEach(e=>Object.values(e).forEach(e=>e.destroy())),this._picked?.destroy(),this._copies?.destroy(),this._sets=null,this._picked=null,this._copies=null,this.width=0,this.height=0,this.valid=!1}},aD='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},p=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},E=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:S(t,{copy:!0,transfer:r}))??S(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=S(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=b}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=4&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:1,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},D=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await C(e,_);if(!n||n.v!==1||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new E(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await d(e))}async removeById(e){let t=await o(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of w(e)){let e=await C(r,_);e?.v===1&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null;for(let e of Object.values(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area "${e}" is already defined as ${n.kind}`);return n}let r=new D(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area "${e}"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*.3,v)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===h.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===h.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=t.reduce((e,t)=>e+(t.meta.bytes??0),0),i=e??Math.max(0,r-n);if(i<=0)return 0;let a=await s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.CACHE?{free:i,budget:(await this._cacheEntries()).reduce((e,t)=>e+(t.meta.bytes??0),0)+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===h.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};',oD=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,aD],{type:`text/javascript;charset=utf-8`});function sD(e){let t;try{if(t=oD&&(self.URL||self.webkitURL).createObjectURL(oD),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(aD),{type:`module`,name:e?.name})}}Ys();var cD={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function lD(){let{upscalerModelBaseUrl:e}=Ks(),t={};for(let n in cD){t[n]={};for(let r in cD[n])t[n][r]=e+cD[n][r]}return t}var uD={get QUALITY_PRESETS(){return lD()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},dD=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||uD.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._toneMapper=null}async _ensureSession(){let e=uD.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new sD,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s}=Ks();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:uD.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:r}=t,i=this.scaleFactor,a=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*i,r*i);let o=uD.TILE_OVERLAP,s=this.tileSize,c=s-o*2,l=Math.ceil(n/c),u=Math.ceil(r/c),d=l*u,f=0;for(let o=0;o<u;o++)for(let u=0;u<l;u++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let l=Math.min(u*c,Math.max(0,n-s)),p=Math.min(o*c,Math.max(0,r-s)),m=Math.min(s,n-l),h=Math.min(s,r-p),g=this._extractTile(t,l,p,m,h),_=await this._inferTile(g,m,h),v=l*i,y=p*i,b=m*i,x=h*i,S=this._tensorToImageData(_,b,x,v,y);a.putImageData(S,v,y),f++,this.dispatchEvent({type:`progress`,progress:f/d,tile:{x:u,y:o,total:d,completed:f}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*i,imageHeight:r*i})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=e.color,{width:n,height:i}=t;this._toneMapper??=new yx(this.renderer.backend.device,`aiupscaler-tonemap`,{input:`texture`,output:`planar`}),this._toneMapper.ensureSize(n,i);let a=await this._toneMapper.toPlanar(t,{exposure:this.getExposure(),toneMapping:this.getToneMapping()??r.ACESFilmicToneMapping,saturation:this.getSaturation()});return this._toneMapper.release(),{planes:a,width:n,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{width:a}=e,o=r*i,s=new Float32Array(3*o);if(e.isHDR){let{planes:c}=e,l=a*e.height;for(let e=0;e<3;e++)for(let u=0;u<i;u++){let i=e*l+(n+u)*a+t;s.set(c.subarray(i,i+r),e*o+u*r)}return s}let{data:c}=e;for(let e=0;e<i;e++)for(let i=0;i<r;i++){let l=((n+e)*a+(t+i))*4,u=e*r+i;s[u]=c[l]/255,s[o+u]=c[l+1]/255,s[2*o+u]=c[l+2]/255}return s}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{width:r,height:i}=e,a=r*i,o=e.isHDR,s=o?e.planes.subarray(3*a):e.data,c=o?1:4,l=o?0:3,u=o?1:255,d=!1;for(let e=l;e<s.length;e+=c)if(s[e]<u){d=!0;break}if(!d){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let f=document.createElement(`canvas`);f.width=r,f.height=i;let p=f.getContext(`2d`),m=p.createImageData(r,i);for(let e=0;e<a;e++){let t=o?Math.min(Math.max(s[e]*255,0),255)|0:s[e*4+3];m.data[e*4]=t,m.data[e*4+1]=t,m.data[e*4+2]=t,m.data[e*4+3]=255}p.putImageData(m,0,0);let h=document.createElement(`canvas`);h.width=t,h.height=n;let g=h.getContext(`2d`);g.imageSmoothingEnabled=!0,g.imageSmoothingQuality=`high`,g.drawImage(f,0,0,t,n);let _=g.getImageData(0,0,t,n).data,v=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)v[e]=_[e*4];this._upscaledAlpha=v,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{planes:n,width:r,height:i}=e,a=r*i,o=t.createImageData(r,i),s=o.data;for(let e=0;e<a;e++){let t=e*4;s[t]=n[e]*255+.5|0,s[t+1]=n[a+e]*255+.5|0,s[t+2]=n[2*a+e]*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!uD.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._toneMapper?.dispose(),this._toneMapper=null,console.log(`AIUpscaler disposed`)}},fD=b({NeuralSuperRes:()=>DD,SR_MAX_INPUT:()=>CD,SR_SCALE:()=>2,presentRGBA8:()=>bD,readDenoisedHalf:()=>gD,releaseDenoisedReader:()=>hD,renderUpscaled:()=>vD});function pD(){if(wD)return wD;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Ks();return t?(globalThis.__NEURAL_ASSET_BASE__=t,wD=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),wD):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function mD(e,t,n){if(ED&&(ED.device!==e||ED.width!==t||ED.height!==n)&&hD(),ED)return ED;let r=t*n*8;return ED={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:TD}),entryPoint:`main`}})},ED}function hD(){ED?.storage.destroy(),ED?.map.destroy(),ED=null}async function gD(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=mD(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function _D(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(I.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(I.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function vD(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await DD.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.set(`maxSamples`,r);let u=_D(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await gD(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&yD(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function yD(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function bD(e,t,n,r){return yD(e,t,n,r)}var xD,SD,CD,wD,TD,ED,DD,OD=y((()=>{R(),jt(),bx(),Ys(),xD=2,SD=vt(`neural`),CD=2048,wD=null,TD=`
1367
1396
  @group(0) @binding(0) var src: texture_2d<f32>;
1368
1397
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1369
1398
 
@@ -1376,7 +1405,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1376
1405
  dst[ a ] = pack2x16float( c.rg );
1377
1406
  dst[ a + 1u ] = pack2x16float( vec2<f32>( c.b, 1.0 ) );
1378
1407
  }
1379
- `,CD=null,wD=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralSuperRes.create: width and height must be positive integers`);if(t>2048||n>2048)throw Error(`NeuralSuperRes.create: input capped at ${bD}px per side (${bD*2}px output), got ${t}x${n}. Above that the runtime's history plane exceeds maxTextureDimension2D and it fails later with an unrelated bind-group error.`);let i=await uD(),a=document.createElement(`canvas`);a.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`,document.body.appendChild(a);let o;try{o=await i.create(a,{width:t,height:n,onProgress:r,timestamps:!0,nrSettings:null})}catch(e){throw a.remove(),e}let s=new e(o,a);return s._allocate(),s}_allocate(){let e=this.inputWidth,t=this.inputHeight;this._color=new Uint16Array(e*t*4),this._depth=new Float32Array(e*t),this._motion=new Uint16Array(e*t*2)}async _run(e){if(this.disposed)throw Error(`NeuralSuperRes: disposed`);let t=this.inputWidth,n=this.inputHeight;if(e.width!==t||e.height!==n)throw Error(`NeuralSuperRes: expected a ${t}x${n} source, got ${e.width}x${e.height}`);let r=this._color;if(!e.half||e.half.length!==r.length)throw Error(`NeuralSuperRes: expected ${r.length} packed halfs from readDenoisedHalf, got ${e.half?.length}`);r.set(e.half),this._depth.fill(.5),this._motion.fill(0);let i=performance.now(),a=await this.sr.render(this.slot,{color:r,depth:this._depth,motion:this._motion,reset:!0,jitter:[0,0]});return await this.sr.device.queue.onSubmittedWorkDone(),{result:a,ms:performance.now()-i}}async upscaleToRGBA8(e,t={}){let{result:n,ms:r}=await this._run(e),{outputWidth:i,outputHeight:a}=this.geometry;this._toneMapper??=new _x(this.sr.device,`rayzee:neural-sr-tonemap`),this._toneMapper.ensureSize(i,a);let o=performance.now();return{rgba8:await this._toneMapper.toRGBA8(n.hdr.buffer??n.hdr,{exposure:t.exposure??1,toneMapping:t.toneMapping??0,saturation:t.saturation??1,flipY:!0}),width:i,height:a,ms:r,toneMs:performance.now()-o}}dispose(){if(!this.disposed){this.disposed=!0,this._toneMapper?.dispose(),this._toneMapper=null,this.canvas.remove();try{this.sr.destroy()}catch(e){yD.warn(`super resolution teardown:`,e)}}}}})),ED=b({NeuralRetouch:()=>LD,RETOUCH_COLOR_STRENGTH:()=>0,RETOUCH_DEFAULTS:()=>AD,RETOUCH_MAX_PIXELS:()=>MD,RETOUCH_RANGES:()=>ND,enhanceFrame:()=>kD});function DD(e={}){let{colorStrength:t=0,...n}=e;return{runtime:{...AD,...n},colorStrength:t}}function OD(){if(PD)return PD;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Ks();return t?(globalThis.__NEURAL_ASSET_BASE__=t,PD=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getSrNrChain)return t(globalThis.NeuralRuntime.getSrNrChain());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getSrNrChain;if(!e)return n(Error(`Neural runtime loaded but exposed no retouch entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),PD):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}async function kD({source:e,settings:t={},instance:n=null,exposure:r=1,tone:i=null,onProgress:a=()=>{}}){let o=n;o&&(o.width!==e.width||o.height!==e.height)&&(o.dispose(),o=null),o||=await LD.create({width:e.width,height:e.height,settings:t,onProgress:a});let{runtime:s,colorStrength:c}=DD(t),l=o.staging;if(!e.half||e.half.length!==l.length)throw Error(`NeuralRetouch: expected ${l.length} packed halfs, got ${e.half?.length}`);l.set(e.half),o.device.queue.writeBuffer(o.source,0,l),o.chain.pipeline.paperWhite=1/Math.min(Math.max(r,1/RD),RD),o.chain.pipeline.colorStrength=c;let u=performance.now(),d=o.device.createCommandEncoder({label:`rayzee:retouch`});await o.chain.encode(d,o.slot,{buffer:o.source},s,()=>{},{reset:!0}),o.device.queue.submit([d.finish()]),await o.device.queue.onSubmittedWorkDone();let f=i?await o.readOutputToned(i):await o.readOutputHDR();return{instance:o,...f,ms:performance.now()-u}}var AD,jD,MD,ND,PD,FD,ID,LD,RD,zD=y((()=>{vx(),jt(),Ys(),AD=Object.freeze({enabled:!0,intensity:1,localTone:1,localStructure:1,skinStructure:-1,autoMask:!0,style:0,preset:0,uiCorrection:!1}),jD=vt(`neural`),MD=2048*2048,ND=Object.freeze({intensity:[0,1],localTone:[0,2],localStructure:[0,2],skinStructure:[-1,2],style:[0,2],preset:[0,3]}),PD=null,FD=`
1408
+ `,ED=null,DD=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralSuperRes.create: width and height must be positive integers`);if(t>2048||n>2048)throw Error(`NeuralSuperRes.create: input capped at ${CD}px per side (${CD*2}px output), got ${t}x${n}. Above that the runtime's history plane exceeds maxTextureDimension2D and it fails later with an unrelated bind-group error.`);let i=await pD(),a=document.createElement(`canvas`);a.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`,document.body.appendChild(a);let o;try{o=await i.create(a,{width:t,height:n,onProgress:r,timestamps:!0,nrSettings:null})}catch(e){throw a.remove(),e}let s=new e(o,a);return s._allocate(),s}_allocate(){let e=this.inputWidth,t=this.inputHeight;this._color=new Uint16Array(e*t*4),this._depth=new Float32Array(e*t),this._motion=new Uint16Array(e*t*2)}async _run(e){if(this.disposed)throw Error(`NeuralSuperRes: disposed`);let t=this.inputWidth,n=this.inputHeight;if(e.width!==t||e.height!==n)throw Error(`NeuralSuperRes: expected a ${t}x${n} source, got ${e.width}x${e.height}`);let r=this._color;if(!e.half||e.half.length!==r.length)throw Error(`NeuralSuperRes: expected ${r.length} packed halfs from readDenoisedHalf, got ${e.half?.length}`);r.set(e.half),this._depth.fill(.5),this._motion.fill(0);let i=performance.now(),a=await this.sr.render(this.slot,{color:r,depth:this._depth,motion:this._motion,reset:!0,jitter:[0,0]});return await this.sr.device.queue.onSubmittedWorkDone(),{result:a,ms:performance.now()-i}}async upscaleToRGBA8(e,t={}){let{result:n,ms:r}=await this._run(e),{outputWidth:i,outputHeight:a}=this.geometry;this._toneMapper??=new yx(this.sr.device,`rayzee:neural-sr-tonemap`),this._toneMapper.ensureSize(i,a);let o=performance.now();return{rgba8:await this._toneMapper.toRGBA8(n.hdr.buffer??n.hdr,{exposure:t.exposure??1,toneMapping:t.toneMapping??0,saturation:t.saturation??1,flipY:!0}),width:i,height:a,ms:r,toneMs:performance.now()-o}}dispose(){if(!this.disposed){this.disposed=!0,this._toneMapper?.dispose(),this._toneMapper=null,this.canvas.remove();try{this.sr.destroy()}catch(e){SD.warn(`super resolution teardown:`,e)}}}}})),kD=b({NeuralRetouch:()=>BD,RETOUCH_COLOR_STRENGTH:()=>0,RETOUCH_DEFAULTS:()=>ND,RETOUCH_MAX_PIXELS:()=>FD,RETOUCH_RANGES:()=>ID,enhanceFrame:()=>MD});function AD(e={}){let{colorStrength:t=0,...n}=e;return{runtime:{...ND,...n},colorStrength:t}}function jD(){if(LD)return LD;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Ks();return t?(globalThis.__NEURAL_ASSET_BASE__=t,LD=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getSrNrChain)return t(globalThis.NeuralRuntime.getSrNrChain());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getSrNrChain;if(!e)return n(Error(`Neural runtime loaded but exposed no retouch entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),LD):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}async function MD({source:e,settings:t={},instance:n=null,exposure:r=1,tone:i=null,onProgress:a=()=>{}}){let o=n;o&&(o.width!==e.width||o.height!==e.height)&&(o.dispose(),o=null),o||=await BD.create({width:e.width,height:e.height,settings:t,onProgress:a});let{runtime:s,colorStrength:c}=AD(t),l=o.staging;if(!e.half||e.half.length!==l.length)throw Error(`NeuralRetouch: expected ${l.length} packed halfs, got ${e.half?.length}`);l.set(e.half),o.device.queue.writeBuffer(o.source,0,l),o.chain.pipeline.paperWhite=1/Math.min(Math.max(r,1/VD),VD),o.chain.pipeline.colorStrength=c;let u=performance.now(),d=o.device.createCommandEncoder({label:`rayzee:retouch`});await o.chain.encode(d,o.slot,{buffer:o.source},s,()=>{},{reset:!0}),o.device.queue.submit([d.finish()]),await o.device.queue.onSubmittedWorkDone();let f=i?await o.readOutputToned(i):await o.readOutputHDR();return{instance:o,...f,ms:performance.now()-u}}var ND,PD,FD,ID,LD,RD,zD,BD,VD,HD=y((()=>{bx(),jt(),Ys(),ND=Object.freeze({enabled:!0,intensity:1,localTone:1,localStructure:1,skinStructure:-1,autoMask:!0,style:0,preset:0,uiCorrection:!1}),PD=vt(`neural`),FD=2048*2048,ID=Object.freeze({intensity:[0,1],localTone:[0,2],localStructure:[0,2],skinStructure:[-1,2],style:[0,2],preset:[0,3]}),LD=null,RD=`
1380
1409
  @group(0) @binding(0) var src: texture_2d<f32>;
1381
1410
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1382
1411
 
@@ -1390,7 +1419,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1390
1419
  let b = u32(clamp(c.b, 0.0, 1.0) * 255.0 + 0.5);
1391
1420
  dst[gid.y * size.x + gid.x] = r | (g << 8u) | (b << 16u) | (255u << 24u);
1392
1421
  }
1393
- `,ID=`
1422
+ `,zD=`
1394
1423
  @group(0) @binding(0) var src: texture_2d<f32>;
1395
1424
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1396
1425
 
@@ -1403,4 +1432,4 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1403
1432
  dst[a] = pack2x16float(c.rg);
1404
1433
  dst[a + 1u] = pack2x16float(vec2<f32>(c.b, 1.0));
1405
1434
  }
1406
- `,LD=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(MD/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await OD()).create(o,t,n,a,DD(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:FD}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:ID}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new _x(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){jD.warn(`retouch teardown:`,e)}}}},RD=20}));R(),jt();var BD=vt(`neural`),VD=120,HD=2,UD=1,WD=0,GD=300,KD=5,qD=3,JD=3,YD=16,XD=e=>Math.max(0,1-e/YD),ZD=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:i,getExposure:a,getSaturation:o,issues:s=null}){super(),this.renderer=e,this._issues=s,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=i,this._stages=n,this._getExposure=a,this._getSaturation=o,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._finalQuality=V.oidnQuality,this.finalDenoise=V.enableOIDN,this.continuousDenoise=V.continuousDenoise,this.continuousDenoiseInterval=V.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.temporalHistory=V.oidnTemporalHistory,this._history=null,this._historyDirty=!0,this._knownResetCount=0,this._seenTracedFrames=0,this._viewProj=new r.Matrix4,this._historyCamera={world:null,projInv:null,viewProj:null,orthographic:!1},this._movedPlacements=new Map,this._movedUpload={count:0,leaves:new Uint32Array,toPrev:new Float32Array},this._matA=new r.Matrix4,this._matB=new r.Matrix4,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}gpuBytes(){return(this.denoiser?.gpuBytes?.()??0)+(this._history?.gpuBytes?.()??0)}_recordNoOverlayCanvas(e){this._issues?.record(Y.DENOISER_UNAVAILABLE,`the ${e} pass needs the render canvas to be in a document, and it is not — skipped`,{pass:e})}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this._historyDirty=!0,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t),this._syncGBufferStages()}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){let e=this._stages.pathTracer;this.denoiser=new RE(this.renderer,{...V,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:({continuous:t=!1}={})=>{if(!e?.storageTextures?.readTarget)return null;let n=t?this._historyTextures():null;if(n)return n;let r=e.storageTextures.getReadTextures(),{backend:i}=this.renderer;return{color:i.get(r.color).texture,normal:i.get(r.normalDepth).texture,albedo:i.get(r.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:I.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:I.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this._denoiserErrorHandler=e=>e.url&&this._issues?.record(Y.ASSET_UNREACHABLE,`denoiser weights "${e.url}" could not be loaded — the render is not denoised`,{url:e.url,asset:`oidn-weights`,cause:String(e.error?.message??e.error)}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.addEventListener(`error`,this._denoiserErrorHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new cD(this.upscalerCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=V.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:I.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:I.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:I.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);this.historyWanted||this._releaseHistory(),t&&(i&&!t.enabled&&t.reset(),t.enabled=i,t.setInstanceLeafOutput?.(this.historyWanted)),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>GD*qD&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=GD);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<JD||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?WD:this._lastCadenceSamples===0?UD:HD,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>VD&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>KD&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._historyDirty=!0,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setTemporalHistory(e){this.temporalHistory=!!e,this._syncGBufferStages()}get historyWanted(){return this.temporalHistory&&this.continuousDenoise&&!!this.denoiser?.enabled&&!this._movingHopeless}get historyActive(){let e=this._stages.pathTracer;return this.historyWanted&&!this._cadenceSuspended&&!!this._stages.normalDepth?.enabled&&e?.uniforms?.get(`cameraProjection`)?.value!==Se.equirectangular&&!(e?.visMode?.value>0)}beforeReset({keepHistory:e=!1}={}){let t=this._stages.pathTracer;if(!t||!this.historyActive)return;let n=t.resetCount!==this._knownResetCount;if(!e||n&&t.frameCount<2){this._historyDirty=!0;return}if(t.frameCount<2)return;let r=this._historyInputs();r&&(this._ensureHistory().merge(r,t.frameCount,this._historyCameraNow(),{commit:!0,keepHistory:!this._historyDirty&&!n,historyScale:XD(t.frameCount)}),this._historyDirty=!1)}afterReset(){this._knownResetCount=this._stages.pathTracer?.resetCount??0}afterTrace(){let e=this._stages.pathTracer;if(!e||e.tracedFrames===this._seenTracedFrames)return;if(this._seenTracedFrames=e.tracedFrames,e.resetCount!==this._knownResetCount&&(this._historyDirty=!0,this._knownResetCount=e.resetCount),!this.historyActive||e.frame.value!==0){this._movedPlacements.clear();return}let t=this._historyInputs();if(!t){this._movedPlacements.clear(),this._historyDirty=!0;return}let n=this._ensureHistory();this._historyDirty&&n.invalidate(),n.accumulate(t,this._historyCameraNow(),this._takeMovedPlacements()),this._historyDirty=!1}notePlacementMoving(e,t,n){e<0||!this.historyActive||this._movedPlacements.has(e)||this._movedPlacements.set(e,{world:t,offset:n,prev:t.slice(n,n+16)})}_takeMovedPlacements(){let e=this._movedPlacements,t=this._movedUpload;if(t.count=e.size,!e.size)return t;t.leaves.length<e.size&&(t.leaves=new Uint32Array(e.size*2),t.toPrev=new Float32Array(e.size*32));let n=[...e.keys()].sort((e,t)=>e-t);for(let r=0;r<n.length;r++){let{world:i,offset:a,prev:o}=e.get(n[r]);this._matB.fromArray(i,a).invert(),this._matA.fromArray(o).multiply(this._matB).toArray(t.toPrev,r*16),t.leaves[r]=n[r]}return e.clear(),t}_historyTextures(){let e=this._stages.pathTracer,t=this._history;if(!t?.valid||this._historyDirty||!this.historyActive||e.isComplete||e.resetCount!==this._knownResetCount||t.width!==this._lastRenderWidth||t.height!==this._lastRenderHeight)return null;if(e.frameCount<=1)return t.textures;if(e.frameCount>=YD)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:XD(e.frameCount)}):null}_historyInputs(){let e=this._stages.pathTracer,t=this.pipeline?.context,n=this.renderer?.backend;if(!e?.storageTextures?.readTarget||!t||!n)return null;let r=e.storageTextures.getReadTextures(),i=e=>e?n.get(e)?.texture:null,a={color:i(r.color),albedo:i(r.albedo),normal:i(r.normalDepth),geo:i(t.getTexture(`pathtracer:normalDepth`)),geoPrev:i(t.getTexture(`pathtracer:prevNormalDepth`)),shading:i(t.getTexture(`pathtracer:shadingNormal`)),leaf:i(t.getTexture(`pathtracer:instanceLeaf`)),width:e.width,height:e.height};return a.color&&a.albedo&&a.normal&&a.geo&&a.geoPrev&&a.shading&&a.leaf?a:null}_historyCameraNow(){let e=this._stages.pathTracer;this._viewProj.multiplyMatrices(e.cameraProjectionMatrix.value,e.cameraViewMatrix.value);let t=this._historyCamera;return t.world=e.cameraWorldMatrix.value.elements,t.projInv=e.cameraProjectionMatrixInverse.value.elements,t.viewProj=this._viewProj.elements,t.orthographic=e.uniforms?.get(`cameraProjection`)?.value===Se.orthographic,t}_ensureHistory(){return this._history??=new eD(this.renderer.backend.device),this._history.settings.cleanAux=!!this.denoiser?.expectsCleanAux(this._finalQuality),this._history}_releaseHistory(){this._history?.dispose(),this._history=null,this._historyDirty=!0,this._movedPlacements.clear()}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){this._recordNoOverlayCanvas(`neural`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){BD.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:I.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(TD(),lD));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(zD(),ED)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(BD.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:u.width,height:u.height})}catch(e){BD.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:I.UPSCALING_END})}}}async denoiseOnce(){let e=this.denoiser;if(!e?.enabled)return!1;for(this._cleanupCompletionListener(),this._resetCadence(),this._useFinalQuality();e.state.isLoading||e.state.isDenoising;)await(e.state.isLoading?e.whenLoaded():new Promise(t=>{let n=()=>{e.removeEventListener(`end`,n),t()};e.addEventListener(`end`,n)}));let t=await e.start();return t&&this._onDisplayRefresh?.(),t&&e.hasOutput}onRenderComplete({isStillComplete:e}){this._cleanupCompletionListener();let t=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,n=()=>{if(this.denoiser?.removeEventListener(`end`,n),this._pendingStartUpscaler=null,e()){if(t&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!t){n();return}let r=()=>{e()&&(this._pendingStartUpscaler=n,this.denoiser.addEventListener(`end`,n),t===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),r()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else r()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay(),this._historyDirty=!0}dispose(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this._denoiserErrorHandler&&this.denoiser.removeEventListener(`error`,this._denoiserErrorHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._issues=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler?this.upscaler.enabled=e:e&&this._recordNoOverlayCanvas(`upscaler`),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=je[e];if(!t)return;let n={};for(let e of Ae)n[e]=ke[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=Oe[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},QD=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},$D=class{constructor(e,t){this.layer=`scene`,this._enabled=!0,this._scene=e,this._camera=t,this._build([])}_build(e){this._orthographic=this._camera.isOrthographicCamera===!0,this._outlineNode=(0,g.outline)(this._scene,this._camera,{selectedObjects:e,edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let i=(0,n.uniform)(3),a=(0,n.uniform)(new r.Color(16777215)),o=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:s,hiddenEdge:c}=this._outlineNode,l=s.mul(a).add(c.mul(o)).mul(i),u=l.r.max(l.g).max(l.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(l,u),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;if(this._camera.isOrthographicCamera!==this._orthographic){let e=[...this._outlineNode.selectedObjects];this._outlineNode.dispose(),this._material.dispose(),this._build(e)}let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function eO(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function tO(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var nO=4096,rO=class{constructor(){this.canvas=eO(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=tO(this._sizeSource,nO);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){se(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};jt(),R();var iO=vt(`overlay`),aO=(e,t)=>e.visible&&e.layer===t&&e.render,oO=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=eO(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new rO().init({device:e,sizeSource:t})}catch(e){iO.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}gpuResources(){let e=this._viewOverlay;return e?.isVisible?[{bytes:e.canvas.width*e.canvas.height*4},...e.renderer?._frameBufferTargets?.values()??[]]:[]}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new QD;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(I.RESOLUTION_CHANGED,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new $D(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(iO.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())aO(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(aO(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(aO(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?tO(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())aO(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};R();var sO=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this.wakeCallback=null,this.applyPoseCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this._rigid=!n.some(e=>e?.isSkinnedMesh)&&!i.some(e=>e.tracks.some(e=>e.name.includes(`morphTargetInfluences`))),this._planClips(i),this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles, ${this._rigid?`rigid`:`deforming`}`)}_planClips(e){let t=this._mixerRoot,n=new Map;if(t.traverse?.(e=>{n.has(e.name)||n.set(e.name,e),n.set(e.uuid,e)}),this._plans=e.map(e=>{let t=new Set,i=!1;for(let a of e.tracks){let{nodeName:e,propertyName:o}=r.PropertyBinding.parseTrackName(a.name),s=n.get(e);s&&(t.add(s),o===`visible`&&(i=!0))}let a=[];for(let e=0;e<this._meshes.length;e++)for(let n=this._meshes[e];n;n=n.parent)if(t.has(n)){a.push(e);break}let o=new Set;for(let e of t)e.traverse(e=>e.isCamera&&o.add(e));return{meshes:Int32Array.from(a),visibility:i,cameras:[...o]}}),this._allPlan=null,!this._rigid)return;this._slotOf=new Int32Array(this._meshes.length).fill(-1);let i=0;for(let e of this._plans)for(let t of e.meshes)this._slotOf[t]<0&&(this._slotOf[t]=i++);this._lastWorld=new Float64Array(i*16).fill(NaN),this._lastVisible=new Uint8Array(i).fill(2)}_planFor(e){if(!this._plans)return null;if(e>=0)return this._plans[e]??null;if(!this._allPlan){let e=new Set,t=new Set,n=!1;for(let r of this._plans)r.meshes.forEach(t=>e.add(t)),r.cameras.forEach(e=>t.add(e)),n||=r.visibility;this._allPlan={meshes:Int32Array.from(e),visibility:n,cameras:[...t]}}return this._allPlan}_applyRigidPose(e){let t=this._planFor(e);if(!t)return;let n=[],r=!1,i=this._lastWorld,a=this._lastVisible;for(let e of t.meshes){let o=this._meshes[e],s=this._slotOf[e],c=o.matrixWorld.elements,l=s*16;for(let t=0;t<16;t++)if(i[l+t]!==c[t]){for(let e=0;e<16;e++)i[l+e]=c[e];n.push(e);break}if(t.visibility||a[s]===2){let e=1;for(let t=o;t;t=t.parent)if(!t.visible){e=0;break}a[s]!==e&&(a[s]=e,r=!0)}}(n.length||r||t.cameras.length)&&this.applyPoseCallback?.({meshIndices:n,visibilityChanged:r,cameras:t.cameras})}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this._activeClip=e,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:I.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:I.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:I.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this._rigid&&(this._mixerRoot.updateMatrixWorld(!0),this._applyRigidPose(-1)),this.dispatchEvent({type:I.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this._activeClip=t,this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){if(this._mixerRoot.updateMatrixWorld(!0),this._rigid)return this._applyRigidPose(this._activeClip),null;let e=this._planFor(this._activeClip)?.cameras;return e?.length&&this.applyPoseCallback?.({meshIndices:[],visibilityChanged:!1,cameras:e}),e=>this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null}};R();var cO=new r.Vector3(0,0,-1),lO=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},uO=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._moved=new Set,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e;for(let e of this._moved)lO(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>lO(e))}noteMoved(e){e&&!e.isLight&&this._moved.add(e)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target&&(this._syncLightAim(e),this._lastLightPosition=e.position.clone()))}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:I.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:I.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:I.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition&&!e.isDirectionalLight){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isDirectionalLight&&e.target&&this._controls.mode===`translate`&&this._syncLightAim(e),e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_syncLightAim(e){let t=this._tempForward.copy(e.target.position).sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(cO,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e),this._moved.add(this._attached)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._moved.clear(),this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},dO=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}},fO=1,pO=e=>typeof e==`string`&&/^https?:\/\//.test(e);function mO(e,t){let n=[];for(;e&&e!==t;){let t=e.parent;if(!t)return null;n.unshift(t.children.indexOf(e)),e=t}return e===t?n:null}function hO(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function gO(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function _O(e){let t=new Map;for(let n of e.sceneMeshes){let e=n.userData?.materialIndex;e!==void 0&&!t.has(e)&&t.set(e,Array.isArray(n.material)?n.material[0]:n.material)}return t}function vO(e){if(!e)return null;let t=e.status(),n=t.activeView,r=t.config?.id??n?.configId??null;return{config:r?{id:r}:null,view:n?{display:n.display,view:n.view,look:n.look??null}:null,transform:n?null:t.activeTransform?.id??null,workingSpace:t.workingSpaceAdopted?t.workingSpace:null,context:t.context??null}}function yO(e){let t=e.meshScene,n=_O(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(mO(e,t))}),{v:1,engine:Zh,savedAt:Date.now(),scene:gO(e),appended:t.children.filter(t=>t!==e.sceneModel&&t.userData?.__rayzeeSceneObject).map(e=>({name:e.userData.__rayzeeName??e.name,url:e.userData.__rayzeeSourceUrl??null,cacheKey:e.userData.__rayzeeCacheKey??null})),settings:e.settings.serialize(),environment:e.environmentManager?.serialize()??null,color:vO(e.color),lights:e.lightManager.serialize(),cameras:e.cameraManager.serialize(),timeline:e.timeline?.serialize()??null,materials:(e.stages.pathTracer?.materialData.serializeHostEdits()??[]).map(e=>({...e,name:n.get(e.index)?.name??``})),hidden:r,moved:(e.transformManager?.movedObjects??[]).map(e=>({path:mO(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function bO(e,t,n){let r=e[t];r?.copy&&(n?.isColor||n?.isVector2||n?.isVector3)?r.copy(n):e[t]=n,e.needsUpdate=!0}async function xO(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=pO(t.hdri)?t.hdri:await n({kind:`environment`,source:t.hdri});try{typeof i==`string`?await e.loadEnvironment(i):i?await e.loadFile(i):r(`environment`,`source unavailable`,{source:t.hdri})}catch(e){r(`environment`,e.message,{source:t.hdri})}}await i.restore(t)}async function SO(e,t,n,r){let i=e.color;if(!t||!i)return;let a=i.status(),o=a.activeView,s=!!t.view&&!!o&&o.display===t.view.display&&o.view===t.view.view&&(o.look??null)===t.view.look,c=a.config?.id??null,l=c??o?.configId??null;if(!((t.config?.id??null)===l&&!t.workingSpace&&!t.context&&(t.view?s:!o&&(!t.transform||t.transform===a.activeTransform?.id))))try{if(t.config&&t.config.id!==c){if(!await n({kind:`colorConfig`,config:t.config})){if(!(await i.constructor.listBuiltinConfigs().catch(()=>[])).some(e=>(e.name??e)===t.config.id||`ocio://${e.name??e}`===t.config.id)){r(`color`,`config unavailable`,{config:t.config.id});return}await e.loadColorConfig({builtin:t.config.id,registerViews:!1})}}else !t.config&&c&&await e.unloadColorConfig();t.context&&i.setContext(t.context),t.view?i.setView(t.view):t.transform&&i.setActiveView(t.transform),(t.workingSpace??null)!==(i.workingSpaceAdopted?i.workingSpace:null)&&(i.setWorkingSpace(t.workingSpace),await e.applyColorWorkingSpace())}catch(e){r(`color`,e.message,{config:t.config?.id??null})}}async function CO(e,t,{resolve:n=async()=>null}={}){if(t?.v!==1)throw Error(`scene state version ${t?.v} is not 1`);let r=[],i=(e,t,n={})=>r.push({section:e,reason:t,...n});for(let n of t.appended??[]){if(!n.url){i(`appended`,`added from memory, not a file`,{name:n.name});continue}try{await e.addModel(n.url,{name:n.name,cacheKey:n.cacheKey??void 0})}catch(e){i(`appended`,e.message,{name:n.name})}}let a=gO(e),o=t.scene??{},s=o.meshes===a.meshes&&o.materials===a.materials;s||i(`scene`,`the loaded scene is not the one saved: objects and materials left as loaded`,{saved:o,now:a}),await xO(e,t.environment,n,i),await SO(e,t.color,n,i);let c=e.settings.restore(t.settings);c.length&&i(`settings`,`not settings in this engine`,{keys:c});let l=e.lightManager.restore(t.lights);for(let t of l){let{gobo:n,ies:r}=t.userData;n&&e.goboManager?.entries?.length&&e.goboManager.setLightGobo(t.uuid,n.name,n),r&&e.iesManager?.entries?.length&&e.iesManager.setSpotLightProfile(t.uuid,r.name,r.intensity,{applyAutoCone:!1})}if(s){let n=_O(e);for(let r of t.materials??[]){let t=n.get(r.index);if(!t||(t.name??``)!==r.name){i(`materials`,`no such material`,{index:r.index,name:r.name});continue}for(let[n,i]of Object.entries(r.props)){let a=Br(i);bO(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>hO(r,e)).filter(Boolean));r.traverse(e=>{e!==r&&!e.isLight&&(e.visible=!a.has(e))}),e.updateAllMeshVisibility();let o=[];for(let n of t.moved??[]){let t=hO(r,n.path);if(!t||t.name!==n.name){i(`moved`,`no such object`,{name:n.name});continue}t.position.fromArray(n.position),t.quaternion.fromArray(n.quaternion),t.scale.fromArray(n.scale),t.updateMatrixWorld(!0),e.transformManager?.noteMoved(t),o.push(t)}if(o.length){let t=[];e.sceneMeshes.forEach((e,n)=>{for(let r=e;r;r=r.parent)if(o.includes(r)){t.push(n);break}}),t.length&&e.updateMeshTransforms(t)}}let{mismatched:u}=e.cameraManager.restore(t.cameras);return u.length&&i(`cameras`,`model cameras changed`,{names:u}),e._dispatchCamerasUpdated(),e.timeline?.restore(t.timeline),e.reset(),{skipped:r}}jt(),R(),Ys(),vx(),Dl();var wO=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),TO=new WeakMap,EO=new Set([...Object.values(I),...Object.values(L)]),DO=new Set;async function OO(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var kO=vt(`engine`);function AO(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var jO=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function MO(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||jO.test(n)}}var NO=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=PT();try{TO.get(e)?.dispose()}catch(e){kO.warn(`prior canvas owner dispose failed`,e)}TO.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._memorySpill=t.memorySpill===!0,this.storage=null,this._storageRelease=null,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=xe(t.profile),this._profileName=t.profile??`viewer`,this._issues=new mn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:I.ISSUE,issue:e})}),this.color=new Mu({issues:this._issues}),Du(this.color),this.settings=new ux({...V,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation,dofMode:this._profile.dofMode},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._emittersMoved=!1,this._maxTextureSize=V.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.timeline=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new sO,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Mb,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){kO.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(W.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,kO.debug(`WebGPU path tracer app initialized`),this}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!Gs(`storage`)?!1:Ks().storage);if(e!==!1){if(e instanceof or)this.storage=e;else{let{storage:e,reason:t,release:n}=await qb(Ks().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Y.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:I.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=L[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!EO.has(e)&&!DO.has(e)&&(DO.add(e),kO.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:I.FRAME});return}if(this.timeline.update(),this.cameraManager.updateControls(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>kO.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:I.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:I.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context}),this.dispatchEvent({type:I.RENDER_COMPLETE,...this._completionInfo()}))}this._renderHelperOverlay(),this.dispatchEvent({type:I.FRAME})}}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this.denoisingManager?.afterTrace(),t.isComplete||(this.completion.updateTime(),e&&this.denoisingManager?.tickContinuousDenoise(t.frameCount)),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),B({timeElapsed:this.completion.timeElapsed,samples:re(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,kO.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:I.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this.denoisingManager?.beforeReset({keepHistory:e||t}),this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this.denoisingManager?.afterReset(),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:I.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:I.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),te(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceFile=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.timeline?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])ce(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){kO.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&TO.get(this.canvas)===this&&TO.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),se(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceFile=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(W.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:I.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:I.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:I.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:I.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??$b(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:I.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...wO(t)});return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){let n=Ln(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:I.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?Rn(e):null,...wO(t)}}),this._sceneSourceFile=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:I.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:I.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:I.TEXTURES_REPROCESSED,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceFile??null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceFile=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ne():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){this._sceneSource=this._sceneSourceFile=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:cx.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:I.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._emittersMoved=!1,this._tagPrimarySceneObject();let n=new jh(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),ne(),this._initAnimationAndTransforms(),this.dispatchEvent({type:I.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[J.count(e.triangleCount,`tri`),t?J.count(t,`mesh`,`meshes`):null,J.count(e.materialData.materialCount,`material`),n?J.count(n,`map`):null,J.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:I.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:I.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:I.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}exportSceneState(){return yO(this)}async importSceneState(e,t){return await CO(this,e,t)}_sceneBudgets(e){return!this._memorySpill||!this.storage?e:{maxTriangles:Cw,maxPlacements:ww,...e}}_progressiveSpill(){if(!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0)return null;let e=this.stages.pathTracer;return{storage:this.storage,uploader:(t,n)=>n===`triangles`?e.createTriangleChunkUploader(t):e.createChunkUploader(t)}}_maybeSpill(){!this._memorySpill||!this.storage||this.animationManager?.hasAnimations||this._sdf?.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:I.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(Y.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident()}_dispatchCamerasUpdated(){this.dispatchEvent({type:I.CAMERAS_UPDATED,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles),this.stages.pathTracer.updateBVHData(this._sdf.bvh),this.reset(!1,{motion:!0}),n}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}_applyAnimationPose({meshIndices:e,visibilityChanged:t,cameras:n}){if(!this._sdf?.instanceTable)return;let r=!1;e.length>0&&(this._notePlacementsMoving(e),this._sdf.updateMeshTransforms(e),this.stages.pathTracer?.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this._sdf.movesEmitters(e)&&(this._emittersMoved=!0,this.animationManager.isPlaying||this._refreshMovedEmitters()),r=!0),t&&(this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),r=!0),n.length>0&&this._followAnimatedCamera(n)&&(r=!0),r&&this.reset(!1,{motion:!0})}_notePlacementsMoving(e){let t=this.denoisingManager,n=this._sdf?.instanceTable;if(!(!t?.historyActive||!n))for(let r of e){let e=n.placementRunOf(r);if(e)for(let r=e.start;r<e.start+e.count;r++)t.notePlacementMoving(n.tlasLeafIndex[r],n.world,r*16)}}_refreshMovedEmitters(){if(this._emittersMoved){if(this._sdf?.spilled){this.ensureSceneResident().then(()=>this._refreshMovedEmitters());return}this._emittersMoved=!1,this._uploadEmissivePayload(this._sdf?.refreshEmissiveTransforms()??null)}}_followAnimatedCamera(e){let t=this.cameraManager,n=t.currentCameraIndex>0?t.cameras[t.currentCameraIndex]:null,i=n?.userData?.__rayzeeSourceUuid,a=i&&e.find(e=>e.uuid===i);if(!a)return!1;a.updateWorldMatrix(!0,!1);let o=new r.Vector3;a.matrixWorld.decompose(n.position,n.quaternion,o),n.scale.set(Math.sign(o.x)||1,Math.sign(o.y)||1,Math.sign(o.z)||1),a.isPerspectiveCamera&&(n.fov=a.fov);let s=t.camera,c=t.controls,l=c?c.target.distanceTo(s.position):0;if(s.position.copy(n.position),s.quaternion.copy(n.quaternion),s.scale.copy(n.scale),s.isPerspectiveCamera&&n.isPerspectiveCamera&&(s.fov=n.fov),s.updateProjectionMatrix(),s.updateMatrixWorld(!0),c){let e=new r.Vector3(0,0,-1).applyQuaternion(s.quaternion);c.target.copy(s.position).addScaledVector(e,l||1)}return!0}updateMeshTransforms(e){this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(!1,{motion:!0}),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,U);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(H,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=Hm(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?H:2048,o=De(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Y.RENDER_RESERVE_CAPPED,`reserved render size ${J.n(e)}px was capped to ${J.n(o)}px by this device's limits — renders above ${J.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:I.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:I.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return U}_isRenderSizeSupported(e,t){return e>U||t>U?(this._issues.record(Y.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${U}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:U}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?ct:lt;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.settings.setMany(ut(r),{silent:!0,source:cx.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),n&&this._applyRenderScale(1),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_presentDisplay(){if(this.animationManagerId){this._needsDisplayRefresh=!0;return}let e=this.pipeline?.context;this._deviceLost||!e||(this.stages.compositor?.render(e),this._renderHelperOverlay())}async runFinalDenoise(){let e=this.denoisingManager;if(await e?.denoiseOnce())return!0;let t=e?.denoiser?e.denoiser.enabled?`the denoise did not complete`:`OIDN was off while accumulating — call denoisingManager.setOIDNEnabled( true ) first`:`the denoiser was not built`;return this._issues.record(Y.DENOISER_UNAVAILABLE,`final denoise produced no picture: ${t}`,{reason:t}),!1}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.cameraManager.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();this.completion.markComplete()&&this.dispatchEvent({type:I.RENDER_COMPLETE,...l});let u=t&&this.denoisingManager?.finalDenoise?await this.runFinalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return zr({engine:Zh,three:r.REVISION,profile:{name:this._profileName,values:{...this._profile}},adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.lockstepReadbacks},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Zh,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:I.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t};return{data:await this._toneMapOnGPU(r?.texture??null,i,a,o,s)??fh(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),s),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return null;try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new _x(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):null}catch(e){return kO.warn(`renderToBuffer: tone mapping on the GPU failed, doing it on the CPU: ${e?.message??e}`),null}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>kO.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),e.register(`denoiser`,()=>({bytes:this.denoisingManager?.gpuBytes()??0})),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this.overlayManager?.gpuResources()??[]]);let t=()=>e.measure();this._addTrackedListener(this,I.SCENE_REBUILD,t),this._addTrackedListener(this,I.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,I.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&Kr.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(Y.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new Nb(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}_denoiserInUse(){let e=this.denoisingManager;return!!e?.denoiser?.enabled||(e?.denoiserStrategy??`none`)!==`none`}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=ll(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&ll(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){kO.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident(),await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(te(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=MO(e),this.adapterInfo.isSoftware&&(this._issues.warn(Y.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),kO.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await OO(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},AO(a,this._deviceLostHolder),a.onuncapturederror=e=>kO.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new eE(this.canvas),this.timeline=new oE({cameraManager:this.cameraManager,onReset:()=>this.reset()})}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new bg({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new jT(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane();let e=()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()};this._addTrackedListener(this.cameraManager.controls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`start`,()=>this.wake())}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Ab(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Rb({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new lE(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>{this.interactionManager?.selectedObject===e&&this.interactionManager.deselect()}}),this.goboManager=new uE(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new xE(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new uO({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new dO(this.transformManager))),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this._presentDisplay()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this._addTrackedListener(this.cameraManager,I.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,I.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,I.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,I.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[I.DENOISING_START,I.DENOISING_END,I.UPSCALING_START,I.UPSCALING_PROGRESS,I.UPSCALING_END,I.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[I.ANIMATION_STARTED,I.ANIMATION_PAUSED,I.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,I.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,I.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({assetLoader:this.assetLoader,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())},onCameraProjection:e=>this.cameraManager.applyProjection(e)}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ne()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.timeline.clear(),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters(),this.dispatchEvent({type:I.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new cy(this.renderer,this.scene,this.cameraManager.camera,{hostMemoryGB:this._hostMemoryGB}),this.stages.normalDepth=new ly(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new uy(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new py(this.renderer,{enabled:!1}),this.stages.nrd=new Zy(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new eb(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new nb(this.renderer,{enabled:!1}),this.stages.edgeFilter=new cb(this.renderer,{enabled:!1}),this.stages.autoExposure=new hb(this.renderer,{enabled:V.autoExposure??!1}),this.stages.compositor=new _b(this.renderer,{saturation:this.settings.get(`saturation`)??V.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new ZD({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,issues:this._issues}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:I.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:I.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new oO(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.fitOrthographic(),this.cameraManager.controls.saveState(),this.cameraManager.controls.update(),this.cameraManager.walkControls.fitSpeed(this.assetLoader.getSceneScale())}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function PO(e){let t=await IO(e);try{return await FO(t,e)}finally{t.dispose()}}async function FO(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,denoise:i=!1,onProgress:a=void 0}={}){let o=e.denoisingManager;i&&o&&!o.finalDenoise&&(o.applyOIDNEnabled(!0),o._syncGBufferStages());let s=await e.renderFrames(t,{onProgress:a,allowEarlyRetire:r});return i&&await e.runFinalDenoise(),{...await e.renderToBuffer({colorSpace:n,source:i?`display`:`accumulation`}),samples:s,retiredBy:s<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo,provenance:e.getProvenance()}}async function IO({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null,storage:c=!1,hostMemoryGB:l=void 0}={}){let u=new NO(e??null,{autoResize:!1,strict:i,profile:a,storage:c,hostMemoryGB:l});try{return u.setReservedRenderResolution(Math.max(n,r)),await u.init(),u.setCanvasSize(n,r),t&&await u.loadModel(t),s&&u.settings.setMany(s,{silent:!0}),o&&u.setDeterministicMode(!0),u}catch(e){throw u.dispose(),e}}R();var LO=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=ct.maxSamples,enableOIDN:a=!0,timeline:o=null,startFrame:s=0,onFrame:c,onProgress:l,onComplete:u}=e,d=this._app,f=d.animationManager?.hasAnimations?d.animationManager.clips[t]:null;if(!f&&!o?.animates){console.warn(d.animationManager?.hasAnimations?`VideoRenderManager: Invalid clip index ${t}`:`VideoRenderManager: No animation clips or keyframes`),u?.(!1);return}let p=f?f.duration/(r||1):o.duration,m=e.totalFrames||Math.ceil(p*n),h=1/n;if(!(m>0)){console.warn(`VideoRenderManager: No frames to render`),u?.(!1);return}this._cancelled=!1,this._rendering=!0;let g=this._saveState({view:!!o});d.stopAnimation(),d.configureForMode(`production`),d.settings.setMany({maxSamples:i},{silent:!0}),d.stages.pathTracer?.updateCompletionThreshold?.(),d.cameraManager.controls&&(d.cameraManager.controls.enabled=!1);try{for(let e=Math.max(0,s);e<m&&!this._cancelled;e++){let n=e*h*r,i=f?d.animationManager.seekTo(n,t):null;if(o?.seek(e*h)&&(d.cameraManager.resetAutoFocus(),d.cameraManager.updateAutoFocus()),i?await d.refitBVH(i):d.reset(),d.stopAnimation(),await this._accumulateFrame(d),this._cancelled||(a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let s=d.getCanvas();if(s&&c){let t=await createImageBitmap(s);await c(t,e,m),t.close()}let u={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(u),d.dispatchEvent({type:I.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(g),this._rendering=!1;let e=!this._cancelled;u?.(e),d.dispatchEvent({type:I.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;){let n=t.readbackWait();if(n){await n;continue}e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(B({samples:re(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(I.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(I.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState({view:e}){let t=this._app,n=t.settings.getEffective(),r=Object.keys(ut(ct));return e&&r.push(`focusDistance`),{view:e?t.cameraManager.captureView():null,settings:r.map(e=>[e,n[e]]),renderMode:t.stages.pathTracer?.renderMode?.value,controlsEnabled:t.cameraManager.controls?.enabled,oidnEnabled:t.denoisingManager?.finalDenoise,oidnQuality:t.denoisingManager?.oidnQuality,wasPlaying:t.animationManager?.isPlaying,pauseRendering:t.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};R(),Ys(),jt(),TD(),zD(),Dl(),e.AF_DEFAULTS=Ie,e.ASVGF_QUALITY_PRESETS=Oe,e.AUTO_FOCUS_MODES=Fe,e.AnimationManager=sO,e.BVH_LEAF_MARKERS=Ke,e.CAMERA_PRESETS=Pe,e.CAMERA_RANGES=Me,e.CameraManager=eE,e.CameraTrack=iE,e.ColorManagement=Mu,e.DEFAULT_LUT_SIZE=Hl,e.DEFAULT_MAX_EV=Vl,e.DEFAULT_MIN_EV=Bl,e.DEFAULT_SUN_PATH=ve,e.DEFAULT_TEXTURE_MATRIX=st,e.DEFAULT_WORKING_SPACE=wu,e.DOWNLOAD_POLICY=Yb,e.DenoisingManager=ZD,e.DownloadCache=rx,e.ENGINE_AREAS=Wn,e.ENGINE_DEFAULTS=V,e.EngineEvents=I,e.EngineIssueError=pn,e.GoboManager=uE,e.IESManager=xE,e.INTERACTIVE_RENDER_CONFIG=lt,e.ISSUE_CODES=Y,e.ISSUE_SEVERITY=fn,e.InteractionManager=Rb,e.IssueLog=mn,e.LEGACY_EVENT_NAMES=L,e.LOG_LEVELS=xt,e.LightManager=lE,e.Logger=kt,e.MATERIAL_DEFAULTS=K,e.MATERIAL_VALUE_SOURCE=br,e.MAX_RESERVABLE_RENDER_SIZE=H,e.MAX_SCENE_BYTES=Vm,e.MAX_TABLE_TRANSFORMS=bl,e.MEMORY_CONSTANTS=dt,e.MemoryLedger=qm,e.NRD_DEFAULTS=ke,e.NRD_HIT_DIST_A=we,e.NRD_HIT_DIST_B=Te,e.NRD_PRESET_KEYS=Ae,e.NRD_QUALITY_PRESETS=je,e.OCIO_VIEW_BASE=yl,e.OverlayManager=oO,e.PRODUCTION_RENDER_CONFIG=ct,e.PathTracerApp=NO,e.PipelineContext=vb,e.RENDER_PROFILES=be,e.RETOUCH_DEFAULTS=AD,e.RETOUCH_MAX_PIXELS=MD,e.RETOUCH_RANGES=ND,e.RenderPipeline=Ab,e.RenderSettings=ux,e.RenderStage=P,e.SAFE_SCENE_BYTES=Bm,e.SCENE_STATE_VERSION=fO,e.SETTING_SOURCE=cx,e.SKY_PRESETS=Ne,e.SR_MAX_INPUT=bD,e.SR_SCALE=vD,e.STORAGE_KIND=Un,e.StageExecutionMode=N,e.StorageManager=or,e.TEXTURE_CONSTANTS=Xe,e.TRIANGLE_DATA_LAYOUT=W,e.TimelineManager=oE,e.TransformManager=uO,e.VERSION=Zh,e.VIEW_TRANSFORMS=Tl,e.VRAMTracker=Hg,e.VideoRenderManager=LO,e.acquireLock=En,e.addAllOcioViews=$l,e.addOcioView=Ql,e.addViewTransform=pl,e.applyMatrixRGBA8=Vc,e.bakeLut=jl,e.bufferBytes=Bg,e.buildOcioView=Yl,e.buildToneMapWGSL=_l,e.cachedObjectURL=ox,e.canvasColorSpaceFor=Ou,e.captureHeadless=FO,e.clearBindingAuditFindings=Tb,e.clearInputOverrides=mu,e.configureAssets=Ws,e.configurePlatform=ei,e.convertColor=Oc,e.convertEncodedRGBA8=Ic,e.convertPixelsF32=kc,e.createLogger=vt,e.dayOfYearForMonth=_e,e.deriveAlphaMode=wr,e.describeAdapter=MO,e.displayCanvasFit=Us,e.estimateSceneBytes=Gm,e.extractMatrix=Hc,e.extractSceneMetadata=ST,e.fetchFile=ix,e.fileIdentity=Ln,e.findNativeLinearSpace=ju,e.fmt=J,e.fromPortable=Br,e.getActiveColorManagement=Eu,e.getAssetConfig=Ks,e.getBindingAuditFindings=wb,e.getPlatform=ti,e.getRegistryVersion=sl,e.getRenderProfile=xe,e.getViewTransform=ll,e.hasColorSpace=Wc,e.heldLockNames=Dn,e.identityKey=Rn,e.isColorManaged=Nu,e.isDataSpace=Uc,e.isDataTexture=bu,e.linearToSrgb=Mc,e.listFileRules=_u,e.listInputOverrides=hu,e.listViewTransforms=ul,e.makeCpuSampler=Ll,e.measureBakeError=zl,e.nameFromUrl=$b,e.onRegistryChange=cl,e.openHeadless=IO,e.openStorage=Kb,e.openZip=aS,e.parseSceneMetadata=xT,e.probeAddressSpace=Km,e.readZipDirectory=nS,e.removeViewTransform=ml,e.renderHeadless=PO,e.renderUpscaled=hD,e.resolveInputSpace=yu,e.sameIdentity=zn,e.setActiveColorManagement=Du,e.setBindingAudit=Cb,e.setInputOverride=pu,e.srgbToLinear=jc,e.sunPosition=he,e.textureBytes=Vg,e.textureInputSpace=Cu,e.timeForSunElevation=ge,e.toPortable=zr});
1435
+ `,BD=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(FD/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await jD()).create(o,t,n,a,AD(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:RD}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:zD}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new yx(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){PD.warn(`retouch teardown:`,e)}}}},VD=20}));R(),jt();var UD=vt(`neural`),WD=120,GD=2,KD=1,qD=0,JD=300,YD=5,XD=3,ZD=3,QD=16,$D=e=>Math.max(0,1-e/QD),eO=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:i,getExposure:a,getSaturation:o,issues:s=null}){super(),this.renderer=e,this._issues=s,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=i,this._stages=n,this._getExposure=a,this._getSaturation=o,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._finalQuality=V.oidnQuality,this.finalDenoise=V.enableOIDN,this.continuousDenoise=V.continuousDenoise,this.continuousDenoiseInterval=V.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.temporalHistory=V.oidnTemporalHistory,this._history=null,this._historyDirty=!0,this._knownResetCount=0,this._seenTracedFrames=0,this._viewProj=new r.Matrix4,this._historyCamera={world:null,projInv:null,viewProj:null,orthographic:!1},this._movedPlacements=new Map,this._movedUpload={count:0,leaves:new Uint32Array,toPrev:new Float32Array},this._matA=new r.Matrix4,this._matB=new r.Matrix4,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}gpuBytes(){return(this.denoiser?.gpuBytes?.()??0)+(this._history?.gpuBytes?.()??0)}_recordNoOverlayCanvas(e){this._issues?.record(Y.DENOISER_UNAVAILABLE,`the ${e} pass needs the render canvas to be in a document, and it is not — skipped`,{pass:e})}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this._historyDirty=!0,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t),this._syncGBufferStages()}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){let e=this._stages.pathTracer;this.denoiser=new HE(this.renderer,{...V,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:({continuous:t=!1}={})=>{if(!e?.storageTextures?.readTarget)return null;let n=t?this._historyTextures():null;if(n)return n;let r=e.storageTextures.getReadTextures(),{backend:i}=this.renderer;return{color:i.get(r.color).texture,normal:i.get(r.normalDepth).texture,albedo:i.get(r.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:I.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:I.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this._denoiserErrorHandler=e=>e.url&&this._issues?.record(Y.ASSET_UNREACHABLE,`denoiser weights "${e.url}" could not be loaded — the render is not denoised`,{url:e.url,asset:`oidn-weights`,cause:String(e.error?.message??e.error)}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.addEventListener(`error`,this._denoiserErrorHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new dD(this.upscalerCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=V.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:I.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:I.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:I.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);this.historyWanted||this._releaseHistory(),t&&(i&&!t.enabled&&t.reset(),t.enabled=i,t.setInstanceLeafOutput?.(this.historyWanted)),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>JD*XD&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=JD);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<ZD||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?qD:this._lastCadenceSamples===0?KD:GD,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>WD&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>YD&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._historyDirty=!0,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setTemporalHistory(e){this.temporalHistory=!!e,this._syncGBufferStages()}get historyWanted(){return this.temporalHistory&&this.continuousDenoise&&!!this.denoiser?.enabled&&!this._movingHopeless}get historyActive(){let e=this._stages.pathTracer;return this.historyWanted&&!this._cadenceSuspended&&!!this._stages.normalDepth?.enabled&&e?.uniforms?.get(`cameraProjection`)?.value!==Se.equirectangular&&!(e?.visMode?.value>0)}beforeReset({keepHistory:e=!1}={}){let t=this._stages.pathTracer;if(!t||!this.historyActive)return;let n=t.resetCount!==this._knownResetCount;if(!e||n&&t.frameCount<2){this._historyDirty=!0;return}if(t.frameCount<2)return;let r=this._historyInputs();r&&(this._ensureHistory().merge(r,t.frameCount,this._historyCameraNow(),{commit:!0,keepHistory:!this._historyDirty&&!n,historyScale:$D(t.frameCount)}),this._historyDirty=!1)}afterReset(){this._knownResetCount=this._stages.pathTracer?.resetCount??0}afterTrace(){let e=this._stages.pathTracer;if(!e||e.tracedFrames===this._seenTracedFrames)return;if(this._seenTracedFrames=e.tracedFrames,e.resetCount!==this._knownResetCount&&(this._historyDirty=!0,this._knownResetCount=e.resetCount),!this.historyActive||e.frame.value!==0){this._movedPlacements.clear();return}let t=this._historyInputs();if(!t){this._movedPlacements.clear(),this._historyDirty=!0;return}let n=this._ensureHistory();this._historyDirty&&n.invalidate(),n.accumulate(t,this._historyCameraNow(),this._takeMovedPlacements()),this._historyDirty=!1}notePlacementMoving(e,t,n){e<0||!this.historyActive||this._movedPlacements.has(e)||this._movedPlacements.set(e,{world:t,offset:n,prev:t.slice(n,n+16)})}_takeMovedPlacements(){let e=this._movedPlacements,t=this._movedUpload;if(t.count=e.size,!e.size)return t;t.leaves.length<e.size&&(t.leaves=new Uint32Array(e.size*2),t.toPrev=new Float32Array(e.size*32));let n=[...e.keys()].sort((e,t)=>e-t);for(let r=0;r<n.length;r++){let{world:i,offset:a,prev:o}=e.get(n[r]);this._matB.fromArray(i,a).invert(),this._matA.fromArray(o).multiply(this._matB).toArray(t.toPrev,r*16),t.leaves[r]=n[r]}return e.clear(),t}_historyTextures(){let e=this._stages.pathTracer,t=this._history;if(!t?.valid||this._historyDirty||!this.historyActive||e.isComplete||e.resetCount!==this._knownResetCount||t.width!==this._lastRenderWidth||t.height!==this._lastRenderHeight)return null;if(e.frameCount<=1)return t.textures;if(e.frameCount>=QD)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:$D(e.frameCount)}):null}_historyInputs(){let e=this._stages.pathTracer,t=this.pipeline?.context,n=this.renderer?.backend;if(!e?.storageTextures?.readTarget||!t||!n)return null;let r=e.storageTextures.getReadTextures(),i=e=>e?n.get(e)?.texture:null,a={color:i(r.color),albedo:i(r.albedo),normal:i(r.normalDepth),geo:i(t.getTexture(`pathtracer:normalDepth`)),geoPrev:i(t.getTexture(`pathtracer:prevNormalDepth`)),shading:i(t.getTexture(`pathtracer:shadingNormal`)),leaf:i(t.getTexture(`pathtracer:instanceLeaf`)),width:e.width,height:e.height};return a.color&&a.albedo&&a.normal&&a.geo&&a.geoPrev&&a.shading&&a.leaf?a:null}_historyCameraNow(){let e=this._stages.pathTracer;this._viewProj.multiplyMatrices(e.cameraProjectionMatrix.value,e.cameraViewMatrix.value);let t=this._historyCamera;return t.world=e.cameraWorldMatrix.value.elements,t.projInv=e.cameraProjectionMatrixInverse.value.elements,t.viewProj=this._viewProj.elements,t.orthographic=e.uniforms?.get(`cameraProjection`)?.value===Se.orthographic,t}_ensureHistory(){return this._history??=new iD(this.renderer.backend.device),this._history.settings.cleanAux=!!this.denoiser?.expectsCleanAux(this._finalQuality),this._history}_releaseHistory(){this._history?.dispose(),this._history=null,this._historyDirty=!0,this._movedPlacements.clear()}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){this._recordNoOverlayCanvas(`neural`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){UD.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:I.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(OD(),fD));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(HD(),kD)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(UD.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:u.width,height:u.height})}catch(e){UD.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:I.UPSCALING_END})}}}async denoiseOnce(){let e=this.denoiser;if(!e?.enabled)return!1;for(this._cleanupCompletionListener(),this._resetCadence(),this._useFinalQuality();e.state.isLoading||e.state.isDenoising;)await(e.state.isLoading?e.whenLoaded():new Promise(t=>{let n=()=>{e.removeEventListener(`end`,n),t()};e.addEventListener(`end`,n)}));let t=await e.start();return t&&this._onDisplayRefresh?.(),t&&e.hasOutput}onRenderComplete({isStillComplete:e}){this._cleanupCompletionListener();let t=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,n=()=>{if(this.denoiser?.removeEventListener(`end`,n),this._pendingStartUpscaler=null,e()){if(t&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!t){n();return}let r=()=>{e()&&(this._pendingStartUpscaler=n,this.denoiser.addEventListener(`end`,n),t===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),r()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else r()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay(),this._historyDirty=!0}dispose(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this._denoiserErrorHandler&&this.denoiser.removeEventListener(`error`,this._denoiserErrorHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._issues=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler?this.upscaler.enabled=e:e&&this._recordNoOverlayCanvas(`upscaler`),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=je[e];if(!t)return;let n={};for(let e of Ae)n[e]=ke[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=Oe[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},tO=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},nO=class{constructor(e,t){this.layer=`scene`,this._enabled=!0,this._scene=e,this._camera=t,this._build([])}_build(e){this._orthographic=this._camera.isOrthographicCamera===!0,this._outlineNode=(0,g.outline)(this._scene,this._camera,{selectedObjects:e,edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let i=(0,n.uniform)(3),a=(0,n.uniform)(new r.Color(16777215)),o=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:s,hiddenEdge:c}=this._outlineNode,l=s.mul(a).add(c.mul(o)).mul(i),u=l.r.max(l.g).max(l.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(l,u),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;if(this._camera.isOrthographicCamera!==this._orthographic){let e=[...this._outlineNode.selectedObjects];this._outlineNode.dispose(),this._material.dispose(),this._build(e)}let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function rO(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function iO(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var aO=4096,oO=class{constructor(){this.canvas=rO(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=iO(this._sizeSource,aO);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){se(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};jt(),R();var sO=vt(`overlay`),cO=(e,t)=>e.visible&&e.layer===t&&e.render,lO=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=rO(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new oO().init({device:e,sizeSource:t})}catch(e){sO.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}gpuResources(){let e=this._viewOverlay;return e?.isVisible?[{bytes:e.canvas.width*e.canvas.height*4},...e.renderer?._frameBufferTargets?.values()??[]]:[]}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new tO;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(I.RESOLUTION_CHANGED,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new nO(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(sO.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())cO(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(cO(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(cO(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?iO(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())cO(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};R();function uO(e,t){let n=[...e].filter(t=>{for(let n=t.parent;n;n=n.parent)if(e.has(n))return!1;return!0}),r=0,i=0;t.traverse?.(()=>r++);for(let e of n)e.traverse?.(()=>i++);return i+n.length/2<r?n:null}var dO=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null,this.wakeCallback=null,this.applyPoseCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this._rigid=!n.some(e=>e?.isSkinnedMesh)&&!i.some(e=>e.tracks.some(e=>e.name.includes(`morphTargetInfluences`))),this._planClips(i),this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[],this._lastMeshWorld=this._rigid?null:new Float64Array(n.length*16).fill(NaN),this._lastMorphWeights=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles, ${this._rigid?`rigid`:`deforming`}`)}_planClips(e){let t=this._mixerRoot,n=new Map;if(t.traverse?.(e=>{n.has(e.name)||n.set(e.name,e),n.set(e.uuid,e)}),this._plans=e.map(e=>{let i=new Set,a=!1,o=!1;for(let s of e.tracks){let{nodeName:e,propertyName:c}=r.PropertyBinding.parseTrackName(s.name),l=e===``||e===`.`?t:n.get(e);if(!l){o=!0;continue}i.add(l),c===`visible`&&(a=!0)}let s=[];for(let e=0;e<this._meshes.length;e++)for(let t=this._meshes[e];t;t=t.parent)if(i.has(t)){s.push(e);break}let c=new Set;for(let e of i)e.traverse(e=>e.isCamera&&c.add(e));return{meshes:Int32Array.from(s),visibility:a,cameras:[...c],nodes:o?null:i,roots:o?null:uO(i,t)}}),this._allPlan=null,!this._rigid)return;this._slotOf=new Int32Array(this._meshes.length).fill(-1);let i=0;for(let e of this._plans)for(let t of e.meshes)this._slotOf[t]<0&&(this._slotOf[t]=i++);this._lastWorld=new Float64Array(i*16).fill(NaN),this._lastVisible=new Uint8Array(i).fill(2)}_planFor(e){if(!this._plans)return null;if(e>=0)return this._plans[e]??null;if(!this._allPlan){let e=new Set,t=new Set,n=!1,r=new Set;for(let i of this._plans)i.meshes.forEach(t=>e.add(t)),i.cameras.forEach(e=>t.add(e)),n||=i.visibility,r&&i.nodes?i.nodes.forEach(e=>r.add(e)):r=null;this._allPlan={meshes:Int32Array.from(e),visibility:n,cameras:[...t],nodes:r,roots:r?uO(r,this._mixerRoot):null}}return this._allPlan}_applyRigidPose(e){let t=this._planFor(e);if(!t)return;let n=[],r=!1,i=this._lastWorld,a=this._lastVisible;for(let e of t.meshes){let o=this._meshes[e],s=this._slotOf[e],c=o.matrixWorld.elements,l=s*16;for(let t=0;t<16;t++)if(i[l+t]!==c[t]){for(let e=0;e<16;e++)i[l+e]=c[e];n.push(e);break}if(t.visibility||a[s]===2){let e=1;for(let t=o;t;t=t.parent)if(!t.visible){e=0;break}a[s]!==e&&(a[s]=e,r=!0)}}(n.length||r||t.cameras.length)&&this.applyPoseCallback?.({meshIndices:n,visibilityChanged:r,cameras:t.cameras})}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this._activeClip=e,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:I.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:I.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:I.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this._rigid&&(this._mixerRoot.updateMatrixWorld(!0),this._applyRigidPose(-1)),this.dispatchEvent({type:I.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this._activeClip=t,this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){let e=this._rigid?this._planFor(this._activeClip)?.roots:null;if(e)for(let t of e)t.updateMatrixWorld(!0);else this._mixerRoot.updateMatrixWorld(!0);if(this._rigid)return this._applyRigidPose(this._activeClip),null;let t=this._planFor(this._activeClip)?.cameras;t?.length&&this.applyPoseCallback?.({meshIndices:[],visibilityChanged:!1,cameras:t});let n=new Int8Array(this._meshes.length);return e=>(n[e]===0&&(n[e]=this._meshes[e].isSkinnedMesh||this._poseChanged(e)?1:-1),n[e]>0?this._computeMeshPositions(e):null)}_poseChanged(e){let t=this._meshes[e],n=this._lastMeshWorld,r=t.matrixWorld.elements,i=e*16,a=!1;for(let e=0;e<16;e++)if(n[i+e]!==r[e]){for(let e=0;e<16;e++)n[i+e]=r[e];a=!0;break}let o=t.morphTargetInfluences;if(o?.length){let t=this._lastMorphWeights[e];(!t||t.length!==o.length||t.some((e,t)=>e!==o[t]))&&(this._lastMorphWeights[e]=Float64Array.from(o),a=!0)}return a}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null}};R();var fO=new r.Vector3(0,0,-1),pO=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},mO=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._moved=new Set,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e;for(let e of this._moved)pO(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>pO(e))}noteMoved(e){e&&!e.isLight&&this._moved.add(e)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target&&(this._syncLightAim(e),this._lastLightPosition=e.position.clone()))}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:I.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:I.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:I.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition&&!e.isDirectionalLight){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isDirectionalLight&&e.target&&this._controls.mode===`translate`&&this._syncLightAim(e),e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_syncLightAim(e){let t=this._tempForward.copy(e.target.position).sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(fO,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e),this._moved.add(this._attached)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._moved.clear(),this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},hO=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}},gO=1,_O=e=>typeof e==`string`&&/^https?:\/\//.test(e);function vO(e,t){let n=[];for(;e&&e!==t;){let t=e.parent;if(!t)return null;n.unshift(t.children.indexOf(e)),e=t}return e===t?n:null}function yO(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function bO(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function xO(e){let t=new Map;for(let n of e.sceneMeshes){let e=n.userData?.materialIndex;e!==void 0&&!t.has(e)&&t.set(e,Array.isArray(n.material)?n.material[0]:n.material)}return t}function SO(e){if(!e)return null;let t=e.status(),n=t.activeView,r=t.config?.id??n?.configId??null;return{config:r?{id:r}:null,view:n?{display:n.display,view:n.view,look:n.look??null}:null,transform:n?null:t.activeTransform?.id??null,workingSpace:t.workingSpaceAdopted?t.workingSpace:null,context:t.context??null}}function CO(e){let t=e.meshScene,n=xO(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(vO(e,t))}),{v:1,engine:Zh,savedAt:Date.now(),scene:bO(e),appended:t.children.filter(t=>t!==e.sceneModel&&t.userData?.__rayzeeSceneObject).map(e=>({name:e.userData.__rayzeeName??e.name,url:e.userData.__rayzeeSourceUrl??null,cacheKey:e.userData.__rayzeeCacheKey??null})),settings:e.settings.serialize(),environment:e.environmentManager?.serialize()??null,color:SO(e.color),lights:e.lightManager.serialize(),cameras:e.cameraManager.serialize(),timeline:e.timeline?.serialize()??null,materials:(e.stages.pathTracer?.materialData.serializeHostEdits()??[]).map(e=>({...e,name:n.get(e.index)?.name??``})),hidden:r,moved:(e.transformManager?.movedObjects??[]).map(e=>({path:vO(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function wO(e,t,n){let r=e[t];r?.copy&&(n?.isColor||n?.isVector2||n?.isVector3)?r.copy(n):e[t]=n,e.needsUpdate=!0}async function TO(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=_O(t.hdri)?t.hdri:await n({kind:`environment`,source:t.hdri});try{typeof i==`string`?await e.loadEnvironment(i):i?await e.loadFile(i):r(`environment`,`source unavailable`,{source:t.hdri})}catch(e){r(`environment`,e.message,{source:t.hdri})}}await i.restore(t)}async function EO(e,t,n,r){let i=e.color;if(!t||!i)return;let a=i.status(),o=a.activeView,s=!!t.view&&!!o&&o.display===t.view.display&&o.view===t.view.view&&(o.look??null)===t.view.look,c=a.config?.id??null,l=c??o?.configId??null;if(!((t.config?.id??null)===l&&!t.workingSpace&&!t.context&&(t.view?s:!o&&(!t.transform||t.transform===a.activeTransform?.id))))try{if(t.config&&t.config.id!==c){if(!await n({kind:`colorConfig`,config:t.config})){if(!(await i.constructor.listBuiltinConfigs().catch(()=>[])).some(e=>(e.name??e)===t.config.id||`ocio://${e.name??e}`===t.config.id)){r(`color`,`config unavailable`,{config:t.config.id});return}await e.loadColorConfig({builtin:t.config.id,registerViews:!1})}}else !t.config&&c&&await e.unloadColorConfig();t.context&&i.setContext(t.context),t.view?i.setView(t.view):t.transform&&i.setActiveView(t.transform),(t.workingSpace??null)!==(i.workingSpaceAdopted?i.workingSpace:null)&&(i.setWorkingSpace(t.workingSpace),await e.applyColorWorkingSpace())}catch(e){r(`color`,e.message,{config:t.config?.id??null})}}async function DO(e,t,{resolve:n=async()=>null}={}){if(t?.v!==1)throw Error(`scene state version ${t?.v} is not 1`);let r=[],i=(e,t,n={})=>r.push({section:e,reason:t,...n});for(let n of t.appended??[]){if(!n.url){i(`appended`,`added from memory, not a file`,{name:n.name});continue}try{await e.addModel(n.url,{name:n.name,cacheKey:n.cacheKey??void 0})}catch(e){i(`appended`,e.message,{name:n.name})}}let a=bO(e),o=t.scene??{},s=o.meshes===a.meshes&&o.materials===a.materials;s||i(`scene`,`the loaded scene is not the one saved: objects and materials left as loaded`,{saved:o,now:a}),await TO(e,t.environment,n,i),await EO(e,t.color,n,i);let c=e.settings.restore(t.settings);c.length&&i(`settings`,`not settings in this engine`,{keys:c});let l=e.lightManager.restore(t.lights);for(let t of l){let{gobo:n,ies:r}=t.userData;n&&e.goboManager?.entries?.length&&e.goboManager.setLightGobo(t.uuid,n.name,n),r&&e.iesManager?.entries?.length&&e.iesManager.setSpotLightProfile(t.uuid,r.name,r.intensity,{applyAutoCone:!1})}if(s){let n=xO(e);for(let r of t.materials??[]){let t=n.get(r.index);if(!t||(t.name??``)!==r.name){i(`materials`,`no such material`,{index:r.index,name:r.name});continue}for(let[n,i]of Object.entries(r.props)){let a=Br(i);wO(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>yO(r,e)).filter(Boolean));r.traverse(e=>{e!==r&&!e.isLight&&(e.visible=!a.has(e))}),e.updateAllMeshVisibility();let o=[];for(let n of t.moved??[]){let t=yO(r,n.path);if(!t||t.name!==n.name){i(`moved`,`no such object`,{name:n.name});continue}t.position.fromArray(n.position),t.quaternion.fromArray(n.quaternion),t.scale.fromArray(n.scale),t.updateMatrixWorld(!0),e.transformManager?.noteMoved(t),o.push(t)}if(o.length){let t=[];e.sceneMeshes.forEach((e,n)=>{for(let r=e;r;r=r.parent)if(o.includes(r)){t.push(n);break}}),t.length&&e.updateMeshTransforms(t)}}let{mismatched:u}=e.cameraManager.restore(t.cameras);return u.length&&i(`cameras`,`model cameras changed`,{names:u}),e._dispatchCamerasUpdated(),e.timeline?.restore(t.timeline),e.reset(),{skipped:r}}jt(),R(),Ys(),bx(),Dl();var OO=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),kO=new WeakMap,AO=new Set([...Object.values(I),...Object.values(L)]),jO=new Set;async function MO(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var NO=vt(`engine`);function PO(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var FO=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function IO(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||FO.test(n)}}var LO=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=IT();try{kO.get(e)?.dispose()}catch(e){NO.warn(`prior canvas owner dispose failed`,e)}kO.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._memorySpill=t.memorySpill===!0,this.storage=null,this._storageRelease=null,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=xe(t.profile),this._profileName=t.profile??`viewer`,this._issues=new mn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:I.ISSUE,issue:e})}),this.color=new Mu({issues:this._issues}),Du(this.color),this.settings=new ux({...V,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation,dofMode:this._profile.dofMode},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._emittersMoved=!1,this._maxTextureSize=V.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.timeline=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new dO,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Mb,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){NO.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(W.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,NO.debug(`WebGPU path tracer app initialized`),this}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!Gs(`storage`)?!1:Ks().storage);if(e!==!1){if(e instanceof or)this.storage=e;else{let{storage:e,reason:t,release:n}=await qb(Ks().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Y.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:I.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=L[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!AO.has(e)&&!jO.has(e)&&(jO.add(e),NO.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:I.FRAME});return}if(this.timeline.update(),this.cameraManager.updateControls(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>NO.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:I.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:I.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context}),this.dispatchEvent({type:I.RENDER_COMPLETE,...this._completionInfo()}))}this._renderHelperOverlay(),this.dispatchEvent({type:I.FRAME})}}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this.denoisingManager?.afterTrace(),t.isComplete||(this.completion.updateTime(),e&&this.denoisingManager?.tickContinuousDenoise(t.frameCount)),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),B({timeElapsed:this.completion.timeElapsed,samples:re(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,NO.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:I.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this.denoisingManager?.beforeReset({keepHistory:e||t}),this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this.denoisingManager?.afterReset(),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:I.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:I.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),te(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceFile=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.timeline?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])ce(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){NO.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&kO.get(this.canvas)===this&&kO.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),se(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceFile=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(W.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:I.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:I.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:I.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:I.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??$b(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:I.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...OO(t)});return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){let n=Ln(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:I.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?Rn(e):null,...OO(t)}}),this._sceneSourceFile=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:I.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:I.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:I.TEXTURES_REPROCESSED,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceFile??null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceFile=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ne():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){this._sceneSource=this._sceneSourceFile=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:cx.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:I.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._emittersMoved=!1,this._tagPrimarySceneObject();let n=new jh(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(Y.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),ne(),this._initAnimationAndTransforms(),this.dispatchEvent({type:I.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[J.count(e.triangleCount,`tri`),t?J.count(t,`mesh`,`meshes`):null,J.count(e.materialData.materialCount,`material`),n?J.count(n,`map`):null,J.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:I.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:I.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:I.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}exportSceneState(){return CO(this)}async importSceneState(e,t){return await DO(this,e,t)}_sceneBudgets(e){return!this._memorySpill||!this.storage?e:{maxTriangles:Tw,maxPlacements:Ew,...e}}_progressiveSpill(){if(!this._memorySpill||!this.storage||(this.assetLoader?.animations?.length??0)>0)return null;let e=this.stages.pathTracer;return{storage:this.storage,uploader:(t,n)=>n===`triangles`?e.createTriangleChunkUploader(t):e.createChunkUploader(t)}}_maybeSpill(){!this._memorySpill||!this.storage||this.animationManager?.hasAnimations||this._sdf?.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:I.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(Y.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident()}_dispatchCamerasUpdated(){this.dispatchEvent({type:I.CAMERAS_UPDATED,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let{triRanges:n,bvhRanges:r,...i}=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles,n),this.stages.pathTracer.updateBVHData(this._sdf.bvh,r),this.reset(!1,{motion:!0}),i}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}_applyAnimationPose({meshIndices:e,visibilityChanged:t,cameras:n}){if(!this._sdf?.instanceTable)return;let r=!1;e.length>0&&(this._notePlacementsMoving(e),this._sdf.updateMeshTransforms(e),this.stages.pathTracer?.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this._sdf.movesEmitters(e)&&(this._emittersMoved=!0,this.animationManager.isPlaying||this._refreshMovedEmitters()),r=!0),t&&(this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),r=!0),n.length>0&&this._followAnimatedCamera(n)&&(r=!0),r&&this.reset(!1,{motion:!0})}_notePlacementsMoving(e){let t=this.denoisingManager,n=this._sdf?.instanceTable;if(!(!t?.historyActive||!n))for(let r of e){let e=n.placementRunOf(r);if(e)for(let r=e.start;r<e.start+e.count;r++)t.notePlacementMoving(n.tlasLeafIndex[r],n.world,r*16)}}_refreshMovedEmitters(){if(this._emittersMoved){if(this._sdf?.spilled){this.ensureSceneResident().then(()=>this._refreshMovedEmitters());return}this._emittersMoved=!1,this._uploadEmissivePayload(this._sdf?.refreshEmissiveTransforms()??null)}}_followAnimatedCamera(e){let t=this.cameraManager,n=t.currentCameraIndex>0?t.cameras[t.currentCameraIndex]:null,i=n?.userData?.__rayzeeSourceUuid,a=i&&e.find(e=>e.uuid===i);if(!a)return!1;a.updateWorldMatrix(!0,!1);let o=new r.Vector3;a.matrixWorld.decompose(n.position,n.quaternion,o),n.scale.set(Math.sign(o.x)||1,Math.sign(o.y)||1,Math.sign(o.z)||1),a.isPerspectiveCamera&&(n.fov=a.fov);let s=t.camera,c=t.controls,l=c?c.target.distanceTo(s.position):0;if(s.position.copy(n.position),s.quaternion.copy(n.quaternion),s.scale.copy(n.scale),s.isPerspectiveCamera&&n.isPerspectiveCamera&&(s.fov=n.fov),s.updateProjectionMatrix(),s.updateMatrixWorld(!0),c){let e=new r.Vector3(0,0,-1).applyQuaternion(s.quaternion);c.target.copy(s.position).addScaledVector(e,l||1)}return!0}updateMeshTransforms(e){this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(!1,{motion:!0}),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,U);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(H,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=Um(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?H:2048,o=De(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Y.RENDER_RESERVE_CAPPED,`reserved render size ${J.n(e)}px was capped to ${J.n(o)}px by this device's limits — renders above ${J.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:I.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:I.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return U}_isRenderSizeSupported(e,t){return e>U||t>U?(this._issues.record(Y.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${U}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:U}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?ct:lt;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.settings.setMany(ut(r),{silent:!0,source:cx.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),n&&this._applyRenderScale(1),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_presentDisplay(){if(this.animationManagerId){this._needsDisplayRefresh=!0;return}let e=this.pipeline?.context;this._deviceLost||!e||(this.stages.compositor?.render(e),this._renderHelperOverlay())}async runFinalDenoise(){let e=this.denoisingManager;if(await e?.denoiseOnce())return!0;let t=e?.denoiser?e.denoiser.enabled?`the denoise did not complete`:`OIDN was off while accumulating — call denoisingManager.setOIDNEnabled( true ) first`:`the denoiser was not built`;return this._issues.record(Y.DENOISER_UNAVAILABLE,`final denoise produced no picture: ${t}`,{reason:t}),!1}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:I.RESOLUTION_CHANGED,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.cameraManager.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();this.completion.markComplete()&&this.dispatchEvent({type:I.RENDER_COMPLETE,...l});let u=t&&this.denoisingManager?.finalDenoise?await this.runFinalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return zr({engine:Zh,three:r.REVISION,profile:{name:this._profileName,values:{...this._profile}},adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.lockstepReadbacks},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Zh,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:I.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t};return{data:await this._toneMapOnGPU(r?.texture??null,i,a,o,s)??fh(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),s),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return null;try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new yx(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):null}catch(e){return NO.warn(`renderToBuffer: tone mapping on the GPU failed, doing it on the CPU: ${e?.message??e}`),null}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>NO.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),e.register(`denoiser`,()=>({bytes:this.denoisingManager?.gpuBytes()??0})),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this.overlayManager?.gpuResources()??[]]);let t=()=>e.measure();this._addTrackedListener(this,I.SCENE_REBUILD,t),this._addTrackedListener(this,I.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,I.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&Kr.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(Y.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new Nb(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}_denoiserInUse(){let e=this.denoisingManager;return!!e?.denoiser?.enabled||(e?.denoiserStrategy??`none`)!==`none`}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=ll(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&ll(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){NO.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident(),await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(te(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=IO(e),this.adapterInfo.isSoftware&&(this._issues.warn(Y.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),NO.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await MO(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},PO(a,this._deviceLostHolder),a.onuncapturederror=e=>NO.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new nE(this.canvas),this.timeline=new cE({cameraManager:this.cameraManager,onReset:()=>this.reset()})}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new bg({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new NT(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane();let e=()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()};this._addTrackedListener(this.cameraManager.controls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`change`,e),this._addTrackedListener(this.cameraManager.walkControls,`start`,()=>this.wake())}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Ab(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Rb({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new dE(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>{this.interactionManager?.selectedObject===e&&this.interactionManager.deselect()}}),this.goboManager=new fE(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new CE(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new mO({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new hO(this.transformManager))),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this._presentDisplay()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this._addTrackedListener(this.cameraManager,I.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,I.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,I.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,I.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[I.DENOISING_START,I.DENOISING_END,I.UPSCALING_START,I.UPSCALING_PROGRESS,I.UPSCALING_END,I.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[I.ANIMATION_STARTED,I.ANIMATION_PAUSED,I.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,I.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,I.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({assetLoader:this.assetLoader,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())},onCameraProjection:e=>this.cameraManager.applyProjection(e)}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ne()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.timeline.clear(),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters(),this.dispatchEvent({type:I.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new cy(this.renderer,this.scene,this.cameraManager.camera,{hostMemoryGB:this._hostMemoryGB}),this.stages.normalDepth=new ly(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new uy(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new py(this.renderer,{enabled:!1}),this.stages.nrd=new Zy(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new eb(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new nb(this.renderer,{enabled:!1}),this.stages.edgeFilter=new cb(this.renderer,{enabled:!1}),this.stages.autoExposure=new hb(this.renderer,{enabled:V.autoExposure??!1}),this.stages.compositor=new _b(this.renderer,{saturation:this.settings.get(`saturation`)??V.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new eO({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,issues:this._issues}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:I.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:I.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new lO(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.fitOrthographic(),this.cameraManager.controls.saveState(),this.cameraManager.controls.update(),this.cameraManager.walkControls.fitSpeed(this.assetLoader.getSceneScale())}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function RO(e){let t=await BO(e);try{return await zO(t,e)}finally{t.dispose()}}async function zO(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,denoise:i=!1,onProgress:a=void 0}={}){let o=e.denoisingManager;i&&o&&!o.finalDenoise&&(o.applyOIDNEnabled(!0),o._syncGBufferStages());let s=await e.renderFrames(t,{onProgress:a,allowEarlyRetire:r});return i&&await e.runFinalDenoise(),{...await e.renderToBuffer({colorSpace:n,source:i?`display`:`accumulation`}),samples:s,retiredBy:s<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo,provenance:e.getProvenance()}}async function BO({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null,storage:c=!1,hostMemoryGB:l=void 0}={}){let u=new LO(e??null,{autoResize:!1,strict:i,profile:a,storage:c,hostMemoryGB:l});try{return u.setReservedRenderResolution(Math.max(n,r)),await u.init(),u.setCanvasSize(n,r),t&&await u.loadModel(t),s&&u.settings.setMany(s,{silent:!0}),o&&u.setDeterministicMode(!0),u}catch(e){throw u.dispose(),e}}R();var VO=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=ct.maxSamples,enableOIDN:a=!0,timeline:o=null,startFrame:s=0,onFrame:c,onProgress:l,onComplete:u}=e,d=this._app,f=d.animationManager?.hasAnimations?d.animationManager.clips[t]:null;if(!f&&!o?.animates){console.warn(d.animationManager?.hasAnimations?`VideoRenderManager: Invalid clip index ${t}`:`VideoRenderManager: No animation clips or keyframes`),u?.(!1);return}let p=f?f.duration/(r||1):o.duration,m=e.totalFrames||Math.ceil(p*n),h=1/n;if(!(m>0)){console.warn(`VideoRenderManager: No frames to render`),u?.(!1);return}this._cancelled=!1,this._rendering=!0;let g=this._saveState({view:!!o});d.stopAnimation(),d.configureForMode(`production`),d.settings.setMany({maxSamples:i},{silent:!0}),d.stages.pathTracer?.updateCompletionThreshold?.(),d.cameraManager.controls&&(d.cameraManager.controls.enabled=!1);try{for(let e=Math.max(0,s);e<m&&!this._cancelled;e++){let n=e*h*r,i=f?d.animationManager.seekTo(n,t):null;if(o?.seek(e*h)&&(d.cameraManager.resetAutoFocus(),d.cameraManager.updateAutoFocus()),i?await d.refitBVH(i):d.reset(),d.stopAnimation(),await this._accumulateFrame(d),this._cancelled||(a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let s=d.getCanvas();if(s&&c){let t=await createImageBitmap(s);await c(t,e,m),t.close()}let u={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(u),d.dispatchEvent({type:I.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(g),this._rendering=!1;let e=!this._cancelled;u?.(e),d.dispatchEvent({type:I.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;){let n=t.readbackWait();if(n){await n;continue}e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(B({samples:re(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(I.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(I.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState({view:e}){let t=this._app,n=t.settings.getEffective(),r=Object.keys(ut(ct));return e&&r.push(`focusDistance`),{view:e?t.cameraManager.captureView():null,settings:r.map(e=>[e,n[e]]),renderMode:t.stages.pathTracer?.renderMode?.value,controlsEnabled:t.cameraManager.controls?.enabled,oidnEnabled:t.denoisingManager?.finalDenoise,oidnQuality:t.denoisingManager?.oidnQuality,wasPlaying:t.animationManager?.isPlaying,pauseRendering:t.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};R(),Ys(),jt(),OD(),HD(),Dl(),e.AF_DEFAULTS=Ie,e.ASVGF_QUALITY_PRESETS=Oe,e.AUTO_FOCUS_MODES=Fe,e.AnimationManager=dO,e.BVH_LEAF_MARKERS=Ke,e.CAMERA_PRESETS=Pe,e.CAMERA_RANGES=Me,e.CameraManager=nE,e.CameraTrack=oE,e.ColorManagement=Mu,e.DEFAULT_LUT_SIZE=Hl,e.DEFAULT_MAX_EV=Vl,e.DEFAULT_MIN_EV=Bl,e.DEFAULT_SUN_PATH=ve,e.DEFAULT_TEXTURE_MATRIX=st,e.DEFAULT_WORKING_SPACE=wu,e.DOWNLOAD_POLICY=Yb,e.DenoisingManager=eO,e.DownloadCache=rx,e.ENGINE_AREAS=Wn,e.ENGINE_DEFAULTS=V,e.EngineEvents=I,e.EngineIssueError=pn,e.GoboManager=fE,e.IESManager=CE,e.INTERACTIVE_RENDER_CONFIG=lt,e.ISSUE_CODES=Y,e.ISSUE_SEVERITY=fn,e.InteractionManager=Rb,e.IssueLog=mn,e.LEGACY_EVENT_NAMES=L,e.LOG_LEVELS=xt,e.LightManager=dE,e.Logger=kt,e.MATERIAL_DEFAULTS=K,e.MATERIAL_VALUE_SOURCE=br,e.MAX_RESERVABLE_RENDER_SIZE=H,e.MAX_SCENE_BYTES=Hm,e.MAX_TABLE_TRANSFORMS=bl,e.MEMORY_CONSTANTS=dt,e.MemoryLedger=Jm,e.NRD_DEFAULTS=ke,e.NRD_HIT_DIST_A=we,e.NRD_HIT_DIST_B=Te,e.NRD_PRESET_KEYS=Ae,e.NRD_QUALITY_PRESETS=je,e.OCIO_VIEW_BASE=yl,e.OverlayManager=lO,e.PRODUCTION_RENDER_CONFIG=ct,e.PathTracerApp=LO,e.PipelineContext=vb,e.RENDER_PROFILES=be,e.RETOUCH_DEFAULTS=ND,e.RETOUCH_MAX_PIXELS=FD,e.RETOUCH_RANGES=ID,e.RenderPipeline=Ab,e.RenderSettings=ux,e.RenderStage=P,e.SAFE_SCENE_BYTES=Vm,e.SCENE_STATE_VERSION=gO,e.SETTING_SOURCE=cx,e.SKY_PRESETS=Ne,e.SR_MAX_INPUT=CD,e.SR_SCALE=xD,e.STORAGE_KIND=Un,e.StageExecutionMode=N,e.StorageManager=or,e.TEXTURE_CONSTANTS=Xe,e.TRIANGLE_DATA_LAYOUT=W,e.TimelineManager=cE,e.TransformManager=mO,e.VERSION=Zh,e.VIEW_TRANSFORMS=Tl,e.VRAMTracker=Hg,e.VideoRenderManager=VO,e.acquireLock=En,e.addAllOcioViews=$l,e.addOcioView=Ql,e.addViewTransform=pl,e.applyMatrixRGBA8=Vc,e.bakeLut=jl,e.bufferBytes=Bg,e.buildOcioView=Yl,e.buildToneMapWGSL=_l,e.cachedObjectURL=ox,e.canvasColorSpaceFor=Ou,e.captureHeadless=zO,e.clearBindingAuditFindings=Tb,e.clearInputOverrides=mu,e.configureAssets=Ws,e.configurePlatform=ei,e.convertColor=Oc,e.convertEncodedRGBA8=Ic,e.convertPixelsF32=kc,e.createLogger=vt,e.dayOfYearForMonth=_e,e.deriveAlphaMode=wr,e.describeAdapter=IO,e.displayCanvasFit=Us,e.estimateSceneBytes=Km,e.extractMatrix=Hc,e.extractSceneMetadata=wT,e.fetchFile=ix,e.fileIdentity=Ln,e.findNativeLinearSpace=ju,e.fmt=J,e.fromPortable=Br,e.getActiveColorManagement=Eu,e.getAssetConfig=Ks,e.getBindingAuditFindings=wb,e.getPlatform=ti,e.getRegistryVersion=sl,e.getRenderProfile=xe,e.getViewTransform=ll,e.hasColorSpace=Wc,e.heldLockNames=Dn,e.identityKey=Rn,e.isColorManaged=Nu,e.isDataSpace=Uc,e.isDataTexture=bu,e.linearToSrgb=Mc,e.listFileRules=_u,e.listInputOverrides=hu,e.listViewTransforms=ul,e.makeCpuSampler=Ll,e.measureBakeError=zl,e.nameFromUrl=$b,e.onRegistryChange=cl,e.openHeadless=BO,e.openStorage=Kb,e.openZip=sS,e.parseSceneMetadata=CT,e.probeAddressSpace=qm,e.readZipDirectory=iS,e.removeViewTransform=ml,e.renderHeadless=RO,e.renderUpscaled=vD,e.resolveInputSpace=yu,e.sameIdentity=zn,e.setActiveColorManagement=Du,e.setBindingAudit=Cb,e.setInputOverride=pu,e.srgbToLinear=jc,e.sunPosition=he,e.textureBytes=Vg,e.textureInputSpace=Cu,e.timeForSunElevation=ge,e.toPortable=zr});