rayzee 7.26.2 → 7.26.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/rayzee.es.js +1 -1
- package/dist/rayzee.umd.js +1 -1
- package/package.json +1 -1
- package/src/Stages/PathTracer.js +12 -0
package/dist/rayzee.es.js
CHANGED
|
@@ -10893,7 +10893,7 @@ var lf = ui("wavefront"), uf = 256, df = [
|
|
|
10893
10893
|
this._readbackFrameCounter = this._readbackEveryNFrames;
|
|
10894
10894
|
return;
|
|
10895
10895
|
}
|
|
10896
|
-
if (this._readbackPending || (this._readbackFrameCounter++, this._readbackFrameCounter < this._readbackEveryNFrames)) return;
|
|
10896
|
+
if (this._readbackPending || (this.maxBounces.value !== this._lastBounceCountsBudget && (this._readbackFrameCounter = this._readbackEveryNFrames), this._readbackFrameCounter++, this._readbackFrameCounter < this._readbackEveryNFrames)) return;
|
|
10897
10897
|
this._readbackFrameCounter = 0;
|
|
10898
10898
|
let e = this._queueManager?.getBounceCountsAttribute();
|
|
10899
10899
|
if (!e) return;
|
package/dist/rayzee.umd.js
CHANGED
|
@@ -649,7 +649,7 @@
|
|
|
649
649
|
let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
|
|
650
650
|
return clamp( ndcDepth, 0.0f, 1.0f );
|
|
651
651
|
}
|
|
652
|
-
`),rl=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=fn({origin:e,direction:t}),y=_n.wrap(Is(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=Us({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Pn).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=pn.wrap(Yn(y.materialIndex,a)).toVar(),r=Cn.wrap(Ti(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(tl({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=nl({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(el({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=te({state:ne({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Mr({N:d,xi:(0,n.vec2)(ie(p).toVar(),ie(p).toVar())}).toVar(),h=fn({origin:y.hitPoint.add(d.mul(.001)),direction:m}),v=_n.wrap(Is(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(Us({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=pn.wrap(Yn(v.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=Us({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=Us({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=Us({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function il(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,sceneScale:b,apertureScale:x,anamorphicRatio:S,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:E,environmentMatrix:D,environmentIntensity:O,enableEnvironmentLight:k,visMode:A,debugVisScale:j,frame:M}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),N=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(N.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(N).add(.5)),s=te({state:(0,n.uint)(N.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),P=fn.wrap(Cs(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S)),F=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(A.equal((0,n.int)(9)),()=>{let e=ve(o,(0,n.int)(0),(0,n.int)(1),s,a,M);F.assign((0,n.vec4)(e,1,1))}).Else(()=>{F.assign(rl(P.origin,P.direction,C,w,T,E,D,O,k,A,j,o,a,u,d,M))});let I=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(N));(0,n.textureStore)(t,I,F).toWriteOnly(),(0,n.textureStore)(r,I,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,I,(0,n.vec4)(F.xyz,1)).toWriteOnly()})})}function al({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function ol({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=E(`uint`,a);(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Q.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Zo(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function sl({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function cl({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=E(`uint`,o);(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)(Q.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(Zo(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}var ll=ht(`wavefront`),ul=256,dl=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],fl=class extends Co{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=100,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this._chunkRows=0,this._numChunks=1,this.vramTracker=new ys(this.renderer),this._registerVRAMProviders(),ll.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(t,n);let i=this._updateAuxAccumulationUniforms(t);this.frame.value=t,this.seedFrame.value=this._seedTick++,this._setWfDispatch();let a=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=a.color,this.shaderBuilder.prevAlbedoTexNode.value=a.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=a.normalDepth),this._refreshWfTextureNodes();let o=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){o.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}let s=this.maxBounces.value,c=s+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value,l=this._wfRenderHeight.value,u=this._chunkRows,d=this._numChunks<=1,f=this._lastBounceCounts,p=d&&f?s<=this._lastBounceCountsBudget?c+1:this._lastBounceCountsBudget:0;for(let e=0,n=0;n<l;n+=u,e++){let r=Math.min(u,l-n),i=this._setChunk(n,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,s=d&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(s*1.5)+1024);o.setDispatchForCount(`generateList`,e),o.dispatch(`resetFrameCounters`),o.dispatch(`buildActivePixels`),o.dispatch(`seedEnter`),o.dispatch(`generateList`)}else o.dispatch(`generate`),o.dispatch(`initActiveIndices`);e===0&&t>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&o.dispatch(`countConvergedDilated`);for(let e=0;e<=c;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(d&&e>0&&this._curveSizingValid){let n=e-1,r;n<p&&f[n]!==void 0?r=f[n]:p>0&&(r=f[p-1]),t=r>0?r:i}else e===0&&a&&(t=s);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of dl)o.setDispatchForCount(e,n)}else{o.dispatch(`enterFull`);for(let e of dl)o.setDispatchForCount(e,i)}if(o.dispatch(`extend`),this._sortMaterials&&(o.dispatch(`resetGlobalHist`),o.dispatch(`globalHist`),o.dispatch(`globalPrefix`),o.dispatch(`globalScatter`)),o.dispatch(`shade`),o.dispatch(`compact`),t?o.dispatch(`compactCopyback`):o.dispatch(`snapshotBounceCount`),e<p&&e<c&&f[e]!==void 0&&f[e]<=this._bounceEarlyExitThreshold)break}o.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let m=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,m),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=i?this._auxSamples+1:1),this._auxSeedPending=!1,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_maybeReadbackCounters(){if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||(this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&(this._lastBounceCounts=new Uint32Array(e.slice(0)),this._lastBounceCountsBudget=n,this._curveSizingValid=!0),this._readbackPending=!1}).catch(e=>{ll.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration&&n>0){let t=new Uint32Array(e);this._convergedFraction=t[Q.CONVERGED_COUNT]/n;let r=t[Q.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?t[Q.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=t[Q.ACTIVE_PIXEL_COUNT]}this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(ui(e.srgbBuckets,n.srgbBuckets),ui(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;n===e&&r===t||!(this.materialData?.materialCount>0)||(this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()))}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout(),this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(e*t/1e3)))}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=(typeof navigator<`u`&&navigator.deviceMemory||4)*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/176),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,V),t=Math.min(this.storageTextures.renderHeight||1,V);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let r=this.storageTextures.renderWidth,i=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let a=this._pathBudget;this._updateChunkLayout();let o=this._chunkRows*r;this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(r*i/1e3))),this._packedBuffers?this._packedBuffers.resize(a):this._packedBuffers=new ko(a,this.renderer);let s=a*1;Oo(this.renderer,this._gBufferAttr),this._gBufferAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(s*4),4);let c=(0,n.storage)(this._gBufferAttr,`uvec4`),l=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),u=V*V;(!this._m2Attr||this._m2Attr.count<u)&&(Oo(this.renderer,this._m2Attr),this._m2Attr=new t.StorageInstancedBufferAttribute(new Float32Array(u),1),Oo(this.renderer,this._streakAttr),this._streakAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(u),1),Oo(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(u),1));let d=(0,n.storage)(this._m2Attr,`float`),f=(0,n.storage)(this._streakAttr,`uint`),p=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),m=(0,n.storage)(this._frozenMaskAttr,`uint`),h=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new ps(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new xs(this.renderer);let g=this._packedBuffers,_=this._queueManager;this._wfRenderWidth.value=r,this._wfRenderHeight.value=i,this._wfMaxRayCount.value=Math.min(a,this._chunkRows*r);let v=this.shaderBuilder.prevColorTexNode,y=this.shaderBuilder.prevAlbedoTexNode,b=this.shaderBuilder.prevNormalDepthTexNode,x=this.storageTextures.getWriteTextures(),S=_.getCounters(),C=_.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(_.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=_.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*r/ul),1,1],[ul,1,1]));let O={rayBufferRW:g.rayBuffer.rw,rngBufferRW:g.rngBuffer.rw,gBufferRW:c,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=ws(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(r/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(p.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(p.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),m.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*r/ul),1,1],[ul,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=p.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(p.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(r*i/ul),1,1],[ul,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),e),(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=ws({...O,listDriven:!0,activeIndicesRO:_.activeIndicesRO.a,counters:S});this._kernelManager.register(`generateList`,F().compute([Math.ceil(o/ul),1,1],[ul,1,1]));let I=this.bvhStorageNode,ee=this.triangleStorageNode,te=this.materialData.materialStorageNode,ne=(0,n.texture)(this.environment.envCDFTexture),re=this.lightStorageNode,ie=this.materialData,ae=this.environment,oe=li(ie.srgbBuckets),se=li(ie.linearBuckets);ri(oe,se),ki(oe);let ce=ae.environmentTexture?(0,n.texture)(ae.environmentTexture):e.envTex;this._wfTexNodes={envTex:ce,envCDFTex:ne,srgbBuckets:oe,linearBuckets:se},this._sortMaterials=(B.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let le=Rs({bvhBuffer:I,triangleBuffer:ee,rayBufferRO:g.rayBuffer.ro,hitBufferRW:g.hitBuffer.rw,activeIndicesRO:_.getActiveReadRO(),counters:S,maxRayCount:this._wfMaxRayCount});if(this._kernelManager.register(`extend`,le().compute([Math.ceil(o/256),1,1],[256,1,1])),this._sortMaterials){let e=_.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,al({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,ol({hitBufferRO:g.hitBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),sortGlobalHistogram:e,counters:S,bins:t})().compute([Math.ceil(o/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,sl({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,cl({hitBufferRO:g.hitBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),sortedIndicesRW:_.getSortedRW(),sortGlobalHistogram:e,counters:S,bins:t})().compute([Math.ceil(o/256),1,1],[256,1,1]))}let ue=Yc({gBufferRW:c,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:ee,materialBuffer:te,envCDFTexture:ne,lightBuffer:re,rayBufferRW:g.rayBuffer.rw,rngBufferRW:g.rngBuffer.rw,hitBufferRO:g.hitBuffer.ro,counters:S,activeIndicesRO:this._sortMaterials?_.getSortedRO():_.getActiveReadRO(),envTexture:ce,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,ue().compute([Math.ceil(o/256),1,1],[256,1,1]));let de=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=de;let fe=(de?Zc:Xc)({rayBufferRO:g.rayBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),activeIndicesWriteRW:_.getActiveWrite(),counters:S,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,fe().compute([Math.ceil(o/256),1,1],[256,1,1]));let pe=(0,n.Fn)(()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,pe().compute([1,1,1],[1,1,1]));let me=_.activeIndicesRO.b,he=_.activeIndices.a,ge=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(_.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),he.element(e).assign(me.element(e))});this._kernelManager.register(`compactCopyback`,ge().compute([Math.ceil(o/ul),1,1],[ul,1,1]));let _e=$c({rayBufferRO:g.rayBuffer.ro,gBufferRO:l,writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:v,prevAlbedoTexture:y,prevNormalDepthTexture:b,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:d,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:f,frozenMaskRO:h,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,_e().compute([Math.ceil(r/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let ve=il({writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:I,triangleBuffer:ee,materialBuffer:te,envTexture:ce,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,ve().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1])),this._wavefrontReady=!0;let ye=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);ll.info(K.list([K.px(r,i),`${K.mb(ye)} wavefront buffers`,`budget ${K.n(a)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},pl=class extends xe{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:be.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(V,V),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(V,V),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&ui(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=li(this.pathTracer?.materialData?.linearBuckets),ri(li(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let u=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),d=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(u.lessThan((0,n.int)(o)).and(d.lessThan((0,n.int)(s))),()=>{let f=Ss((0,n.vec2)((0,n.float)(u).add(.5).div(o),(0,n.float)(d).add(.5).div(s)),i,a,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon),p=fn({origin:(0,n.vec3)(i[3]),direction:f}),m=_n.wrap(Fs(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),_).toWriteOnly();let v=m.normal.toVar();(0,n.If)(m.didHit,()=>{let t=pn.wrap(Yn(m.materialIndex,r)).toVar(),i=Tn.wrap(hi(m.uv,t)).toVar(),a=(0,n.vec4)(0).toVar();(0,n.If)(t.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{a.assign(yi(e,m.triangleIndex,m.normal,t.normalTransform))});let o=bi(m.normal,t,i,a).toVar();v.assign(xi(o,t,i))});let y=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),y).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraProjection.value=t.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(t.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(t.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=t.uniforms.get(`panoLevelHorizon`).value),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(V,V);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._computeBuilt=!1}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},ml=class extends xe{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:be.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(V,V),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(V,V),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(V,V);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},hl=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),gl=e=>(0,n.vec3)(hl(e.x),hl(e.y),hl(e.z)),_l=class extends xe{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:be.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(V,V),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(V,V),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(V,V),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(V,V),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(V,V),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Rn(gl(m.div((0,n.max)(_,(0,n.vec3)(Le))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Rn(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Le)),T=gl(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),ee=F(O,k,M),te=F(C,A,N),ne=F(O,A,P),re=I.add(ee).add(te).add(ne);(0,n.If)(re.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(re),o=e.xyz.mul(I).add(t.xyz.mul(ee)).add(r.xyz.mul(te)).add(i.xyz.mul(ne)).mul(a),l=e.w.mul(I).add(t.w.mul(ee)).add(r.w.mul(te)).add(i.w.mul(ne)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=gl((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Rn(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(V,V);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},vl=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),yl=(0,n.wgslFn)(`
|
|
652
|
+
`),rl=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=fn({origin:e,direction:t}),y=_n.wrap(Is(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=Us({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Pn).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=pn.wrap(Yn(y.materialIndex,a)).toVar(),r=Cn.wrap(Ti(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(tl({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=nl({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(el({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=pn.wrap(Yn(y.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=te({state:ne({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Mr({N:d,xi:(0,n.vec2)(ie(p).toVar(),ie(p).toVar())}).toVar(),h=fn({origin:y.hitPoint.add(d.mul(.001)),direction:m}),v=_n.wrap(Is(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(Us({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=pn.wrap(Yn(v.materialIndex,a)).toVar(),t=Cn.wrap(Ti(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=Us({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=Us({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=Us({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function il(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,sceneScale:b,apertureScale:x,anamorphicRatio:S,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:E,environmentMatrix:D,environmentIntensity:O,enableEnvironmentLight:k,visMode:A,debugVisScale:j,frame:M}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),N=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(N.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(N).add(.5)),s=te({state:(0,n.uint)(N.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),P=fn.wrap(Cs(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S)),F=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(A.equal((0,n.int)(9)),()=>{let e=ve(o,(0,n.int)(0),(0,n.int)(1),s,a,M);F.assign((0,n.vec4)(e,1,1))}).Else(()=>{F.assign(rl(P.origin,P.direction,C,w,T,E,D,O,k,A,j,o,a,u,d,M))});let I=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(N));(0,n.textureStore)(t,I,F).toWriteOnly(),(0,n.textureStore)(r,I,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,I,(0,n.vec4)(F.xyz,1)).toWriteOnly()})})}function al({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function ol({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=E(`uint`,a);(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Q.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Zo(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function sl({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function cl({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=E(`uint`,o);(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)(Q.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(Zo(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}var ll=ht(`wavefront`),ul=256,dl=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],fl=class extends Co{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=100,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this._chunkRows=0,this._numChunks=1,this.vramTracker=new ys(this.renderer),this._registerVRAMProviders(),ll.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(t,n);let i=this._updateAuxAccumulationUniforms(t);this.frame.value=t,this.seedFrame.value=this._seedTick++,this._setWfDispatch();let a=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=a.color,this.shaderBuilder.prevAlbedoTexNode.value=a.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=a.normalDepth),this._refreshWfTextureNodes();let o=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){o.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}let s=this.maxBounces.value,c=s+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value,l=this._wfRenderHeight.value,u=this._chunkRows,d=this._numChunks<=1,f=this._lastBounceCounts,p=d&&f?s<=this._lastBounceCountsBudget?c+1:this._lastBounceCountsBudget:0;for(let e=0,n=0;n<l;n+=u,e++){let r=Math.min(u,l-n),i=this._setChunk(n,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,s=d&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(s*1.5)+1024);o.setDispatchForCount(`generateList`,e),o.dispatch(`resetFrameCounters`),o.dispatch(`buildActivePixels`),o.dispatch(`seedEnter`),o.dispatch(`generateList`)}else o.dispatch(`generate`),o.dispatch(`initActiveIndices`);e===0&&t>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&o.dispatch(`countConvergedDilated`);for(let e=0;e<=c;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(d&&e>0&&this._curveSizingValid){let n=e-1,r;n<p&&f[n]!==void 0?r=f[n]:p>0&&(r=f[p-1]),t=r>0?r:i}else e===0&&a&&(t=s);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of dl)o.setDispatchForCount(e,n)}else{o.dispatch(`enterFull`);for(let e of dl)o.setDispatchForCount(e,i)}if(o.dispatch(`extend`),this._sortMaterials&&(o.dispatch(`resetGlobalHist`),o.dispatch(`globalHist`),o.dispatch(`globalPrefix`),o.dispatch(`globalScatter`)),o.dispatch(`shade`),o.dispatch(`compact`),t?o.dispatch(`compactCopyback`):o.dispatch(`snapshotBounceCount`),e<p&&e<c&&f[e]!==void 0&&f[e]<=this._bounceEarlyExitThreshold)break}o.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let m=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,m),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=i?this._auxSamples+1:1),this._auxSeedPending=!1,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_maybeReadbackCounters(){if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||(this.maxBounces.value!==this._lastBounceCountsBudget&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&(this._lastBounceCounts=new Uint32Array(e.slice(0)),this._lastBounceCountsBudget=n,this._curveSizingValid=!0),this._readbackPending=!1}).catch(e=>{ll.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration&&n>0){let t=new Uint32Array(e);this._convergedFraction=t[Q.CONVERGED_COUNT]/n;let r=t[Q.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?t[Q.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=t[Q.ACTIVE_PIXEL_COUNT]}this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(ui(e.srgbBuckets,n.srgbBuckets),ui(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;n===e&&r===t||!(this.materialData?.materialCount>0)||(this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()))}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout(),this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(e*t/1e3)))}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=(typeof navigator<`u`&&navigator.deviceMemory||4)*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/176),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,V),t=Math.min(this.storageTextures.renderHeight||1,V);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let r=this.storageTextures.renderWidth,i=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let a=this._pathBudget;this._updateChunkLayout();let o=this._chunkRows*r;this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(r*i/1e3))),this._packedBuffers?this._packedBuffers.resize(a):this._packedBuffers=new ko(a,this.renderer);let s=a*1;Oo(this.renderer,this._gBufferAttr),this._gBufferAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(s*4),4);let c=(0,n.storage)(this._gBufferAttr,`uvec4`),l=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),u=V*V;(!this._m2Attr||this._m2Attr.count<u)&&(Oo(this.renderer,this._m2Attr),this._m2Attr=new t.StorageInstancedBufferAttribute(new Float32Array(u),1),Oo(this.renderer,this._streakAttr),this._streakAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(u),1),Oo(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(u),1));let d=(0,n.storage)(this._m2Attr,`float`),f=(0,n.storage)(this._streakAttr,`uint`),p=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),m=(0,n.storage)(this._frozenMaskAttr,`uint`),h=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new ps(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new xs(this.renderer);let g=this._packedBuffers,_=this._queueManager;this._wfRenderWidth.value=r,this._wfRenderHeight.value=i,this._wfMaxRayCount.value=Math.min(a,this._chunkRows*r);let v=this.shaderBuilder.prevColorTexNode,y=this.shaderBuilder.prevAlbedoTexNode,b=this.shaderBuilder.prevNormalDepthTexNode,x=this.storageTextures.getWriteTextures(),S=_.getCounters(),C=_.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(_.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=_.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*r/ul),1,1],[ul,1,1]));let O={rayBufferRW:g.rayBuffer.rw,rngBufferRW:g.rngBuffer.rw,gBufferRW:c,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=ws(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(r/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(p.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(p.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),m.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*r/ul),1,1],[ul,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=p.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(p.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(S.element((0,n.uint)(Q.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(r*i/ul),1,1],[ul,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),e),(0,n.atomicStore)(S.element((0,n.uint)(Q.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=ws({...O,listDriven:!0,activeIndicesRO:_.activeIndicesRO.a,counters:S});this._kernelManager.register(`generateList`,F().compute([Math.ceil(o/ul),1,1],[ul,1,1]));let I=this.bvhStorageNode,ee=this.triangleStorageNode,te=this.materialData.materialStorageNode,ne=(0,n.texture)(this.environment.envCDFTexture),re=this.lightStorageNode,ie=this.materialData,ae=this.environment,oe=li(ie.srgbBuckets),se=li(ie.linearBuckets);ri(oe,se),ki(oe);let ce=ae.environmentTexture?(0,n.texture)(ae.environmentTexture):e.envTex;this._wfTexNodes={envTex:ce,envCDFTex:ne,srgbBuckets:oe,linearBuckets:se},this._sortMaterials=(B.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let le=Rs({bvhBuffer:I,triangleBuffer:ee,rayBufferRO:g.rayBuffer.ro,hitBufferRW:g.hitBuffer.rw,activeIndicesRO:_.getActiveReadRO(),counters:S,maxRayCount:this._wfMaxRayCount});if(this._kernelManager.register(`extend`,le().compute([Math.ceil(o/256),1,1],[256,1,1])),this._sortMaterials){let e=_.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,al({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,ol({hitBufferRO:g.hitBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),sortGlobalHistogram:e,counters:S,bins:t})().compute([Math.ceil(o/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,sl({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,cl({hitBufferRO:g.hitBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),sortedIndicesRW:_.getSortedRW(),sortGlobalHistogram:e,counters:S,bins:t})().compute([Math.ceil(o/256),1,1],[256,1,1]))}let ue=Yc({gBufferRW:c,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:ee,materialBuffer:te,envCDFTexture:ne,lightBuffer:re,rayBufferRW:g.rayBuffer.rw,rngBufferRW:g.rngBuffer.rw,hitBufferRO:g.hitBuffer.ro,counters:S,activeIndicesRO:this._sortMaterials?_.getSortedRO():_.getActiveReadRO(),envTexture:ce,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,ue().compute([Math.ceil(o/256),1,1],[256,1,1]));let de=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=de;let fe=(de?Zc:Xc)({rayBufferRO:g.rayBuffer.ro,activeIndicesReadRO:_.getActiveReadRO(),activeIndicesWriteRW:_.getActiveWrite(),counters:S,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,fe().compute([Math.ceil(o/256),1,1],[256,1,1]));let pe=(0,n.Fn)(()=>{(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,pe().compute([1,1,1],[1,1,1]));let me=_.activeIndicesRO.b,he=_.activeIndices.a,ge=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(S.element((0,n.uint)(Q.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(_.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),(0,n.atomicStore)(S.element((0,n.uint)(Q.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),he.element(e).assign(me.element(e))});this._kernelManager.register(`compactCopyback`,ge().compute([Math.ceil(o/ul),1,1],[ul,1,1]));let _e=$c({rayBufferRO:g.rayBuffer.ro,gBufferRO:l,writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:v,prevAlbedoTexture:y,prevNormalDepthTexture:b,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:d,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:f,frozenMaskRO:h,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,_e().compute([Math.ceil(r/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let ve=il({writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:I,triangleBuffer:ee,materialBuffer:te,envTexture:ce,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,ve().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1])),this._wavefrontReady=!0;let ye=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);ll.info(K.list([K.px(r,i),`${K.mb(ye)} wavefront buffers`,`budget ${K.n(a)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},pl=class extends xe{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:be.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(V,V),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(V,V),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&ui(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=li(this.pathTracer?.materialData?.linearBuckets),ri(li(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let u=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),d=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(u.lessThan((0,n.int)(o)).and(d.lessThan((0,n.int)(s))),()=>{let f=Ss((0,n.vec2)((0,n.float)(u).add(.5).div(o),(0,n.float)(d).add(.5).div(s)),i,a,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon),p=fn({origin:(0,n.vec3)(i[3]),direction:f}),m=_n.wrap(Fs(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),_).toWriteOnly();let v=m.normal.toVar();(0,n.If)(m.didHit,()=>{let t=pn.wrap(Yn(m.materialIndex,r)).toVar(),i=Tn.wrap(hi(m.uv,t)).toVar(),a=(0,n.vec4)(0).toVar();(0,n.If)(t.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{a.assign(yi(e,m.triangleIndex,m.normal,t.normalTransform))});let o=bi(m.normal,t,i,a).toVar();v.assign(xi(o,t,i))});let y=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),y).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraProjection.value=t.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(t.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(t.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=t.uniforms.get(`panoLevelHorizon`).value),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(V,V);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._computeBuilt=!1}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},ml=class extends xe{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:be.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(V,V),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(V,V),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(V,V);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},hl=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),gl=e=>(0,n.vec3)(hl(e.x),hl(e.y),hl(e.z)),_l=class extends xe{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:be.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(V,V),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(V,V),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(V,V),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(V,V),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(V,V),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Rn(gl(m.div((0,n.max)(_,(0,n.vec3)(Le))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Rn(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Le)),T=gl(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),ee=F(O,k,M),te=F(C,A,N),ne=F(O,A,P),re=I.add(ee).add(te).add(ne);(0,n.If)(re.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(re),o=e.xyz.mul(I).add(t.xyz.mul(ee)).add(r.xyz.mul(te)).add(i.xyz.mul(ne)).mul(a),l=e.w.mul(I).add(t.w.mul(ee)).add(r.w.mul(te)).add(i.w.mul(ne)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=gl((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Rn(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(V,V);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},vl=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),yl=(0,n.wgslFn)(`
|
|
653
653
|
fn temporalAccumulate(
|
|
654
654
|
lum: f32,
|
|
655
655
|
prevMean: f32,
|
package/package.json
CHANGED
package/src/Stages/PathTracer.js
CHANGED
|
@@ -710,6 +710,18 @@ export class PathTracer extends PathTracerStage {
|
|
|
710
710
|
|
|
711
711
|
if ( this._readbackPending ) return;
|
|
712
712
|
|
|
713
|
+
// A curve measured at a different budget has an untrusted tail, so curveReliableUpto collapses
|
|
714
|
+
// to the old budget: the per-bounce early exit is off past that point and every remaining
|
|
715
|
+
// iteration full-sizes off curve[curveReliableUpto - 1]. Measured on a 1024² interior, raising
|
|
716
|
+
// the budget 3 -> 20 doubles the frame's dispatch work (13 -> 26 bounce iterations, 109 -> 214
|
|
717
|
+
// compute passes) for as long as that lasts. Waiting out the N-frame cadence just extends it, so
|
|
718
|
+
// re-measure on the next frame instead — same idiom as the mid-motion priming above.
|
|
719
|
+
if ( this.maxBounces.value !== this._lastBounceCountsBudget ) {
|
|
720
|
+
|
|
721
|
+
this._readbackFrameCounter = this._readbackEveryNFrames;
|
|
722
|
+
|
|
723
|
+
}
|
|
724
|
+
|
|
713
725
|
this._readbackFrameCounter ++;
|
|
714
726
|
if ( this._readbackFrameCounter < this._readbackEveryNFrames ) return;
|
|
715
727
|
this._readbackFrameCounter = 0;
|