rayzee 9.4.0 → 9.4.1
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.
- package/dist/rayzee.es.js +22 -13
- package/dist/rayzee.umd.js +2 -2
- package/package.json +1 -1
- package/src/managers/CameraManager.js +55 -34
package/dist/rayzee.umd.js
CHANGED
|
@@ -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 pp=vt(`shader`),mp=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),pp.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;ua(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();rp(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();sp(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}},hp=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 gp;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 gp;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}}},gp=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(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}},vp=1073741824,yp=1073741824,bp=15,xp=16,Sp=2147483648,Cp=(e,t)=>~(e<<4|t)>>>0,wp=e=>e>=Sp,Tp=e=>~e>>>0>>>4,Ep=e=>~e&15;function Dp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/xp,r=e=>{let n=e*xp;return t[n+3]===vp&&t[n+1]>0&&t[n+1]<=bp},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*xp;t[n+3]>=yp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*xp),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*xp,s=n*xp;c.set(e.subarray(o,o+xp),s),!(t[o+3]>=yp)&&(l[s+3]=Op(t,t[o+3],r,i),l[s+7]=Op(t,t[o+7],r,i))}return c}function Op(e,t,n,r){let i=t*xp;return n(t)?Cp(e[i],e[i+1]):r[t]}var kp=(e,t,n)=>e>=Sp?Cp(Tp(e)+n,Ep(e)):e+t;function Ap(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=xp){if(e[a+3]===vp){e[a]+=n;continue}e[a+3]=kp(e[a+3],t,n),e[a+7]=kp(e[a+7],t,n)}}jt();var jp=vt(`bvh`),Mp=1073741824,Np=1073741826,Pp=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Fp=1073741824;function Ip(e,t){if(e>=Fp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Fp}`);return e}var Lp=null;function Rp(e){Lp=e}var zp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Bp=zp.FLOATS_PER_TRIANGLE,Vp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Hp=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}},Up=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=Vp(this.triangles),n=zp.POSITION_A_OFFSET,r=zp.POSITION_B_OFFSET,i=zp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Bp,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/(Bp*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Lp&&si()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;jp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Bp*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(Lp())}catch(i){jp.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?Dp(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/(Bp*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 hp(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){jp.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 _p(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){jp.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*Bp);for(let e=0;e<a;e++){let t=this.indices[e]*Bp,n=e*Bp;f.set(d.subarray(t,t+Bp),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 jp.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 Hp;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 Hp;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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Pp(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]=Mp}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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Pp(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]=Np,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Mp}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;Ip(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Pp(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]<Mp&&(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)}},Wp={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},Gp=Wp.FLOATS_PER_TRIANGLE,Kp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),qp=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):qp(e)}},Yp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Xp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Zp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*em,Qp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Kp(e),u:t?e:qp(e)}};function $p(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 em=16,tm=1073741824,nm=1073741825,rm=1e-12;function im(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)<=rm*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 am(e,t,n,r,i){let a=Wp.POSITION_A_OFFSET,o=Wp.POSITION_B_OFFSET,s=Wp.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*Gp;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 om=new Float32Array(12);function sm(e,t,n,r){let i=Yp(e,t),a=Xp(e,t),o=Zp(e,t);if(a[o+3]===tm){am(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 cm(e,t,n,r,i){let a=Yp(e,t),o=Xp(e,t),s=Zp(e,t),c=(t-i)*6,l=o[s+3];if(l===tm){am(n,o[s],o[s+1],r,c);return}if(l===nm){im(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;wp(l)&&(am(n,Tp(l),Ep(l),om,0),d=om,f=0);let p=r,m=(u-i)*6;wp(u)&&(am(n,Tp(u),Ep(u),om,6),p=om,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 lm=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Qp(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*Gp,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+Wp.POSITION_A_OFFSET]=l,a[s+Wp.POSITION_A_OFFSET+1]=u,a[s+Wp.POSITION_A_OFFSET+2]=d,a[s+Wp.POSITION_B_OFFSET]=f,a[s+Wp.POSITION_B_OFFSET+1]=p,a[s+Wp.POSITION_B_OFFSET+2]=m,a[s+Wp.POSITION_C_OFFSET]=h,a[s+Wp.POSITION_C_OFFSET+1]=g,a[s+Wp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=$p(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Wp.NORMAL_A_PACKED_OFFSET]=w,o[s+Wp.NORMAL_B_PACKED_OFFSET]=w,o[s+Wp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Qp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Jp(e);for(let e=n+r-1;e>=n;e--)cm(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=Qp(t),a=Jp(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=Xp(a,e),n=Zp(a,e);t[n+3]===nm?(sm(a,t[n],i,s),im(Yp(a,e),n,s,0,o,e*6)):cm(a,e,i,o,0)}}refit(e,t,n){let r=Qp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Jp(e);for(let e=n-1;e>=0;e--)cm(i,e,r,this._bounds,0)}},um="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})}}",dm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,um],{type:`text/javascript;charset=utf-8`});function fm(e){let t;try{if(t=dm&&(self.URL||self.webkitURL).createObjectURL(dm),!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(um),{type:`module`,name:e?.name})}}var pm="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})}}};",mm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,pm],{type:`text/javascript;charset=utf-8`});function hm(e){let t;try{if(t=mm&&(self.URL||self.webkitURL).createObjectURL(mm),!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(pm),{type:`module`,name:e?.name})}}jt(),Rp(()=>ci(fm));var gm=vt(`bvh`),_m=20,vm=5e4,ym=8;function bm(e,t,n,r){let i=e.byteLength/(_m*4),a=Math.min(oi(),ym),o=Math.ceil(Math.log2(a*2.5+1));return gm.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=ci(fm),_=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,gm.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(Sm(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,xm(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=>{gm.warn(`parallel build setup failed:`,e),c(e)})})}async function xm(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){gm.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}gm.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=ci(hm);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 Sm(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ci(fm),s=e.byteLength/(_m*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*_m*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=>{gm.warn(`single worker fallback failed:`,e),a(e)})})}function Cm(e){return si()&&typeof SharedArrayBuffer<`u`&&e>=vm}var wm=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Tm(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 Em(e,t,n){let r=Tm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(wm),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 Dm(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 Om(e){for(let t=0;t<16;t++)if(e[t]!==wm[t])return!1;return!0}function km(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 Am(e,t){for(let n=0;n<16;n++)if(e[t+n]!==wm[n])return!1;return!0}var jm=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(wm,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]=+(Tm(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 Em(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}km(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}km(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){Mm(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){Mm(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 Mm(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 Nm=16,Pm=32,Fm=e=>e<Pm?e:Pm,Im=8,Lm=64,Rm=new Float64Array(16),zm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Pm*3),this._binBounds=new Float64Array(Pm*6*3),this._binSuffix=new Float64Array(Pm),this._binSuffixCount=new Int32Array(Pm),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*Nm;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(Lm);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*Nm;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*Nm;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*Nm;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=Rm;Em(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|(Am(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<=Im)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=Fm(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)}},Bm=W.FLOATS_PER_TRIANGLE*4,Vm=64,Hm=.9,Um=64,Wm=4,Gm=7040*1024*1024,Km=9216*1024*1024;function qm(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 Jm=1.15,Ym=12*1024*1024*1024;function Xm({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Bm,bvh:Math.ceil(e*Hm)*Vm,geometry:n,placements:t*Um,orderMaps:e*Wm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Zm(e,{chunkBytes:t=vn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ym),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()}}},$m="let e,t;const n={MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let r=null;function i(e){if(e.stream===`begin`){let{width:t,height:n,depth:i}=e;r={width:t,height:n,depth:i,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*i*4)};return}let{width:t,height:n,depth:i,context:a,data:o}=r;if(e.stream===`layer`){a.clearRect(0,0,t,n),a.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(a.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}r=null,self.postMessage({data:o.buffer,width:t,height:n,depth:i},[o.buffer])}async function a({shared:n,width:r,height:i,layers:a}){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;let o=new Uint8Array(n),s=r*i*4;for(let{index:e,texture:t}of a)try{await d(t,o,e*s,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(t){if(t.data.shared){try{e||o(t.data.maxTextureSize),await a(t.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(t.data.stream){try{i(t.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:n,maxTextureSize:r,method:c=`direct-transfer`}=t.data;try{e||o(r);let t=await s(n,r,c);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function o(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 s(e,t,n){switch(n){case`direct-transfer`:return await m(e,t);case`offscreen-optimized`:return await g(e,t);case`imageBitmap-batch`:return await _(e,t);default:return await m(e,t)}}async function c(e,t,n){let{maxWidth:r,maxHeight:i}=v(e,t),a=e.length,o=l(r,i,a),s=Math.ceil(a/o);console.log(`Processing ${a} textures in ${s} chunks of up to ${o} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*o*4/1024/1024).toFixed(2)}MB`);let c;try{c=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await h(e,y(e,t),n)}let d=r*i*o*4,f;try{f=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await h(e,y(e,t),n)}for(let t=0;t<s;t++){let n=t*o,s=Math.min(n+o,a),l=s-n,d=await u(e.slice(n,s),r,i,f.subarray(0,r*i*l*4)),p=n*r*i*4,m=l*r*i*4;c.set(new Uint8Array(d.data.slice(0,m)),p),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:c.buffer,width:r,height:i,depth:a}}function l(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 u(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 d(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 d(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 f(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 f(e,i,a)}return await u(e,t,n,r)}async function p(e,t,n,r,i){await d(e,n,r*i*4*t,r,i)}async function m(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await p(t,e,s,i,a)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function h(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await f(e,r,i,n)}async function g(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(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:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}t.clearRect(0,0,i,a),t.drawImage(n,0,0);let o=t.getImageData(0,0,i,a),c=i*a*4*e;s.set(o.data,c),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(n,r){let{maxWidth:i,maxHeight:a}=v(n,r),o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`imageBitmap-batch`)}let u=Math.min(l(i,a,n.length),n.length);for(let r=0;r<n.length;r+=u){let o=Math.min(r+u,n.length),c=[];for(let e=r;e<o;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}c.push(r.then(t=>({bitmap:t,index:e})))}let l=await Promise.all(c);e.width=i,e.height=a,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of l){t.clearRect(0,0,i,a),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,a),o=i*a*4*n;s.set(r.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function v(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 y(e,t){let n=v(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",eh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$m],{type:`text/javascript;charset=utf-8`});function th(e){let t;try{if(t=eh&&(self.URL||self.webkitURL).createObjectURL(eh),!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($m),{type:`module`,name:e?.name})}}var nh=`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})}};`,rh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,nh],{type:`text/javascript;charset=utf-8`});function ih(e){let t;try{if(t=rh&&(self.URL||self.webkitURL).createObjectURL(rh),!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(nh),{type:`module`,name:e?.name})}}function ah({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)}}jl();var oh=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),sh=new Map;function ch(){sh.clear();for(let e of kl.values())sh.set(e.id,oh(e.cpu))}ch(),fl(ch);function lh(e){return pl(e)?.outputEncoded===!0}function uh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function dh(e,t){let n=pl(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var fh=.2126,ph=.7152,mh=.0722;function hh(e,t){if(t===1)return;let n=e[0]*fh+e[1]*ph+e[2]*mh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function gh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=sh.get(n)??sh.get(r.NoToneMapping),s=dh(t,n),c=lh(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,hh(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]=uh(u[0])*255+.5,l[t+1]=uh(u[1])*255+.5,l[t+2]=uh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var _h=vt(`textures`),vh=8*2**20,yh=16,bh=4,xh=8192*8192,Sh={busy:0,waiting:[]};async function Ch(){return Sh.busy<Math.max(1,oi()-1)?Sh.busy++:await new Promise(e=>Sh.waiting.push(e)),()=>{let e=Sh.waiting.shift();e?e():Sh.busy--}}var wh={toSRGB:null,toLinear:null};function Th(e){if(!wh[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?uh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}wh[e]=t}return wh[e]}var Eh=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=[]}},Dh=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`}},Oh=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=[]}},kh=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 Eh,this.bufferPool=new Dh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Oh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof gn)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 Oh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:oi()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Au();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){_h.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,_h.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=Th(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?_h.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):_h.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=Au()?.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`worker-streaming`:c=await this.processInWorkerStreaming(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 gn)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:`worker-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=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new th;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<xh)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,bh,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=ci(th);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(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;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=ci(th);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=dt.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>yh&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.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=si()&&i*t.length>=vh?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)=>ah(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ch(),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=ci(ih),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++)mn(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 Oh;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:Ah(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:Ah(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 Ah(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var jh=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=Nh(E,Mh(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=Nh(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 Mh(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 Nh(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 Ph=Object.freeze({r:0,g:0,b:0});function Fh(e){if(!e)return Ph;if(!zr())return e;let t=[e.r,e.g,e.b];return Vr(t),{r:t[0],g:t[1],b:t[2]}}var Ih=vt(`emissive`),Lh=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&&(_=Fh(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&&Ih.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,Ih.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 Ih.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=Fh(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 jh().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,Ih.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 Rh=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)}}},zh=1<<20,Bh=1<<21,Vh=()=>new Promise(e=>setTimeout(e,0)),Hh=[0,1,2,4,5,6,8,9,10];function Uh(e,t,n,r=Hh){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 Wh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Uh(e,i,a)),r+=a,r>=Bh&&(r=0,await Vh());return n}async function Gh(e,t){let n=await e?.area(qn.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 Kh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(qn.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,zh),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+=zh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+zh*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 qh(e,t,n,r){for(let i=0;i<r;i+=zh){let a=Math.min(zh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Jh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Yh=16,Xh=W.POSITION_A_OFFSET,Zh=W.POSITION_B_OFFSET,Qh=W.POSITION_C_OFFSET;async function $h(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+Xh]+o[n+Zh]+o[n+Qh],c[r]=o[n+Xh+1]+o[n+Zh+1]+o[n+Qh+1],l[r]=o[n+Xh+2]+o[n+Zh+2]+o[n+Qh+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 tg(u,o,eg(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await ng(e,t,n,u,i),{order:u,pieces:d,tree:p}}function eg(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 tg(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 ng(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 rg(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Yh;let s=new Float32Array(i*Yh),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];Ap(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*Yh;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 ig=`9.4.0`,ag=1e4,og=15e5;function sg(e,t,n=ag){return e>=n&&t/og<e/3}var cg="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})}};",lg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,cg],{type:`text/javascript;charset=utf-8`});function ug(e){let t;try{if(t=lg&&(self.URL||self.webkitURL).createObjectURL(lg),!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(cg),{type:`module`,name:e?.name})}}var dg="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})}};",fg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,dg],{type:`text/javascript;charset=utf-8`});function pg(e){let t;try{if(t=fg&&(self.URL||self.webkitURL).createObjectURL(fg),!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(dg),{type:`module`,name:e?.name})}}jt(),$s();var mg=5e4,hg=2e5,gg=2e6,_g=1<<19,vg=4e7,yg=1.5*1024**3,bg=256*1024*1024,xg=vt(`scene`),Sg=e=>Array.isArray(e)?e:[e],Cg=e=>Sg(e).reduce((e,t)=>e+t.byteLength,0),wg=64*1024*1024;async function Tg(e,t,n){for(let r of Sg(n))await e.writeAt(t,r),t+=r.byteLength}function Eg(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 Dg=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(oi(),6),maxSceneBytes:Km,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:ag,...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 Fr({issues:this.config.issues}),this.bvhBuilder=new Up,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 kh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Lh,this.tlasBuilder=new zm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?xg.debug(e):xg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Xm(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=yg+Eg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Gm,maxBytes:t,fits:r.total<=Gm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(xg.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(Gm)} 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:Gm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Zm(Math.ceil(t*Jm),{shared:yn});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?Cg(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;xg.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,xn(e=>this.memory.alloc(e));let r=new Rh(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>vg,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=kr(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=>xg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,xg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),xn(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 xg.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=Cn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await mr.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await mr.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 br.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);jm.rootAABB(Sg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Cg(r),f.blasAt.set(e,a),n.nodeCount=Cg(r)/64,n.bvhData=null,this._queueSpill(f,()=>Tg(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>bg&&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>yg&&(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),xg.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 jm,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(_,zm.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??Cg(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(zm.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(Cn.lazy(O,16,Float32Array,void 0,yn));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 qh(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 Sg(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;xg.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 xg.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>=hg&&Cm(e.count)}async _buildLargeBLAS(e,t){if(e.count>gg)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 bm(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 $h(n,e.start,e.count,_g,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(oi(),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),jm.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{...rg(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:${ig}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=zu(Xs().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Gh(r,this._blasKey);if(!i)return null;let a=e=>(xg.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 Wh(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 Jh(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},xg.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=zu(Xs().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 Wh(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 Kh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&xg.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 mr.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await mr.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(Sg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Cg(a),e.blasAt.set(t,o),r.nodeCount=Cg(a)/64,r.bvhData=null,this._queueSpill(e,()=>Tg(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+=wg)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(wg,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 mr.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);Ap(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=ci(fm);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 xg.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 xg.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){xg.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 xg.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=Cn.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||=ci(ug),!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 lm;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?(Dm(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(Dm(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||zm.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)):xg.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):(xg.error(`failed to get BVH data`),!1)):(xg.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 mr.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await mr.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 xg.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=kr(e),xg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&xg.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>=mg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return zm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,xg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ci(pg);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 Cn?e:Cn.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 Cn?e:Cn.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=Om(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||Om(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){xg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{xg.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,ci(fm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){xg.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}},Og=[[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]],kg=[[-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]],Ag=[[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 jg(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=Og[i],o=kg[i],s=Ag[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 Mg=1/(4*Math.PI);function Ng(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]=jg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Vr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Pg=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=Ng(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=Ng(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=Ng(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Mg,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=Ng(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*Mg,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 Fg=1<<18,Ig=vt(`pathtracer`),Lg=100,Rg=4,zg=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 Dg,this.lightSerializer=new Pg,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 on(a,o),this._defineUniformGetters(),this.materialData=new $r(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 Qu(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new mp,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._writeLightList(`directional`,this.directionalLightsData,this.numDirectionalLights),this._writeLightList(`area`,this.areaLightsData,this.numAreaLights),this._writeLightList(`point`,this.pointLightsData,this.numPointLights),this._writeLightList(`spot`,this.spotLightsData,this.numSpotLights)}_writeLightList(e,t,n){let r=nn[e],i=this[`${e}LightsBufferNode`],a=t?Math.floor(t.length/r):0,o=a*r;o>i.array.length&&(i.array=new Float32Array(an(e,a)*r),this._lightBufferRealloc=!0),o>0&&i.array.set(t.subarray(0,o)),i.array.fill(0,o),n.value=a}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),this._accumulationLockstep=!!this._lockstep}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<Lg}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}),Ig.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=Fg;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/Rg),Ig.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){Ig.error(`triangle data required`);return}if(!this.bvhStorageNode){Ig.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._accumulationLockstep=!1),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(),Ig.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(),Ig.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{Ig.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(),Ig.debug(`material rebuild complete`)}catch(e){Ig.error(`material rebuild failed:`,e);try{Ig.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Ig.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 Bg=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},Vg=65535,Hg={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},Ug=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,Bg.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(){Ca(this._renderer,this._countersAttr),Ca(this._renderer,this._bounceCountsAttr),Ca(this._renderer,this._attrA),Ca(this._renderer,this._attrB),Ca(this._renderer,this._sortAttr),Ca(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}},Wg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Gg={[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 Kg(e){return(Wg[e.format]??4)*(Gg[e.type]??4)}function qg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Jg(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*Kg(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*Kg(e)}var Yg=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*Kg(e));return a}return this._isResident(e)?Jg(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 Xg=vt(`wavefront`),Zg=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);Xg.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=>Xg.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()}},Qg=(0,n.int)(Se.equirectangular),$g=(0,n.int)(Se.orthographic),e_=e=>e.equal($g);function t_(){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 n_=(e,t,n,r)=>({origin:i_(e,t,n,r.cameraProjection),direction:a_(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),r_=(e,t,n,r,i)=>{let{origin:a,direction:o}=n_(e,n,r,i);return a.add(o.mul(t))},i_=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(e_(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}),a_=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Qg),()=>{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(e_(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}),o_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=i_(e,r,i,a).toVar(),y=a_(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(Qg),s.y.sub(s.x).mul(.5),(0,n.select)(e_(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(Qg),()=>{C.assign(Yi({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)))}),mi({origin:b,direction:x})});function s_(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=mi.wrap(o_(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ba(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),Va(t,C,k.direction,(0,n.uint)(Hg.ACTIVE)),Ha(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),Ua(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Ma(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),so(t,C,(0,n.vec3)(1))}),to(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Qa(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 c_=32,l_=4096,u_=4,d_=1e8,f_=()=>(0,n.array)(`int`,c_).toVar(),p_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),m_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),h_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),g_=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)(d_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},__=(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)),v_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),y_=(0,n.wgslFn)(`
|
|
715
|
+
`);jt();var pp=vt(`shader`),mp=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),pp.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;ua(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();rp(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();sp(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}},hp=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 gp;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 gp;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}}},gp=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(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}},vp=1073741824,yp=1073741824,bp=15,xp=16,Sp=2147483648,Cp=(e,t)=>~(e<<4|t)>>>0,wp=e=>e>=Sp,Tp=e=>~e>>>0>>>4,Ep=e=>~e&15;function Dp(e){let t=new Uint32Array(e.buffer,e.byteOffset,e.length),n=e.length/xp,r=e=>{let n=e*xp;return t[n+3]===vp&&t[n+1]>0&&t[n+1]<=bp},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*xp;t[n+3]>=yp||(r(t[n+7])||s.push(t[n+7]),r(t[n+3])||s.push(t[n+3]))}let c=new Float32Array(o*xp),l=new Uint32Array(c.buffer);for(let n=0;n<o;n++){let o=a[n]*xp,s=n*xp;c.set(e.subarray(o,o+xp),s),!(t[o+3]>=yp)&&(l[s+3]=Op(t,t[o+3],r,i),l[s+7]=Op(t,t[o+7],r,i))}return c}function Op(e,t,n,r){let i=t*xp;return n(t)?Cp(e[i],e[i+1]):r[t]}var kp=(e,t,n)=>e>=Sp?Cp(Tp(e)+n,Ep(e)):e+t;function Ap(e,t,n,r=0,i=e.length){for(let a=r;a<i;a+=xp){if(e[a+3]===vp){e[a]+=n;continue}e[a+3]=kp(e[a+3],t,n),e[a+7]=kp(e[a+7],t,n)}}jt();var jp=vt(`bvh`),Mp=1073741824,Np=1073741826,Pp=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Fp=1073741824;function Ip(e,t){if(e>=Fp)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Fp}`);return e}var Lp=null;function Rp(e){Lp=e}var zp={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Bp=zp.FLOATS_PER_TRIANGLE,Vp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Hp=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}},Up=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=Vp(this.triangles),n=zp.POSITION_A_OFFSET,r=zp.POSITION_B_OFFSET,i=zp.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Bp,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/(Bp*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Lp&&si()?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;jp.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Bp*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(Lp())}catch(i){jp.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?Dp(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/(Bp*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 hp(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){jp.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 _p(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){jp.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*Bp);for(let e=0;e<a;e++){let t=this.indices[e]*Bp,n=e*Bp;f.set(d.subarray(t,t+Bp),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 jp.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 Hp;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 Hp;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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Pp(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]=Mp}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)}Ip(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Pp(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]=Np,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Mp}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;Ip(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Pp(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]<Mp&&(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)}},Wp={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},Gp=Wp.FLOATS_PER_TRIANGLE,Kp=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),qp=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),Jp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):qp(e)}},Yp=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,Xp=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,Zp=(e,t)=>e.chunked?e.chunked.baseOf(t):t*em,Qp=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):Kp(e),u:t?e:qp(e)}};function $p(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 em=16,tm=1073741824,nm=1073741825,rm=1e-12;function im(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)<=rm*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 am(e,t,n,r,i){let a=Wp.POSITION_A_OFFSET,o=Wp.POSITION_B_OFFSET,s=Wp.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*Gp;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 om=new Float32Array(12);function sm(e,t,n,r){let i=Yp(e,t),a=Xp(e,t),o=Zp(e,t);if(a[o+3]===tm){am(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 cm(e,t,n,r,i){let a=Yp(e,t),o=Xp(e,t),s=Zp(e,t),c=(t-i)*6,l=o[s+3];if(l===tm){am(n,o[s],o[s+1],r,c);return}if(l===nm){im(a,s,r,(o[s]-i)*6,r,c);return}let u=o[s+7],d=r,f=(l-i)*6;wp(l)&&(am(n,Tp(l),Ep(l),om,0),d=om,f=0);let p=r,m=(u-i)*6;wp(u)&&(am(n,Tp(u),Ep(u),om,6),p=om,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 lm=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(e,t,n){let r=n.length,i=Qp(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*Gp,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+Wp.POSITION_A_OFFSET]=l,a[s+Wp.POSITION_A_OFFSET+1]=u,a[s+Wp.POSITION_A_OFFSET+2]=d,a[s+Wp.POSITION_B_OFFSET]=f,a[s+Wp.POSITION_B_OFFSET+1]=p,a[s+Wp.POSITION_B_OFFSET+2]=m,a[s+Wp.POSITION_C_OFFSET]=h,a[s+Wp.POSITION_C_OFFSET+1]=g,a[s+Wp.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=$p(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Wp.NORMAL_A_PACKED_OFFSET]=w,o[s+Wp.NORMAL_B_PACKED_OFFSET]=w,o[s+Wp.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=Qp(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=Jp(e);for(let e=n+r-1;e>=n;e--)cm(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=Qp(t),a=Jp(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=Xp(a,e),n=Zp(a,e);t[n+3]===nm?(sm(a,t[n],i,s),im(Yp(a,e),n,s,0,o,e*6)):cm(a,e,i,o,0)}}refit(e,t,n){let r=Qp(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=Jp(e);for(let e=n-1;e>=0;e--)cm(i,e,r,this._bounds,0)}},um="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})}}",dm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,um],{type:`text/javascript;charset=utf-8`});function fm(e){let t;try{if(t=dm&&(self.URL||self.webkitURL).createObjectURL(dm),!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(um),{type:`module`,name:e?.name})}}var pm="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})}}};",mm=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,pm],{type:`text/javascript;charset=utf-8`});function hm(e){let t;try{if(t=mm&&(self.URL||self.webkitURL).createObjectURL(mm),!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(pm),{type:`module`,name:e?.name})}}jt(),Rp(()=>ci(fm));var gm=vt(`bvh`),_m=20,vm=5e4,ym=8;function bm(e,t,n,r){let i=e.byteLength/(_m*4),a=Math.min(oi(),ym),o=Math.ceil(Math.log2(a*2.5+1));return gm.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=ci(fm),_=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,gm.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(Sm(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,xm(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=>{gm.warn(`parallel build setup failed:`,e),c(e)})})}async function xm(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){gm.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}gm.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=ci(hm);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 Sm(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=ci(fm),s=e.byteLength/(_m*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*_m*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=>{gm.warn(`single worker fallback failed:`,e),a(e)})})}function Cm(e){return si()&&typeof SharedArrayBuffer<`u`&&e>=vm}var wm=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Tm(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 Em(e,t,n){let r=Tm(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(wm),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 Dm(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 Om(e){for(let t=0;t<16;t++)if(e[t]!==wm[t])return!1;return!0}function km(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 Am(e,t){for(let n=0;n<16;n++)if(e[t+n]!==wm[n])return!1;return!0}var jm=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(wm,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]=+(Tm(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 Em(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}km(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}km(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){Mm(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){Mm(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 Mm(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 Nm=16,Pm=32,Fm=e=>e<Pm?e:Pm,Im=8,Lm=64,Rm=new Float64Array(16),zm=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Pm*3),this._binBounds=new Float64Array(Pm*6*3),this._binSuffix=new Float64Array(Pm),this._binSuffixCount=new Int32Array(Pm),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*Nm;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(Lm);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*Nm;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*Nm;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*Nm;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=Rm;Em(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|(Am(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<=Im)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=Fm(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)}},Bm=W.FLOATS_PER_TRIANGLE*4,Vm=64,Hm=.9,Um=64,Wm=4,Gm=7040*1024*1024,Km=9216*1024*1024;function qm(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 Jm=1.15,Ym=12*1024*1024*1024;function Xm({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Bm,bvh:Math.ceil(e*Hm)*Vm,geometry:n,placements:t*Um,orderMaps:e*Wm};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function Zm(e,{chunkBytes:t=vn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Ym),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()}}},$m="let e,t;const n={MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let r=null;function i(e){if(e.stream===`begin`){let{width:t,height:n,depth:i}=e;r={width:t,height:n,depth:i,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*i*4)};return}let{width:t,height:n,depth:i,context:a,data:o}=r;if(e.stream===`layer`){a.clearRect(0,0,t,n),a.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(a.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}r=null,self.postMessage({data:o.buffer,width:t,height:n,depth:i},[o.buffer])}async function a({shared:n,width:r,height:i,layers:a}){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;let o=new Uint8Array(n),s=r*i*4;for(let{index:e,texture:t}of a)try{await d(t,o,e*s,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(t){if(t.data.shared){try{e||o(t.data.maxTextureSize),await a(t.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(t.data.stream){try{i(t.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:n,maxTextureSize:r,method:c=`direct-transfer`}=t.data;try{e||o(r);let t=await s(n,r,c);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function o(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 s(e,t,n){switch(n){case`direct-transfer`:return await m(e,t);case`offscreen-optimized`:return await g(e,t);case`imageBitmap-batch`:return await _(e,t);default:return await m(e,t)}}async function c(e,t,n){let{maxWidth:r,maxHeight:i}=v(e,t),a=e.length,o=l(r,i,a),s=Math.ceil(a/o);console.log(`Processing ${a} textures in ${s} chunks of up to ${o} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*o*4/1024/1024).toFixed(2)}MB`);let c;try{c=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await h(e,y(e,t),n)}let d=r*i*o*4,f;try{f=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await h(e,y(e,t),n)}for(let t=0;t<s;t++){let n=t*o,s=Math.min(n+o,a),l=s-n,d=await u(e.slice(n,s),r,i,f.subarray(0,r*i*l*4)),p=n*r*i*4,m=l*r*i*4;c.set(new Uint8Array(d.data.slice(0,m)),p),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:c.buffer,width:r,height:i,depth:a}}function l(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 u(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 d(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 d(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 f(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 f(e,i,a)}return await u(e,t,n,r)}async function p(e,t,n,r,i){await d(e,n,r*i*4*t,r,i)}async function m(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await p(t,e,s,i,a)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function h(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await f(e,r,i,n)}async function g(n,r){let{maxWidth:i,maxHeight:a}=v(n,r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a);let o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(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:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}t.clearRect(0,0,i,a),t.drawImage(n,0,0);let o=t.getImageData(0,0,i,a),c=i*a*4*e;s.set(o.data,c),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*a*4*e;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function _(n,r){let{maxWidth:i,maxHeight:a}=v(n,r),o=n.length,s;try{s=new Uint8Array(i*a*o*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await c(n,r,`imageBitmap-batch`)}let u=Math.min(l(i,a,n.length),n.length);for(let r=0;r<n.length;r+=u){let o=Math.min(r+u,n.length),c=[];for(let e=r;e<o;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}c.push(r.then(t=>({bitmap:t,index:e})))}let l=await Promise.all(c);e.width=i,e.height=a,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of l){t.clearRect(0,0,i,a),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,a),o=i*a*4*n;s.set(r.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function v(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 y(e,t){let n=v(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",eh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,$m],{type:`text/javascript;charset=utf-8`});function th(e){let t;try{if(t=eh&&(self.URL||self.webkitURL).createObjectURL(eh),!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($m),{type:`module`,name:e?.name})}}var nh=`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})}};`,rh=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,nh],{type:`text/javascript;charset=utf-8`});function ih(e){let t;try{if(t=rh&&(self.URL||self.webkitURL).createObjectURL(rh),!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(nh),{type:`module`,name:e?.name})}}function ah({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)}}jl();var oh=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),sh=new Map;function ch(){sh.clear();for(let e of kl.values())sh.set(e.id,oh(e.cpu))}ch(),fl(ch);function lh(e){return pl(e)?.outputEncoded===!0}function uh(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function dh(e,t){let n=pl(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var fh=.2126,ph=.7152,mh=.0722;function hh(e,t){if(t===1)return;let n=e[0]*fh+e[1]*ph+e[2]*mh;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function gh(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=sh.get(n)??sh.get(r.NoToneMapping),s=dh(t,n),c=lh(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,hh(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]=uh(u[0])*255+.5,l[t+1]=uh(u[1])*255+.5,l[t+2]=uh(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}jt();var _h=vt(`textures`),vh=8*2**20,yh=16,bh=4,xh=8192*8192,Sh={busy:0,waiting:[]};async function Ch(){return Sh.busy<Math.max(1,oi()-1)?Sh.busy++:await new Promise(e=>Sh.waiting.push(e)),()=>{let e=Sh.waiting.shift();e?e():Sh.busy--}}var wh={toSRGB:null,toLinear:null};function Th(e){if(!wh[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?uh(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}wh[e]=t}return wh[e]}var Eh=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=[]}},Dh=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`}},Oh=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=[]}},kh=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 Eh,this.bufferPool=new Dh({maxMemory:e.maxBufferMemory||dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Oh,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof gn)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 Oh,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:oi()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Au();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){_h.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,_h.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=Th(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?_h.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):_h.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=Au()?.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`worker-streaming`:c=await this.processInWorkerStreaming(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 gn)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:`worker-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=1,n=null;try{let r=await this.prepareTexturesForWorkerDirect(e),i=this._sharedPackSlots(r);if(i>0)return t+=i,this.activeWorkers+=i,this.createDataArrayTextureFromResult(await this._packAcrossWorkers(r,t));n=new th;let a=await new Promise((e,t)=>{n.onmessage=n=>{n.data.error?t(Error(n.data.error)):e(n.data)},n.onerror=t;let i=[];r.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),n.postMessage({textures:r,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return this.createDataArrayTextureFromResult(a)}finally{n?.terminate(),this.activeWorkers-=t}}_sharedPackSlots(e){if(typeof SharedArrayBuffer>`u`||!globalThis.crossOriginIsolated||e.reduce((e,t)=>e+t.width*t.height,0)<xh)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,bh,t+1)-1)}async _packAcrossWorkers(e,t){let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(e.map(e=>({image:e}))),i=e.length,a=new SharedArrayBuffer(n*r*i*4),o=Array.from({length:t},()=>({cost:0,layers:[],transfer:[]})),s=e.map((e,t)=>t),c=t=>e[t].width*e[t].height;s.sort((e,t)=>c(t)-c(e));for(let t of s){let n=o.reduce((e,t)=>t.cost<e.cost?t:e),r=e[t];n.layers.push({index:t,texture:r}),n.cost+=c(t),r.data instanceof ArrayBuffer?n.transfer.push(r.data):r.bitmap&&n.transfer.push(r.bitmap)}let l=[];try{await Promise.all(o.filter(e=>e.layers.length).map(e=>new Promise((t,i)=>{let o=ci(th);l.push(o),o.onmessage=({data:e})=>e.error?i(Error(e.error)):t(),o.onerror=e=>i(Error(e.message||`texture worker failed`)),o.postMessage({shared:a,width:n,height:r,layers:e.layers,maxTextureSize:this.maxTextureSize},e.transfer)})))}finally{for(let e of l)e.terminate()}return{data:a,width:n,height:r,depth:i}}async processInWorkerStreaming(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;for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;let a=ci(th);try{let e=0,o=null,s,c=new Promise((e,t)=>s={resolve:e,reject:t});c.catch(()=>{}),a.onmessage=({data:t})=>{t.error?s.reject(Error(t.error)):t.stream===`ack`?e++:s.resolve(t),o?.()},a.onerror=e=>{s.reject(Error(e.message||`texture worker failed`)),o?.()},a.postMessage({stream:`begin`,width:n,height:r,depth:i});let l=performance.now();for(let s=0;s<i;s++){for(;s-e>=dt.STREAM_BATCH_SIZE;)await Promise.race([new Promise(e=>o=e),c]),l=performance.now();let i=t[s],u=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});a.postMessage({stream:`layer`,index:s,bitmap:u},[u]),performance.now()-l>yh&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.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=si()&&i*t.length>=vh?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)=>ah(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ch(),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=ci(ih),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++)mn(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 Oh;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:Ah(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:Ah(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 Ah(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var jh=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=Nh(E,Mh(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=Nh(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 Mh(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 Nh(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 Ph=Object.freeze({r:0,g:0,b:0});function Fh(e){if(!e)return Ph;if(!zr())return e;let t=[e.r,e.g,e.b];return Vr(t),{r:t[0],g:t[1],b:t[2]}}var Ih=vt(`emissive`),Lh=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&&(_=Fh(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&&Ih.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,Ih.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 Ih.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=Fh(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 jh().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,Ih.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 Rh=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)}}},zh=1<<20,Bh=1<<21,Vh=()=>new Promise(e=>setTimeout(e,0)),Hh=[0,1,2,4,5,6,8,9,10];function Uh(e,t,n,r=Hh){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 Wh(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Uh(e,i,a)),r+=a,r>=Bh&&(r=0,await Vh());return n}async function Gh(e,t){let n=await e?.area(qn.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 Kh(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(qn.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,zh),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+=zh*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+zh*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 qh(e,t,n,r){for(let i=0;i<r;i+=zh){let a=Math.min(zh,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function Jh(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}var Yh=16,Xh=W.POSITION_A_OFFSET,Zh=W.POSITION_B_OFFSET,Qh=W.POSITION_C_OFFSET;async function $h(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+Xh]+o[n+Zh]+o[n+Qh],c[r]=o[n+Xh+1]+o[n+Zh+1]+o[n+Qh+1],l[r]=o[n+Xh+2]+o[n+Zh+2]+o[n+Qh+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 tg(u,o,eg(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await ng(e,t,n,u,i),{order:u,pieces:d,tree:p}}function eg(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 tg(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 ng(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 rg(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/Yh;let s=new Float32Array(i*Yh),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];Ap(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*Yh;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 ig=`9.4.1`,ag=1e4,og=15e5;function sg(e,t,n=ag){return e>=n&&t/og<e/3}var cg="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})}};",lg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,cg],{type:`text/javascript;charset=utf-8`});function ug(e){let t;try{if(t=lg&&(self.URL||self.webkitURL).createObjectURL(lg),!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(cg),{type:`module`,name:e?.name})}}var dg="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})}};",fg=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,dg],{type:`text/javascript;charset=utf-8`});function pg(e){let t;try{if(t=fg&&(self.URL||self.webkitURL).createObjectURL(fg),!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(dg),{type:`module`,name:e?.name})}}jt(),$s();var mg=5e4,hg=2e5,gg=2e6,_g=1<<19,vg=4e7,yg=1.5*1024**3,bg=256*1024*1024,xg=vt(`scene`),Sg=e=>Array.isArray(e)?e:[e],Cg=e=>Sg(e).reduce((e,t)=>e+t.byteLength,0),wg=64*1024*1024;async function Tg(e,t,n){for(let r of Sg(n))await e.writeAt(t,r),t+=r.byteLength}function Eg(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 Dg=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(oi(),6),maxSceneBytes:Km,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,sceneCache:!0,sceneCacheMinBuildMs:ag,...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 Fr({issues:this.config.issues}),this.bvhBuilder=new Up,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 kh({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Lh,this.tlasBuilder=new zm,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?xg.debug(e):xg.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Xm(n);if(this._progressive&&(r.total-=r.bvh),this._streaming){let t=yg+Eg(e)*(W.FLOATS_PER_TRIANGLE*4+44);r.total-=Math.max(0,r.triangles-t)}let i={...n,estimate:r,safeBytes:Gm,maxBytes:t,fits:r.total<=Gm};if(this.memoryPreflight=i,r.total<1610612736)return i;if(xg.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(Gm)} 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:Gm}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=Zm(Math.ceil(t*Jm),{shared:yn});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?Cg(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;xg.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,xn(e=>this.memory.alloc(e));let r=new Rh(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>vg,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=kr(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=>xg.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,xg.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._disposeGeometrySpill(),xn(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 xg.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=Cn.lazy(o,W.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await mr.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await mr.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 br.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);jm.rootAABB(Sg(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Cg(r),f.blasAt.set(e,a),n.nodeCount=Cg(r)/64,n.bvhData=null,this._queueSpill(f,()=>Tg(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>bg&&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>yg&&(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),xg.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 jm,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(_,zm.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??Cg(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(zm.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(Cn.lazy(O,16,Float32Array,void 0,yn));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 qh(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 Sg(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;xg.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 xg.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>=hg&&Cm(e.count)}async _buildLargeBLAS(e,t){if(e.count>gg)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 bm(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 $h(n,e.start,e.count,_g,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(oi(),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),jm.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{...rg(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:${ig}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=zu(Xs().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await Gh(r,this._blasKey);if(!i)return null;let a=e=>(xg.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 Wh(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 Jh(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},xg.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=zu(Xs().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 Wh(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 Kh(t,r,{index:{v:2,tlasNodeCount:n.tlasNodeCount,totalNodes:n.totalNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&xg.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 mr.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await mr.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(Sg(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Cg(a),e.blasAt.set(t,o),r.nodeCount=Cg(a)/64,r.bvhData=null,this._queueSpill(e,()=>Tg(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+=wg)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(wg,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 mr.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);Ap(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=ci(fm);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 xg.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 xg.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){xg.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 xg.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=Cn.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||=ci(ug),!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 lm;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?(Dm(s,c,e*16,r),n.setPlacementMatrix(t,r)):l?(Dm(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||zm.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)):xg.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):(xg.error(`failed to get BVH data`),!1)):(xg.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 mr.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await mr.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 xg.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=kr(e),xg.info(`read ${J.mb(r)} of scene geometry back from disk in ${J.ms(performance.now()-n)}`),t.error&&xg.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>=mg&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return zm.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,xg.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=ci(pg);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 Cn?e:Cn.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 Cn?e:Cn.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=Om(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||Om(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){xg.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{xg.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,ci(fm))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){xg.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}},Og=[[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]],kg=[[-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]],Ag=[[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 jg(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=Og[i],o=kg[i],s=Ag[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 Mg=1/(4*Math.PI);function Ng(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]=jg(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Vr(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var Pg=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=Ng(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=Ng(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=Ng(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Mg,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=Ng(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*Mg,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 Fg=1<<18,Ig=vt(`pathtracer`),Lg=100,Rg=4,zg=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 Dg,this.lightSerializer=new Pg,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 on(a,o),this._defineUniformGetters(),this.materialData=new $r(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 Qu(this.scene,this.uniforms,this.renderer),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new mp,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._writeLightList(`directional`,this.directionalLightsData,this.numDirectionalLights),this._writeLightList(`area`,this.areaLightsData,this.numAreaLights),this._writeLightList(`point`,this.pointLightsData,this.numPointLights),this._writeLightList(`spot`,this.spotLightsData,this.numSpotLights)}_writeLightList(e,t,n){let r=nn[e],i=this[`${e}LightsBufferNode`],a=t?Math.floor(t.length/r):0,o=a*r;o>i.array.length&&(i.array=new Float32Array(an(e,a)*r),this._lightBufferRealloc=!0),o>0&&i.array.set(t.subarray(0,o)),i.array.fill(0,o),n.value=a}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),this._accumulationLockstep=!!this._lockstep}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<Lg}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}),Ig.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=Fg;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/Rg),Ig.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){Ig.error(`triangle data required`);return}if(!this.bvhStorageNode){Ig.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._accumulationLockstep=!1),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(),Ig.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(),Ig.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{Ig.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(),Ig.debug(`material rebuild complete`)}catch(e){Ig.error(`material rebuild failed:`,e);try{Ig.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Ig.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 Bg=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},Vg=65535,Hg={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},Ug=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,Bg.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(){Ca(this._renderer,this._countersAttr),Ca(this._renderer,this._bounceCountsAttr),Ca(this._renderer,this._attrA),Ca(this._renderer,this._attrB),Ca(this._renderer,this._sortAttr),Ca(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}},Wg={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Gg={[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 Kg(e){return(Wg[e.format]??4)*(Gg[e.type]??4)}function qg(e){return e?.gpuByteLength??e?.array?.byteLength??0}function Jg(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*Kg(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*Kg(e)}var Yg=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*Kg(e));return a}return this._isResident(e)?Jg(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 Xg=vt(`wavefront`),Zg=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);Xg.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=>Xg.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()}},Qg=(0,n.int)(Se.equirectangular),$g=(0,n.int)(Se.orthographic),e_=e=>e.equal($g);function t_(){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 n_=(e,t,n,r)=>({origin:i_(e,t,n,r.cameraProjection),direction:a_(e,t,n,r.cameraProjection,r.panoLonRange,r.panoLatRange,r.panoLevelHorizon)}),r_=(e,t,n,r,i)=>{let{origin:a,direction:o}=n_(e,n,r,i);return a.add(o.mul(t))},i_=(0,n.Fn)(([e,t,r,i])=>{let a=(0,n.vec3)(t[3]).toVar();return(0,n.If)(e_(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}),a_=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal(Qg),()=>{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(e_(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}),o_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_])=>{let v=i_(e,r,i,a).toVar(),y=a_(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(Qg),s.y.sub(s.x).mul(.5),(0,n.select)(e_(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(Qg),()=>{C.assign(Yi({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)))}),mi({origin:b,direction:x})});function s_(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=mi.wrap(o_(O,E,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x));Ba(t,C,k.origin,(0,n.int)(0),(0,n.int)(0)),Va(t,C,k.direction,(0,n.uint)(Hg.ACTIVE)),Ha(t,C,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),Ua(t,C,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(A,()=>{Ma(i,C,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),so(t,C,(0,n.vec3)(1))}),to(t,C,(0,n.uint)(0),(0,n.uint)(T),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),Qa(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 c_=32,l_=4096,u_=4,d_=1e8,f_=()=>(0,n.array)(`int`,c_).toVar(),p_=e=>(0,n.int)((0,n.uint)(e.bitNot()).shiftRight((0,n.uint)(4))),m_=e=>(0,n.int)((0,n.uint)(e.bitNot()).bitAnd((0,n.uint)(15))),h_=e=>e?e=>e.shiftRight((0,n.uint)(30)).equal((0,n.uint)(1)):e=>e.greaterThanEqual((0,n.uint)(Ue)),g_=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)(d_).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},__=(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)),v_=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),y_=(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.
|
|
@@ -1028,7 +1028,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1028
1028
|
let linear = rayzee_source( gid.x, srcY );
|
|
1029
1029
|
rayzee_store( gid.y * params.width + gid.x, linear, rayzee_tone_map( linear.rgb, params.mode, params.exposure, params.saturation ) );
|
|
1030
1030
|
}
|
|
1031
|
-
`,Tx=32,Ex=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(Tx),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}=vx();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:wx(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*Cx[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:Tx,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*Cx[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}}}}));Dx();var Ox=512,kx=4<<20,Ax=15e8,jx=new TextDecoder;function Mx(e){return e.length>=2&&e[0]===31&&e[1]===139}function Nx(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Px(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function Fx(e){return Mx(e)?`gzip`:Nx(e)?`zip`:Px(e)?`tar`:null}function Ix(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return jx.decode(e.subarray(t,r))}function Lx(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=Ix(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function Rx(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function zx(e){let t=jx.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var Bx=e=>e+(Ox-e%Ox)%Ox,Vx=e=>e===`L`||e===`x`||e===`X`;function Hx(e){let t=Ix(e,345,155),n=Ix(e,0,100);return{type:String.fromCharCode(e[156]||48),size:Lx(e,124,12),name:t?`${t}/${n}`:n}}function Ux(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:Rx(t)||null}function Wx(e){for(let t=0;t<Ox;t++)if(e[t]!==0)return!1;return!0}var Gx=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Ax,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(Ox),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(Ox-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===Ox&&(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<Ox;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=Hx(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=Bx(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,Vx(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=Ux(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=Ix(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=zx(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 Kx(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 qx(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function qx(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=kx){let r=Math.min(n+kx,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+=kx){let i=Math.min(r+kx,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function Jx(e,t={}){let{onProgress:n,...r}=t,i=new Gx(r),a=0,o=0;return await Kx(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 Yx=1<<20;async function Xx(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,Yx));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+Ox<=n;){let e=await l(s,Ox);if(Wx(e))break;let{type:n,size:i,name:a}=Hx(e),u=o??a;o=null;let d=s+Ox;if(Vx(n)){let e=await l(d,i);o=n===`L`?Ix(e,0,e.length):zx(e)}else{let e=Ux(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+Bx(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function Zx(){let e=new Gx({retain:()=>!1});return{push:t=>e.push(t),finish:()=>(e.end(),e.listing.filter(e=>e.offset!==void 0))}}async function Qx(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 Xx(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 Gx({...a});await qx(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 $x(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=Rx(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 eS(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 tS=101010256,nS=117853008,rS=101075792,iS=33639248,aS=67324752,oS=65557,sS=new TextDecoder;async function cS(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function lS(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function uS(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function dS(e){let t=e.size,n=await cS(e,Math.max(0,t-oS-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===tS){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)!==nS)throw Error(`zip: ZIP64 locator missing`);let n=lS(r,t+8),c=new DataView((await cS(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==rS)throw Error(`zip: ZIP64 end record missing`);a=lS(c,32),o=lS(c,40),s=lS(c,48)}let c=await cS(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)!==iS)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?sS.decode(f):uS(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=lS(l,t),t+=8),n===4294967295&&(n=lS(l,t),t+=8),s===4294967295&&(s=lS(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 fS(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await cS(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==aS)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function pS(e,t){let n=await fS(e,t),r=await cS(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 mS(e,{filter:t=null}={}){let n=await dS(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?pS(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await pS(e,n)]);let i=await fS(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 hS=1,gS=3;async function _S(e,t){return`${e}:${Vn(await Bn(t))}`}async function vS(e,{storage:t,label:n=e.name,onProgress:r=null}){if(!t||typeof DecompressionStream>`u`)return null;let i=t.area(qn.ARCHIVES),a=await _S(`gunzip`,e),o=await i.open(a),s=!!o;if(!o){let s=await i.create(a,{label:n,expectedBytes:e.size*gS});if(!s)return null;let c=Zx(),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:hS,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:qn.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!==hS?(o.release(),null):{file:c,index:l,release:()=>o.release(),cached:s}}async function yS(e,t){if(!t)return null;let n=await t.area(qn.ARCHIVES).open(await _S(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===hS?e:null}finally{n.release()}}async function bS(e,t,n){if(!t||!n)return!1;let r=await t.area(qn.ARCHIVES).create(await _S(`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 xS=`__rayzeeArchivePath`,SS=`__rayzeeArchiveLoader`,CS=64,wS=32<<20,TS=64<<20,ES={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},DS=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],OS=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],kS=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}};function AS(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 jS(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[xS],delete t[SS],t}catch{throw new kS(`${t}: userData is not plain JSON`)}}var MS=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/CS)*CS;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 NS(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new kS(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function PS(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new kS(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=NS(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?NS(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:jS(e.userData,n)}}function FS(e,t){let n={uuid:e.uuid,userData:jS(e.userData,`texture ${e.uuid}`)};for(let t of DS)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[xS];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 kS(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function IS(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 LS(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function RS(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new MS,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=AS(e);if(!n)throw new kS(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:jS(e.userData,`${n} "${e.name}"`)};for(let t of OS)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),LS(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=>PS(e,a)),textures:[...l.values()].map(e=>FS(e,a)),materials:[...c.values()].map(e=>IS(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 zS(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+=wS)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+wS)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function BS(e){let t=ES[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function VS(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=BS(s),l=r+o;if(o>TS){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+TS)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function HS(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 US(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function WS(e,t){for(let n of DS)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 GS(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await VS(t,HS(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[xS]=t.path,e.userData[SS]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);WS(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,US(i,r));t.index&&e.setIndex(US(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 OS)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 KS=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function qS(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):KS.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function JS(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 YS({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 XS(e,t){return ai().decodeImage(t===`image/png`?JS(e):e,t)}async function ZS(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}async function QS(e,t=qS({uri:e})){let n=YS(await XS(await ZS(e),t));return n.flipY=!0,n}function $S(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=qS(n),a=n.uri??`bufferView ${n.bufferView}`,o=(n.bufferView===void 0?ZS(this.options.manager.resolveURL(r.LoaderUtils.resolveURL(n.uri,this.options.path))):this.getDependency(`bufferView`,n.bufferView).then(e=>new Uint8Array(e))).then(e=>XS(e,i)).then(e=>{let t=YS(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 eC=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer);function tC(e){e&&eC(e)&&e.buffer.transfer(0)}function nC(e,t){let n=e.constructor;if(eC(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 rC={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},iC=9,aC=10,oC=12,sC=13,cC=32,lC=34,uC=35,dC=43,fC=45,pC=46,mC=48,hC=57,gC=91,_C=93,vC=69,yC=101,bC=e=>e===cC||e===iC||e===aC||e===sC||e===oC,xC=e=>e>=mC&&e<=hC,SC=15,CC=22,wC=(()=>{let e=new Float64Array(CC+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),TC=new TextDecoder;function EC(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 TC.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var DC=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&&bC(e[t]);)t++;if(t<n&&e[t]===uC){for(;t<n&&e[t]!==aC;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===gC)return this.i=t+1,{type:rC.LBRACKET};if(r===_C)return this.i=t+1,{type:rC.RBRACKET};if(r===lC){let r=++t;for(;t<n&&e[t]!==lC;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:rC.STRING,value:EC(e,r,t)}}if(xC(r)||r===pC&&xC(e[t+1])||(r===fC||r===dC)&&(xC(e[t+1])||e[t+1]===pC&&xC(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(bC(n)||n===lC||n===gC||n===_C||n===uC)break;t++}return this.i=t,{type:rC.WORD,value:EC(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===fC?(i=!0,r++):t[r]===dC&&r++;let a=0,o=0,s=0;for(;r<n&&xC(t[r]);)a=a*10+(t[r]-mC),o++,r++;if(r<n&&t[r]===pC)for(r++;r<n&&xC(t[r]);)a=a*10+(t[r]-mC),o++,s++,r++;let c=0;if(r<n&&(t[r]===yC||t[r]===vC)){let e=r+1,i=!1;if(e<n&&(t[e]===fC||t[e]===dC)&&(i=t[e]===fC,e++),e<n&&xC(t[e])){let a=0;for(;e<n&&xC(t[e]);)a=a*10+(t[e]-mC),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${EC(t,e,r)}"`);let l=c-s;if(!(o<=SC&&l>=-CC&&l<=CC)){let n=Number(EC(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${EC(t,e,r)}"`);return{type:rC.NUMBER,value:n}}let u=l===0?a:l>0?a*wC[l]:a/wC[-l];return i&&(u=-u),{type:rC.NUMBER,value:u}}};function OC(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function kC(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 AC(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 jC(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 MC(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function NC(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function PC(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 FC(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function IC(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 LC(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function RC(e,t,n){let r=LC(FC(t,e)),i=LC(IC(LC(n),r)),a=IC(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 zC(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 OC();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 BC=8,VC=1,HC=2,UC=3,WC=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]);function GC(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var KC={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},qC=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=OC(),this.ctmEnd=null,this.activeTransform=UC,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 DC(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=nC(e.matrices,e.count*16),e.matricesEnd&&=nC(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=nC(n.matrices,e),n.matricesEnd&&=nC(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||GC(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===UC&&this.ctmEnd===null){this.ctm=jC(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&HC?jC(t,e):t,this.activeTransform&VC&&(this.ctm=jC(this.ctm,e))}_setCTM(e){if(this.activeTransform===UC){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&HC?e:t,this.activeTransform&VC&&(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!==rC.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!==rC.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===rC.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==rC.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===rC.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===rC.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==rC.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===rC.NUMBER){let t=[];for(;n()&&t.length<BC;){let e=this._next();if(e.type!==rC.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(KC[e]||Float64Array)(BC*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==rC.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=nC(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:nC(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!==rC.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===rC.NUMBER||e.type===rC.STRING)return e.value;if(e.type===rC.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!==rC.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);WC.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(OC());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(MC(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(NC(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(PC(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=RC([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(zC(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:zC(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=zC(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=OC(),this.ctmEnd=null,this.activeTransform=UC,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=VC:e===`EndTime`?this.activeTransform=HC:e===`All`?this.activeTransform=UC: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===rC.STRING&&this._next(),this._peek()&&this._peek().type===rC.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&&!GC(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&&!GC(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=jC(zC(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 DC(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!==UC||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===UC&&GC(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=zC(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=jC(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===rC.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===rC.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}`))}},JC={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]},YC=[.92,.92,.92];function XC(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 ZC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function QC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function $C(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:XC(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=ew(i.value[0]);return e&&JC[e]?{rgb:JC[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 ew(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(JC))if(e.toLowerCase().includes(t))return t;return null}function tw(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=ZC(e,`uroughness`,null),r=ZC(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function nw(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 $C(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await $C(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 $C(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await $C(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 $C(i,`eta`,t,YC)).rgb||YC:JC.cu);a.metalness=1,a.roughness=tw(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=ZC(i,`eta`,1.5),a.roughness=tw(i,0),a.thickness=n===`thindielectric`?0:ZC(i,`thickness`,0);break;case`coateddiffuse`:s(await $C(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=tw(i,0);break;case`diffusetransmission`:{let e=await $C(i,`transmittance`,t,[.25,.25,.25]);s(await $C(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,ZC(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([nw(o,t),nw(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 $C(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 rw(e){return e===3?3/16:3/(8*e)}function iw(e){return 1/(e+3/(8*rw(e)))}function aw(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 ow(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 sw(e,t){let n=e.length/3,r=aw(n,t),i=r.edgeV0.length,a=ow(e,r,n,rw,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 cw(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=sw(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=ow(i,aw(s,a),s,iw,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function lw(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 uw=(()=>{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 dw(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 fw(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?zC(t):null,c=e.srgb?uw: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]=lw(f,p,m);dw(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 pw=2;function mw(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 hw(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 gw(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 _w(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 vw(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function yw(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?mw(c,i):hw(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 bw(e,t,n){let r=vw(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++)yw(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function xw(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 Sw(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++)yw(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,xw(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(xw(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(xw(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 Cw(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??pw)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=bw(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?Sw(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],gw(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&&_w(h,[0,1,0],g),gw(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],_w(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]);_w(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&&_w(h,[0,1,0],g),gw(g),y=!0}if(d&&d[b]!==e)continue;_w(h,g,_),gw(_);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:nC(S,C)}}var ww=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],Tw=4096;function Ew(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 Dw(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return nC(e,n)}function Ow(e){return e instanceof Float32Array?e:Float32Array.from(e)}var kw=1e3,Aw=45e6,jw=6e6,Mw=6e7,Nw=8e6,Pw=256,Fw=4096,Iw=5e5,Lw=2,Rw={flat:1,ribbon:1,cylinder:2},zw=.05;function Bw(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 Vw(e,t){let n=Math.min(e.width,Tw),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 Hw(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 Uw=class{constructor(e={}){this.maxTriangles=e.maxTriangles??Aw,this.maxPlacements=e.maxPlacements??jw,this.mergeShapesAbove=e.mergeShapesAbove??Pw,this.curveSteps=e.curveSteps??Lw,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??zw,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=QC(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(QC(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<=Fw){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(QC(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)AC(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?jC(ww,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<kw&&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<=Fw){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]);tC(n.matrices),tC(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=>Bw(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);tC(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?jC(ww,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?jC(ww,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?jC(ww,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<kw&&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?jC(ww,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(QC(e.params,`filename`,null)))){for(let e in t.attributes)tC(t.attributes[e].array);tC(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&tC(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=zC(m),g=p.vertexCount;p.positions=Dw(p.positions,(g+u)*3),p.normals=Dw(p.normals,(g+u)*3),c&&(p.uvs=Dw(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=Dw(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>=Iw?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(nC(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(nC(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(nC(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(nC(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<kw&&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(Ow(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(Ow(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(Ow(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(Ew(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(ZC(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=QC(e,`type`,`flat`),a=ZC(e,`width`,1),o=Cw({P:t,basis:QC(e,`basis`,`bezier`),width0:ZC(e,`width0`,a),width1:ZC(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??Rw[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(ZC(e,`levels`,3)))),{positions:a,indices:o,levels:s}=cw(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=QC(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(ZC(e,`radius`,1),48,32)}_disk(e){let t=ZC(e,`radius`,1),n=ZC(e,`innerradius`,0),i=ZC(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 nw(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 $C(t.params,`L`,n,[1,1,1]),i=ZC(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=QC(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 Hw(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)),kC(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=ZC(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=Vw(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}=fw(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=ZC(t.params,`scale`,1),i=QC(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 $C(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)`)}},Ww=1e3,Gw=2048,Kw=1e5;function qw(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,Ww).map(([e,t])=>({path:t,number:e}))}function Jw(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 Yw(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?`#`+Jw(i):i.join(`,`)};`}return t}var Xw=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}|${Yw(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+`:`+Yw(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+`:`+Yw(e.params)),t}};function Zw(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&&!Qw(e,r,i,t,r,a,n)&&eT(e,r,i,t,r,a,n),n}function Qw(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,Gw),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)),$w(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function $w(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 eT(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 tT(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function nT(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 rT(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!tT(t,0,t,e))return!1;return!0}var iT=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 Xw(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?Zw(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&&!tT(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&&tT(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=nT(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=nT(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!rT(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<Kw){let n=nT(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 ${Kw.toLocaleString()} left static`),r}};function aT(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;tT(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=Kw?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 oT=2e6,sT=new TextDecoder;function cT(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 lT(e,t){return!e||t.startsWith(`/`)?cT(t):cT(`${e}/${t}`)}var uT=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=cT(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(lT(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(lT(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),tC(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=cT(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 dT(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 fT=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),pT=4*1024*1024,mT=fT(`WorldBegin`),hT=[fT(`Include`),fT(`Import`)];function gT(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 _T(e){for(let t=dT(e,mT);t>=0;t=dT(e,mT,t+1))if(gT(e,t))return!0;return!1}function vT(e,t){for(let n of hT)for(let r=dT(e,n);r>=0;r=dT(e,n,r+1)){if(!gT(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=sT.decode(e.subarray(a,i));t.add(cT(o).toLowerCase().split(`/`).pop())}}function yT(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,_T(t)),vT(t,n)}return bT(t,r,n)}function bT(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 xT(e){return yT(e)[0]||null}async function ST(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,_T(t)),vT(t,r),t.length>=pT&&(a=!0),o.lazy&&(e.release(o),tC(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,pT)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return bT(t.map(e=>e.key),a,i)}async function CT(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new uT(t,n),c=[],l=await ST(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 qC({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?qw(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>oT)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=aT(e);else{let t=new iT(m.map(e=>(e.number-m[0].number)/30),wT(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=aT(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 Uw({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 wT(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 TT=[`sourceFile`,`url`,`file`];function ET(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 DT(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function OT(e){let t=ET(e);if(!t)return null;let n=ET(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function kT(e){let t=ET(e);if(!t)return null;let n=TT.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=DT(t.rotation),i=DT(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function AT(e){let t=OT(e);if(!t)return null;let n=kT(t.environment);return n?{environment:n}:null}function jT(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=AT(e);if(t)return t}return null}$s();var MT={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`}},NT=/\.(usd|usda|usdc)$/i,PT=/\.(png|jpg|jpeg|avif)$/i,FT=3e4,IT=4e9;function LT(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 RT=683;function zT(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 BT=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 px(t,{downloads:this.downloads,key:i,policy:a,name:ox(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 ux(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 MT[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=ox(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`,Vn(await Bn(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 Vu(r,Vn(await Bn(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)&&Vu(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):ai().decodeImage?(l=await QS(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=Fx(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 Jx(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await yS(e,this.storage))?.listing??await Xx(e,{onProgress:n}):(await dS(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=eS(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 vS(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=Fx(await this._readHead(e)),c=this.storage?Vn(await Bn(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(xT(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(qn.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 uT({},t),c=await GS(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(qn.SCENES);if(!r)return;let i;try{i=RS(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 kS?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};sg(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(qn.SCENES);!t||!n||!sg(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 zS(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?$x(o):null,c;if(a)c=await mS(e,{filter:s});else{let t=i??await yS(e,this.storage);c=await Qx(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||bS(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=IT){if(n<r)return;let{root:i,elements:a}=eS(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},hn.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 Jx(e,{filter:a.length?$x(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}=eS(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},hn.WARNING),i}if(l){let e=$x(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},hn.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[xS]=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 Vu(e,`bytes:${await zn(r)}`),e.userData[xS]=t,e.userData[SS]=`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:${ig}`,`${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 CT({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},hn.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(MT[n]&&MT[n].type===`model`)return NT.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=>NT.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&&(NT.test(e)||PT.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(NT,``)===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=jT(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),FT))]);return clearTimeout(r),i||this._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${FT}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}=Xs(),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),ai().decodeImage&&i.register(e=>$S(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=jT(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=jT(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 Rh(`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*=zT(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/RT,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=RT,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*zT(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=LT(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(MT))r.type===e&&(t[n]=r);return t}return MT}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}},VT={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},HT=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 UT(e=1,t=1){let n={...VT,defaultView:null},r={...VT,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 HT(r);return r}var WT=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}},GT=8,KT=4,qT=.25,JT=r.MathUtils.degToRad(89),YT=.25,XT={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]},ZT=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,QT=e=>e.shiftKey?KT:e.altKey?qT:1,$T={type:`change`},eE={type:`start`},tE=new r.Vector3,nE=new r.Vector3,rE=new r.Vector3,iE=new r.Vector3,aE=new r.Quaternion,oE=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/GT,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)/GT}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]=XT[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return nE.set(1,0,0).applyQuaternion(i.quaternion),tE.crossVectors(i.up,nE).normalize(),nE.crossVectors(tE,i.up),rE.set(0,0,0).addScaledVector(nE,t).addScaledVector(tE,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(rE),this.orbit.target.add(rE),i.updateMatrixWorld(),this.dispatchEvent($T),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,YT);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(aE.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(tE);let s=Math.asin(r.MathUtils.clamp(tE.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-JT,JT);n.quaternion.multiply(aE.setFromAxisAngle(iE.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(tE),a),this.dispatchEvent($T)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(ZT))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=QT(e),XT[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(eE))))}}_onKeyUp(e){this._factor=QT(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 sE=Object.freeze(new r.Vector3(1,1,1)),cE=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,lE=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new WT(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 oE(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??sE),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:cE(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 cE(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:Ur(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=Wr(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=Wr(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=Ub(l,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?Ub(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()}},uE=.001,dE=2,fE=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),pE=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+dE: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,...mE(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,mE(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]+uE):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:fE(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:fE(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:fE(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:fE(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 mE({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}R();var hE=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new pE(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})}},gE=`__rayzeeUserLight`,_E={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},vE=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[gE]=!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?.[gE]: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:Ur(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=_E[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=Wr(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}},yE=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=>bE(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}),u=performance.now();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),performance.now()-u>16&&(await new Promise(e=>setTimeout(e,0)),u=performance.now())}let d=new r.DataArrayTexture(s,i,a,o);d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d.format=r.RGBAFormat,d.type=r.UnsignedByteType,d.generateMipmaps=!1,d.needsUpdate=!0;let f=this.texture;return this.texture=d,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=d,this.pathTracer.shaderBuilder?.updateGoboMaps?.(d),f?.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:xE(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 bE(e){let t=await px(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 xE(e){return Math.max(0,Math.min(1,e))}function SE(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
|
|
1031
|
+
`,Tx=32,Ex=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(Tx),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}=vx();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:wx(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*Cx[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:Tx,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*Cx[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}}}}));Dx();var Ox=512,kx=4<<20,Ax=15e8,jx=new TextDecoder;function Mx(e){return e.length>=2&&e[0]===31&&e[1]===139}function Nx(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Px(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function Fx(e){return Mx(e)?`gzip`:Nx(e)?`zip`:Px(e)?`tar`:null}function Ix(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return jx.decode(e.subarray(t,r))}function Lx(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=Ix(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function Rx(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function zx(e){let t=jx.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var Bx=e=>e+(Ox-e%Ox)%Ox,Vx=e=>e===`L`||e===`x`||e===`X`;function Hx(e){let t=Ix(e,345,155),n=Ix(e,0,100);return{type:String.fromCharCode(e[156]||48),size:Lx(e,124,12),name:t?`${t}/${n}`:n}}function Ux(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:Rx(t)||null}function Wx(e){for(let t=0;t<Ox;t++)if(e[t]!==0)return!1;return!0}var Gx=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Ax,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(Ox),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(Ox-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===Ox&&(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<Ox;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=Hx(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=Bx(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,Vx(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=Ux(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=Ix(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=zx(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 Kx(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 qx(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function qx(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=kx){let r=Math.min(n+kx,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+=kx){let i=Math.min(r+kx,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function Jx(e,t={}){let{onProgress:n,...r}=t,i=new Gx(r),a=0,o=0;return await Kx(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 Yx=1<<20;async function Xx(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,Yx));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+Ox<=n;){let e=await l(s,Ox);if(Wx(e))break;let{type:n,size:i,name:a}=Hx(e),u=o??a;o=null;let d=s+Ox;if(Vx(n)){let e=await l(d,i);o=n===`L`?Ix(e,0,e.length):zx(e)}else{let e=Ux(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+Bx(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function Zx(){let e=new Gx({retain:()=>!1});return{push:t=>e.push(t),finish:()=>(e.end(),e.listing.filter(e=>e.offset!==void 0))}}async function Qx(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 Xx(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 Gx({...a});await qx(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 $x(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=Rx(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 eS(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 tS=101010256,nS=117853008,rS=101075792,iS=33639248,aS=67324752,oS=65557,sS=new TextDecoder;async function cS(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function lS(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function uS(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function dS(e){let t=e.size,n=await cS(e,Math.max(0,t-oS-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===tS){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)!==nS)throw Error(`zip: ZIP64 locator missing`);let n=lS(r,t+8),c=new DataView((await cS(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==rS)throw Error(`zip: ZIP64 end record missing`);a=lS(c,32),o=lS(c,40),s=lS(c,48)}let c=await cS(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)!==iS)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?sS.decode(f):uS(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=lS(l,t),t+=8),n===4294967295&&(n=lS(l,t),t+=8),s===4294967295&&(s=lS(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 fS(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await cS(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==aS)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function pS(e,t){let n=await fS(e,t),r=await cS(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 mS(e,{filter:t=null}={}){let n=await dS(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?pS(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await pS(e,n)]);let i=await fS(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 hS=1,gS=3;async function _S(e,t){return`${e}:${Vn(await Bn(t))}`}async function vS(e,{storage:t,label:n=e.name,onProgress:r=null}){if(!t||typeof DecompressionStream>`u`)return null;let i=t.area(qn.ARCHIVES),a=await _S(`gunzip`,e),o=await i.open(a),s=!!o;if(!o){let s=await i.create(a,{label:n,expectedBytes:e.size*gS});if(!s)return null;let c=Zx(),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:hS,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:qn.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!==hS?(o.release(),null):{file:c,index:l,release:()=>o.release(),cached:s}}async function yS(e,t){if(!t)return null;let n=await t.area(qn.ARCHIVES).open(await _S(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===hS?e:null}finally{n.release()}}async function bS(e,t,n){if(!t||!n)return!1;let r=await t.area(qn.ARCHIVES).create(await _S(`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 xS=`__rayzeeArchivePath`,SS=`__rayzeeArchiveLoader`,CS=64,wS=32<<20,TS=64<<20,ES={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},DS=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],OS=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],kS=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}};function AS(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 jS(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[xS],delete t[SS],t}catch{throw new kS(`${t}: userData is not plain JSON`)}}var MS=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/CS)*CS;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 NS(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new kS(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function PS(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new kS(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=NS(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?NS(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:jS(e.userData,n)}}function FS(e,t){let n={uuid:e.uuid,userData:jS(e.userData,`texture ${e.uuid}`)};for(let t of DS)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[xS];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 kS(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function IS(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 LS(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function RS(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new MS,o=[],s=new Map,c=new Map,l=new Map,u=(e,t)=>{let n=AS(e);if(!n)throw new kS(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:jS(e.userData,`${n} "${e.name}"`)};for(let t of OS)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),LS(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=>PS(e,a)),textures:[...l.values()].map(e=>FS(e,a)),materials:[...c.values()].map(e=>IS(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 zS(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+=wS)await e.write(`data.bin`,a.subarray(t,Math.min(a.length,t+wS)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),await e.writeJSON(`graph.json`,t)}function BS(e){let t=ES[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function VS(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=BS(s),l=r+o;if(o>TS){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+TS)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function HS(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 US(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function WS(e,t){for(let n of DS)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 GS(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await VS(t,HS(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[xS]=t.path,e.userData[SS]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);WS(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,US(i,r));t.index&&e.setIndex(US(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 OS)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 KS=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function qS(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):KS.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function JS(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 YS({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 XS(e,t){return ai().decodeImage(t===`image/png`?JS(e):e,t)}async function ZS(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}async function QS(e,t=qS({uri:e})){let n=YS(await XS(await ZS(e),t));return n.flipY=!0,n}function $S(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=qS(n),a=n.uri??`bufferView ${n.bufferView}`,o=(n.bufferView===void 0?ZS(this.options.manager.resolveURL(r.LoaderUtils.resolveURL(n.uri,this.options.path))):this.getDependency(`bufferView`,n.bufferView).then(e=>new Uint8Array(e))).then(e=>XS(e,i)).then(e=>{let t=YS(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 eC=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer);function tC(e){e&&eC(e)&&e.buffer.transfer(0)}function nC(e,t){let n=e.constructor;if(eC(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 rC={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},iC=9,aC=10,oC=12,sC=13,cC=32,lC=34,uC=35,dC=43,fC=45,pC=46,mC=48,hC=57,gC=91,_C=93,vC=69,yC=101,bC=e=>e===cC||e===iC||e===aC||e===sC||e===oC,xC=e=>e>=mC&&e<=hC,SC=15,CC=22,wC=(()=>{let e=new Float64Array(CC+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),TC=new TextDecoder;function EC(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 TC.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var DC=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&&bC(e[t]);)t++;if(t<n&&e[t]===uC){for(;t<n&&e[t]!==aC;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===gC)return this.i=t+1,{type:rC.LBRACKET};if(r===_C)return this.i=t+1,{type:rC.RBRACKET};if(r===lC){let r=++t;for(;t<n&&e[t]!==lC;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:rC.STRING,value:EC(e,r,t)}}if(xC(r)||r===pC&&xC(e[t+1])||(r===fC||r===dC)&&(xC(e[t+1])||e[t+1]===pC&&xC(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(bC(n)||n===lC||n===gC||n===_C||n===uC)break;t++}return this.i=t,{type:rC.WORD,value:EC(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===fC?(i=!0,r++):t[r]===dC&&r++;let a=0,o=0,s=0;for(;r<n&&xC(t[r]);)a=a*10+(t[r]-mC),o++,r++;if(r<n&&t[r]===pC)for(r++;r<n&&xC(t[r]);)a=a*10+(t[r]-mC),o++,s++,r++;let c=0;if(r<n&&(t[r]===yC||t[r]===vC)){let e=r+1,i=!1;if(e<n&&(t[e]===fC||t[e]===dC)&&(i=t[e]===fC,e++),e<n&&xC(t[e])){let a=0;for(;e<n&&xC(t[e]);)a=a*10+(t[e]-mC),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${EC(t,e,r)}"`);let l=c-s;if(!(o<=SC&&l>=-CC&&l<=CC)){let n=Number(EC(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${EC(t,e,r)}"`);return{type:rC.NUMBER,value:n}}let u=l===0?a:l>0?a*wC[l]:a/wC[-l];return i&&(u=-u),{type:rC.NUMBER,value:u}}};function OC(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function kC(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 AC(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 jC(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 MC(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function NC(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function PC(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 FC(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function IC(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 LC(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function RC(e,t,n){let r=LC(FC(t,e)),i=LC(IC(LC(n),r)),a=IC(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 zC(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 OC();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 BC=8,VC=1,HC=2,UC=3,WC=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]);function GC(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var KC={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},qC=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=OC(),this.ctmEnd=null,this.activeTransform=UC,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 DC(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=nC(e.matrices,e.count*16),e.matricesEnd&&=nC(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=nC(n.matrices,e),n.matricesEnd&&=nC(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||GC(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===UC&&this.ctmEnd===null){this.ctm=jC(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&HC?jC(t,e):t,this.activeTransform&VC&&(this.ctm=jC(this.ctm,e))}_setCTM(e){if(this.activeTransform===UC){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&HC?e:t,this.activeTransform&VC&&(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!==rC.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!==rC.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===rC.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==rC.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===rC.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===rC.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==rC.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===rC.NUMBER){let t=[];for(;n()&&t.length<BC;){let e=this._next();if(e.type!==rC.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(KC[e]||Float64Array)(BC*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==rC.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=nC(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:nC(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!==rC.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===rC.NUMBER||e.type===rC.STRING)return e.value;if(e.type===rC.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!==rC.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);WC.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(OC());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(MC(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(NC(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(PC(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=RC([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(zC(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:zC(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=zC(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=OC(),this.ctmEnd=null,this.activeTransform=UC,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=VC:e===`EndTime`?this.activeTransform=HC:e===`All`?this.activeTransform=UC: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===rC.STRING&&this._next(),this._peek()&&this._peek().type===rC.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&&!GC(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&&!GC(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=jC(zC(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 DC(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!==UC||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===UC&&GC(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=zC(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=jC(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===rC.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===rC.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}`))}},JC={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]},YC=[.92,.92,.92];function XC(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 ZC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function QC(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function $C(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:XC(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=ew(i.value[0]);return e&&JC[e]?{rgb:JC[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 ew(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(JC))if(e.toLowerCase().includes(t))return t;return null}function tw(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=ZC(e,`uroughness`,null),r=ZC(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function nw(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 $C(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await $C(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 $C(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await $C(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 $C(i,`eta`,t,YC)).rgb||YC:JC.cu);a.metalness=1,a.roughness=tw(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=ZC(i,`eta`,1.5),a.roughness=tw(i,0),a.thickness=n===`thindielectric`?0:ZC(i,`thickness`,0);break;case`coateddiffuse`:s(await $C(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=tw(i,0);break;case`diffusetransmission`:{let e=await $C(i,`transmittance`,t,[.25,.25,.25]);s(await $C(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,ZC(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([nw(o,t),nw(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 $C(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 rw(e){return e===3?3/16:3/(8*e)}function iw(e){return 1/(e+3/(8*rw(e)))}function aw(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 ow(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 sw(e,t){let n=e.length/3,r=aw(n,t),i=r.edgeV0.length,a=ow(e,r,n,rw,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 cw(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=sw(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=ow(i,aw(s,a),s,iw,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function lw(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 uw=(()=>{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 dw(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 fw(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?zC(t):null,c=e.srgb?uw: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]=lw(f,p,m);dw(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 pw=2;function mw(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 hw(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 gw(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 _w(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 vw(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function yw(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?mw(c,i):hw(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 bw(e,t,n){let r=vw(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++)yw(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function xw(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 Sw(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++)yw(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,xw(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(xw(o,n,o,e,t)>p(n))return!1;for(let n=e;n<t;n++)if(xw(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 Cw(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??pw)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=bw(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=e.tolerance>0?Sw(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],gw(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&&_w(h,[0,1,0],g),gw(g)}else{if(a&&a.length>=3)g[0]=a[0],g[1]=a[1],g[2]=a[2],_w(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]);_w(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&&_w(h,[0,1,0],g),gw(g),y=!0}if(d&&d[b]!==e)continue;_w(h,g,_),gw(_);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:nC(S,C)}}var ww=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],Tw=4096;function Ew(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 Dw(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return nC(e,n)}function Ow(e){return e instanceof Float32Array?e:Float32Array.from(e)}var kw=1e3,Aw=45e6,jw=6e6,Mw=6e7,Nw=8e6,Pw=256,Fw=4096,Iw=5e5,Lw=2,Rw={flat:1,ribbon:1,cylinder:2},zw=.05;function Bw(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 Vw(e,t){let n=Math.min(e.width,Tw),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 Hw(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 Uw=class{constructor(e={}){this.maxTriangles=e.maxTriangles??Aw,this.maxPlacements=e.maxPlacements??jw,this.mergeShapesAbove=e.mergeShapesAbove??Pw,this.curveSteps=e.curveSteps??Lw,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??zw,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=QC(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(QC(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<=Fw){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(QC(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)AC(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?jC(ww,i):i))}m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=p,this.reportedMeshes+=p,this.report.length<kw&&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<=Fw){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]);tC(n.matrices),tC(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=>Bw(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);tC(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?jC(ww,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?jC(ww,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?jC(ww,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<kw&&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?jC(ww,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(QC(e.params,`filename`,null)))){for(let e in t.attributes)tC(t.attributes[e].array);tC(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&tC(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=zC(m),g=p.vertexCount;p.positions=Dw(p.positions,(g+u)*3),p.normals=Dw(p.normals,(g+u)*3),c&&(p.uvs=Dw(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=Dw(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>=Iw?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.Float32BufferAttribute(nC(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.Float32BufferAttribute(nC(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.Float32BufferAttribute(nC(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.Uint32BufferAttribute(nC(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<kw&&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(Ow(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(Ow(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(Ow(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(Ew(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(ZC(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=QC(e,`type`,`flat`),a=ZC(e,`width`,1),o=Cw({P:t,basis:QC(e,`basis`,`bezier`),width0:ZC(e,`width0`,a),width1:ZC(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??Rw[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(ZC(e,`levels`,3)))),{positions:a,indices:o,levels:s}=cw(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=QC(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(ZC(e,`radius`,1),48,32)}_disk(e){let t=ZC(e,`radius`,1),n=ZC(e,`innerradius`,0),i=ZC(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 nw(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 $C(t.params,`L`,n,[1,1,1]),i=ZC(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=QC(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 Hw(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)),kC(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=ZC(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=Vw(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}=fw(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=ZC(t.params,`scale`,1),i=QC(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 $C(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)`)}},Ww=1e3,Gw=2048,Kw=1e5;function qw(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,Ww).map(([e,t])=>({path:t,number:e}))}function Jw(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 Yw(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?`#`+Jw(i):i.join(`,`)};`}return t}var Xw=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}|${Yw(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+`:`+Yw(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+`:`+Yw(e.params)),t}};function Zw(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&&!Qw(e,r,i,t,r,a,n)&&eT(e,r,i,t,r,a,n),n}function Qw(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,Gw),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)),$w(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function $w(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 eT(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 tT(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function nT(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 rT(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!tT(t,0,t,e))return!1;return!0}var iT=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 Xw(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?Zw(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&&!tT(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&&tT(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=nT(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=nT(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!rT(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<Kw){let n=nT(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 ${Kw.toLocaleString()} left static`),r}};function aT(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;tT(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=Kw?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 oT=2e6,sT=new TextDecoder;function cT(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 lT(e,t){return!e||t.startsWith(`/`)?cT(t):cT(`${e}/${t}`)}var uT=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=cT(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(lT(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(lT(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),tC(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=cT(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 dT(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 fT=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),pT=4*1024*1024,mT=fT(`WorldBegin`),hT=[fT(`Include`),fT(`Import`)];function gT(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 _T(e){for(let t=dT(e,mT);t>=0;t=dT(e,mT,t+1))if(gT(e,t))return!0;return!1}function vT(e,t){for(let n of hT)for(let r=dT(e,n);r>=0;r=dT(e,n,r+1)){if(!gT(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=sT.decode(e.subarray(a,i));t.add(cT(o).toLowerCase().split(`/`).pop())}}function yT(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,_T(t)),vT(t,n)}return bT(t,r,n)}function bT(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 xT(e){return yT(e)[0]||null}async function ST(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,_T(t)),vT(t,r),t.length>=pT&&(a=!0),o.lazy&&(e.release(o),tC(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,pT)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return bT(t.map(e=>e.key),a,i)}async function CT(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new uT(t,n),c=[],l=await ST(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 qC({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?qw(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>oT)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=aT(e);else{let t=new iT(m.map(e=>(e.number-m[0].number)/30),wT(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=aT(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 Uw({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 wT(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 TT=[`sourceFile`,`url`,`file`];function ET(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 DT(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function OT(e){let t=ET(e);if(!t)return null;let n=ET(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function kT(e){let t=ET(e);if(!t)return null;let n=TT.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=DT(t.rotation),i=DT(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function AT(e){let t=OT(e);if(!t)return null;let n=kT(t.environment);return n?{environment:n}:null}function jT(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=AT(e);if(t)return t}return null}$s();var MT={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`}},NT=/\.(usd|usda|usdc)$/i,PT=/\.(png|jpg|jpeg|avif)$/i,FT=3e4,IT=4e9;function LT(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 RT=683;function zT(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 BT=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 px(t,{downloads:this.downloads,key:i,policy:a,name:ox(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 ux(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 MT[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=ox(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`,Vn(await Bn(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 Vu(r,Vn(await Bn(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)&&Vu(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):ai().decodeImage?(l=await QS(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=Fx(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 Jx(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await yS(e,this.storage))?.listing??await Xx(e,{onProgress:n}):(await dS(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=eS(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 vS(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=Fx(await this._readHead(e)),c=this.storage?Vn(await Bn(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(xT(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(qn.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 uT({},t),c=await GS(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(qn.SCENES);if(!r)return;let i;try{i=RS(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 kS?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};sg(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(qn.SCENES);!t||!n||!sg(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 zS(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?$x(o):null,c;if(a)c=await mS(e,{filter:s});else{let t=i??await yS(e,this.storage);c=await Qx(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||bS(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=IT){if(n<r)return;let{root:i,elements:a}=eS(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},hn.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 Jx(e,{filter:a.length?$x(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}=eS(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},hn.WARNING),i}if(l){let e=$x(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},hn.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[xS]=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 Vu(e,`bytes:${await zn(r)}`),e.userData[xS]=t,e.userData[SS]=`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:${ig}`,`${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 CT({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},hn.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(MT[n]&&MT[n].type===`model`)return NT.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=>NT.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&&(NT.test(e)||PT.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(NT,``)===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=jT(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),FT))]);return clearTimeout(r),i||this._issues?.record(Y.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${FT}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}=Xs(),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),ai().decodeImage&&i.register(e=>$S(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=jT(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=jT(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 Rh(`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*=zT(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/RT,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=RT,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*zT(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=LT(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(MT))r.type===e&&(t[n]=r);return t}return MT}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}},VT={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},HT=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 UT(e=1,t=1){let n={...VT,defaultView:null},r={...VT,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 HT(r);return r}var WT=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}},GT=8,KT=4,qT=.25,JT=r.MathUtils.degToRad(89),YT=.25,XT={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]},ZT=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,QT=e=>e.shiftKey?KT:e.altKey?qT:1,$T={type:`change`},eE={type:`start`},tE=new r.Vector3,nE=new r.Vector3,rE=new r.Vector3,iE=new r.Vector3,aE=new r.Quaternion,oE=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/GT,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)/GT}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]=XT[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return nE.set(1,0,0).applyQuaternion(i.quaternion),tE.crossVectors(i.up,nE).normalize(),nE.crossVectors(tE,i.up),rE.set(0,0,0).addScaledVector(nE,t).addScaledVector(tE,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(rE),this.orbit.target.add(rE),i.updateMatrixWorld(),this.dispatchEvent($T),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,YT);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(aE.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(tE);let s=Math.asin(r.MathUtils.clamp(tE.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-JT,JT);n.quaternion.multiply(aE.setFromAxisAngle(iE.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(tE),a),this.dispatchEvent($T)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(ZT))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=QT(e),XT[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(eE))))}}_onKeyUp(e){this._factor=QT(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 sE=Object.freeze(new r.Vector3(1,1,1)),cE=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,lE=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new WT(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 oE(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,r){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,r??=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 i=this.cameras[this.currentCameraIndex];if(i&&(i.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??sE),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 this._placeAt(this.cameras[e],t);this.resetAutoFocus();let a=this.cameras[e],o=a?.userData?.__rayzeeEffects;this._showOrthographic(o?o.orthoHeight:cE(a)),this._applyEffects(o),n?.(),r?.(),this.dispatchEvent({type:I.CAMERA_SWITCHED,cameraIndex:e,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)})}resetView(){let e=this.currentCameraIndex>0?this.cameras[this.currentCameraIndex]:null;if(!e){this.controls.reset();return}this._placeAt(e,this._getSettings?.(`focusDistance`));let t=cE(e);this.camera.orthographic&&this._setView(!0,t?t/2:this.camera.orthoHalfHeight),this._onReset?.()}_placeAt(e,t){if(this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale),e.isPerspectiveCamera&&(this.camera.fov=e.fov),this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),!this.controls)return;let n=e.userData?.__rayzeeOrbitTarget;if(n)this.controls.target.copy(n);else{let n=new r.Vector3(0,0,-1).applyQuaternion(e.quaternion);this.controls.target.copy(this.camera.position).addScaledVector(n,t||5)}this.controls.update()}_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 cE(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:Ur(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=Wr(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=Wr(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=Ub(l,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?Ub(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()}},uE=.001,dE=2,fE=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),pE=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+dE: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,...mE(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,mE(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]+uE):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:fE(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:fE(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:fE(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:fE(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 mE({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}R();var hE=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new pE(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})}},gE=`__rayzeeUserLight`,_E={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},vE=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[gE]=!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?.[gE]: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:Ur(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=_E[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=Wr(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}},yE=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=>bE(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}),u=performance.now();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),performance.now()-u>16&&(await new Promise(e=>setTimeout(e,0)),u=performance.now())}let d=new r.DataArrayTexture(s,i,a,o);d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d.format=r.RGBAFormat,d.type=r.UnsignedByteType,d.generateMipmaps=!1,d.needsUpdate=!0;let f=this.texture;return this.texture=d,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=d,this.pathTracer.shaderBuilder?.updateGoboMaps?.(d),f?.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:xE(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 bE(e){let t=await px(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 xE(e){return Math.max(0,Math.min(1,e))}function SE(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
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=EE(o),t=2+2*Number(e[1]);o=DE(o,t)}let s=EE(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 CE(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=OE(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=kE(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=OE(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=kE(kE(f,h,d),kE(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function wE(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 TE(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 EE(e){return e.split(/\s+/).filter(e=>e.length>0)}function DE(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function OE(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 kE(e,t,n){return e+(t-e)*n}var AE=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 fx().fetch(e.url),a=SE(await r.text().finally(i),e.name);return{it:e,profile:a,grid:CE(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=wE(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:TE(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:jE(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 jE(e){return Math.max(0,Math.min(1,e))}jt(),$s();var ME=vt(`oidn`),NE=16,PE=null;async function FE(){return PE||=(await import(`oidn-web/dist/oidn.js`)).initUNetFromBuffer,PE}var IE={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}},LE=.18,RE=256,zE=256,BE=`
|
|
1033
1033
|
const WG: u32 = ${RE}u;
|
|
1034
1034
|
const GROUPS: u32 = ${zE}u;
|