rayzee 5.3.4 → 5.3.6
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/assets/BVHSubtreeWorker-CTHfS54a.js +2 -0
- package/dist/assets/BVHSubtreeWorker-CTHfS54a.js.map +1 -0
- package/dist/assets/BVHWorker-BarjE67Z.js +2 -0
- package/dist/assets/BVHWorker-BarjE67Z.js.map +1 -0
- package/dist/rayzee.es.js +983 -910
- package/dist/rayzee.es.js.map +1 -1
- package/dist/rayzee.umd.js +41 -41
- package/dist/rayzee.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/Passes/AIUpscaler.js +16 -4
- package/src/PathTracerApp.js +0 -4
- package/src/Processor/BVHBuilder.js +28 -8
- package/src/Processor/EquirectHDRInfo.js +16 -4
- package/src/Processor/ParallelBVHBuilder.js +58 -20
- package/src/Processor/SceneProcessor.js +76 -31
- package/src/Processor/TextureCreator.js +17 -4
- package/src/Processor/Workers/fetchAsWorker.js +30 -0
- package/src/managers/DenoisingManager.js +4 -17
- package/dist/assets/BVHSubtreeWorker-BoG4D6dP.js +0 -2
- package/dist/assets/BVHSubtreeWorker-BoG4D6dP.js.map +0 -1
- package/dist/assets/BVHWorker-BqQTDljT.js +0 -2
- package/dist/assets/BVHWorker-BqQTDljT.js.map +0 -1
package/dist/rayzee.umd.js
CHANGED
|
@@ -146,7 +146,7 @@
|
|
|
146
146
|
return seed;
|
|
147
147
|
|
|
148
148
|
}
|
|
149
|
-
`,[ne,P]),I={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},L=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||I.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case I.ALWAYS:return!0;case I.PER_CYCLE:return t===0?!0:n===!0;case I.PER_TILE:return!0;case I.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},ge=class{constructor(e,t,n){this.width=e,this.height=t,this.tiles=n,this.tileIndex=0,this.tileBoundsCache=new Map,this.totalTilesCache=n*n,this.currentTileBounds=null,this.spiralOrder=this.generateSpiralOrder(n)}calculateTileBounds(e,t,n,r){let i=`${e}-${t}-${n}-${r}`;if(this.tileBoundsCache.has(i))return this.tileBoundsCache.get(i);let a=Math.ceil(n/t),o=Math.ceil(r/t),s=e%t,c=Math.floor(e/t),l=s*a,u=c*o,d={x:l,y:u,width:Math.min(a,n-l),height:Math.min(o,r-u)};return this.tileBoundsCache.set(i,d),d}generateSpiralOrder(e){let t=e*e,n=[];for(let r=0;r<t;r++){let t=r%e,i=Math.floor(r/e),a=(e-1)/2,o=t-a,s=i-a,c=Math.abs(o)+Math.abs(s),l=Math.sqrt(o*o+s*s),u=Math.atan(s,o);u<0&&(u+=2*Math.PI);let d=(t+i*e)*.001;n.push({index:r,x:t,y:i,manhattanDistance:c,euclideanDistance:l,angle:u,positionOffset:d})}return n.sort((e,t)=>{let n=e.manhattanDistance-t.manhattanDistance;if(Math.abs(n)>.01)return n;let r=e.euclideanDistance-t.euclideanDistance;if(Math.abs(r)>.01)return r;let i=e.angle-t.angle;return Math.abs(i)>.01?i:e.positionOffset-t.positionOffset}),n.map(e=>e.index)}handleTileRendering(e,t,n){let r=!0,i=-1,a=null,o=!0;if(t===1)if(n===0)i=-1,o=!0;else{let e=(n-1)%this.totalTilesCache;i=this.spiralOrder[e],a=this.calculateTileBounds(i,this.tiles,this.width,this.height),o=e===this.totalTilesCache-1,r=o}else i=-1,o=!0;return this.tileIndex=i,{tileIndex:i,tileBounds:a,shouldSwapTargets:r,isCompleteCycle:o}}setTileCount(e){if(e<1&&(console.warn(`TileManager: Tile count must be at least 1, clamping to 1`),e=1),e>10&&console.warn(`TileManager: Tile count > 10 may cause performance issues`),e>6){let t=e*e;console.warn(`TileManager: ${e}x${e} = ${t} tiles may impact performance and memory usage`)}this.tiles=e,this.totalTilesCache=e*e,this.tileIndex=0,this.spiralOrder=this.generateSpiralOrder(e),this.tileBoundsCache.clear()}setSize(e,t){this.width=e,this.height=t,this.tileBoundsCache.clear()}calculateCompletionThreshold(e){return this.totalTilesCache*e}getCurrentTileInfo(){return{tileIndex:this.tileIndex,tiles:this.tiles,totalTiles:this.totalTilesCache,currentBounds:this.currentTileBounds}}dispose(){this.tileBoundsCache.clear(),this.currentTileBounds=null}},_e=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!0,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,numRaysPerPixel:1,useAdaptiveSampling:!0,useEnvMapIS:!0,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},R={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`},ve=null;function ye(e){ve=e}var be=()=>ve?.({type:R.LOADING_RESET}),z=e=>{ve?.({type:R.LOADING_UPDATE,...e})},xe=e=>{ve?.({type:R.STATS_UPDATE,...e})};function Se(e){let t=e.frameCount||0;if(e.renderMode?.value===1&&t>0){let n=e.tileManager?.totalTilesCache||1;return 1+Math.floor((t-1)/n)}return t}function Ce(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(we(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;we(e),e.dispose()}}function we(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function Te({material:e,geometry:t,children:n}){if(e&&Ce(e),t&&t.dispose(),n.length>0)for(let e of n)Te(e)}function B(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Ce(e);return}for(;e.children.length>0;)for(let t of e.children)B(t);Te(e),e.removeFromParent(),e.clear()}}function Ee(e,t,n){return e===1?n*t:t}function De(e,t,n,r=!1){return r?1:t===0?1/(e+1):e===0?1:1/(1+Math.floor((e-1)/n)+1)}function Oe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}function ke(e,r){let i=new t.StorageTexture(e,r);return i.type=n.FloatType,i.format=n.RGBAFormat,i.minFilter=n.LinearFilter,i.magFilter=n.LinearFilter,i}var Ae=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,e>0&&t>0&&this.create(e,t)}create(e,r){this.dispose(),this.renderWidth=e,this.renderHeight=r,this.writeColor=ke(e,r),this.writeNormalDepth=ke(e,r),this.writeAlbedo=ke(e,r),this.readTarget=new t.RenderTarget(e,r,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,console.log(`StorageTexturePool: Created ${e}x${r} (3 write StorageTextures + 1 MRT RenderTarget)`)}ensureSize(e,t){return this.renderWidth!==e||this.renderHeight!==t||!this.writeColor?(this.create(e,t),!0):!1}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e){e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0]),e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1]),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2])}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.writeColor?.setSize(e,t),this.writeNormalDepth?.setSize(e,t),this.writeAlbedo?.setSize(e,t),this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},V={resolution:512,canvasWidth:512,canvasHeight:512,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,useImportanceSampledEnvironment:!0,environmentIntensity:1,backgroundIntensity:1,environmentRotation:270,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,samplesPerPixel:1,transmissiveBounces:5,samplingTechnique:3,enableEmissiveTriangleSampling:!1,emissiveBoost:1,adaptiveSampling:!1,adaptiveSamplingMin:1,adaptiveSamplingMax:8,adaptiveSamplingVarianceThreshold:.1,temporalVarianceWeight:.6,enableEarlyTermination:!0,earlyTerminationThreshold:.002,showAdaptiveSamplingHelper:!1,performanceModeAdaptive:`medium`,fireflyThreshold:3,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tiles:3,tilesHelper:!1,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,pixelEdgeSharpness:.75,edgeSharpenSpeed:.05,edgeThreshold:1,enableOIDN:!1,oidnQuality:`fast`,debugGbufferMaps:!1,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,debugVisScale:100,denoiserStrategy:`edgeaware`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,ssrcTemporalAlpha:.1,ssrcSpatialRadius:4,ssrcSpatialWeight:.4,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},je={low:{temporalAlpha:.3,atrousIterations:1,phiColor:30,phiNormal:64,phiDepth:2,phiLuminance:6,maxAccumFrames:8,varianceBoost:.5},medium:{temporalAlpha:.1,atrousIterations:3,phiColor:20,phiNormal:128,phiDepth:1,phiLuminance:2,maxAccumFrames:32,varianceBoost:1},high:{temporalAlpha:.05,atrousIterations:8,phiColor:5,phiNormal:256,phiDepth:.5,phiLuminance:2,maxAccumFrames:64,varianceBoost:1.5}},Me={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},Ne={clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:20,sunIntensity:15,rayleighDensity:.9,turbidity:.8},clearNoon:{name:`Clear Noon`,sunAzimuth:0,sunElevation:75,sunIntensity:20,rayleighDensity:1,turbidity:.3},overcast:{name:`Overcast`,sunAzimuth:0,sunElevation:45,sunIntensity:6,rayleighDensity:.6,turbidity:4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:10,sunIntensity:19,rayleighDensity:.8,turbidity:1.2},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:2,sunIntensity:18,rayleighDensity:.7,turbidity:2},dusk:{name:`Dusk`,sunAzimuth:270,sunElevation:-8,sunIntensity:8,rayleighDensity:.5,turbidity:1.5}},Pe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,fov:45,focusDistance:1.5,aperture:1.4,focalLength:135,apertureScale:1.5},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,fov:65,focusDistance:10,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Extreme close-up with thin focus plane`,fov:40,focusDistance:.3,aperture:2,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,fov:50,focusDistance:.8,aperture:2.8,focalLength:85,apertureScale:1},architectural:{name:`Architectural`,description:`Wide view with deep focus`,fov:75,focusDistance:5,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,fov:35,focusDistance:3,aperture:1.4,focalLength:200,apertureScale:1.8,anamorphicRatio:1.5}},Fe={MANUAL:`manual`,AUTO:`auto`},Ie={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},H={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},U={SLOTS_PER_MATERIAL:27,FLOATS_PER_MATERIAL:108,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26}},W={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},Le={PIXELS_PER_MATERIAL:27,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192},Re=[0,0,1,1,0,0,0,1],ze={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,enableAlphaShadows:!0,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},G={maxSamples:V.maxSamples,bounces:V.bounces,samplesPerPixel:V.samplesPerPixel,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:V.transmissiveBounces,tiles:V.tiles,tilesHelper:V.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},Be={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4},Ve={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},He=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=t?1:0:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let r=(e,t,n)=>{let r=(0,o.uniform)(t,n);return this._uniforms.set(e,r),r},i=(e,t)=>(this._booleans.add(e),r(e,t?1:0,`int`));r(`frame`,0,`uint`),r(`maxBounces`,V.bounces,`int`),r(`samplesPerPixel`,V.samplesPerPixel,`int`),r(`maxSamples`,V.maxSamples,`int`),r(`transmissiveBounces`,V.transmissiveBounces,`int`),r(`visMode`,V.debugMode,`int`),r(`debugVisScale`,V.debugVisScale,`float`),i(`enableAccumulation`,!0),r(`accumulationAlpha`,0,`float`),i(`cameraIsMoving`,!1),i(`hasPreviousAccumulated`,!1),r(`environmentIntensity`,V.environmentIntensity,`float`),r(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`showBackground`,V.showBackground),i(`transparentBackground`,V.transparentBackground),i(`enableEnvironment`,V.enableEnvironment),r(`environmentMatrix`,new n.Matrix4,`mat4`),i(`useEnvMapIS`,V.useImportanceSampledEnvironment),r(`envTotalSum`,0,`float`),r(`envResolution`,new n.Vector2(1,1),`vec2`),r(`sunDirection`,new n.Vector3(0,1,0),`vec3`),r(`sunAngularSize`,.0087,`float`),i(`hasSun`,!1),r(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),r(`exposure`,V.exposure,`float`),r(`numDirectionalLights`,0,`int`),r(`numAreaLights`,0,`int`),r(`numPointLights`,0,`int`),r(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,o.uniformArray)(new Float32Array(128),`float`),area:(0,o.uniformArray)(new Float32Array(208),`float`),point:(0,o.uniformArray)(new Float32Array(144),`float`),spot:(0,o.uniformArray)(new Float32Array(224),`float`)},r(`cameraWorldMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrixInverse`,new n.Matrix4,`mat4`),r(`cameraViewMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrix`,new n.Matrix4,`mat4`),i(`enableDOF`,V.enableDOF),r(`focusDistance`,V.focusDistance,`float`),r(`focalLength`,V.focalLength,`float`),r(`aperture`,V.aperture,`float`),r(`apertureScale`,1,`float`),r(`anamorphicRatio`,V.anamorphicRatio??1,`float`),r(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,O),O.value=V.samplingTechnique,i(`useAdaptiveSampling`,V.adaptiveSampling),r(`adaptiveSamplingMin`,V.adaptiveSamplingMin??1,`int`),r(`adaptiveSamplingMax`,V.adaptiveSamplingMax,`int`),r(`fireflyThreshold`,V.fireflyThreshold,`float`),i(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),r(`emissiveBoost`,V.emissiveBoost,`float`),r(`emissiveTriangleCount`,0,`int`),r(`emissiveTotalPower`,0,`float`),r(`lightBVHNodeCount`,0,`int`),r(`renderMode`,V.renderMode,`int`),i(`enableAlphaShadows`,V.enableAlphaShadows),r(`resolution`,new n.Vector2(e,t),`vec2`),r(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Ve[e]||e}},Ue=U.SLOTS_PER_MATERIAL,We=class{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let n=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=n):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,o.storage)(this.materialStorageAttr,`vec4`,n).toReadOnly()),this.materialCount=Math.floor(n/Ue),console.log(`MaterialDataManager: ${this.materialCount} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.albedoMaps&&(this.albedoMaps=e.albedoMaps),e.emissiveMaps&&(this.emissiveMaps=e.emissiveMaps),e.normalMaps&&(this.normalMaps=e.normalMaps),e.bumpMaps&&(this.bumpMaps=e.bumpMaps),e.roughnessMaps&&(this.roughnessMaps=e.roughnessMaps),e.metalnessMaps&&(this.metalnessMaps=e.metalnessMaps),e.displacementMaps&&(this.displacementMaps=e.displacementMaps)}loadTexturesFromSdfs(){this.albedoMaps=this.sdfs.albedoTextures,this.emissiveMaps=this.sdfs.emissiveTextures,this.normalMaps=this.sdfs.normalTextures,this.bumpMaps=this.sdfs.bumpTextures,this.roughnessMaps=this.sdfs.roughnessTextures,this.metalnessMaps=this.sdfs.metalnessTextures,this.displacementMaps=this.sdfs.displacementTextures}getTextureArrays(){return{albedoMaps:this.albedoMaps,emissiveMaps:this.emissiveMaps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,displacementMaps:this.displacementMaps}}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*U.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+U.COLOR]=n[0],r[i+U.COLOR+1]=n[1],r[i+U.COLOR+2]=n[2]):(r[i+U.COLOR]=n.r,r[i+U.COLOR+1]=n.g,r[i+U.COLOR+2]=n.b);break;case`metalness`:r[i+U.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+U.EMISSIVE]=n[0],r[i+U.EMISSIVE+1]=n[1],r[i+U.EMISSIVE+2]=n[2]):(r[i+U.EMISSIVE]=n.r,r[i+U.EMISSIVE+1]=n.g,r[i+U.EMISSIVE+2]=n.b);break;case`roughness`:r[i+U.ROUGHNESS]=n;break;case`ior`:r[i+U.IOR]=n;break;case`transmission`:r[i+U.TRANSMISSION]=n;break;case`thickness`:r[i+U.THICKNESS]=n;break;case`emissiveIntensity`:r[i+U.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.ATTENUATION_COLOR]=n[0],r[i+U.ATTENUATION_COLOR+1]=n[1],r[i+U.ATTENUATION_COLOR+2]=n[2]):(r[i+U.ATTENUATION_COLOR]=n.r,r[i+U.ATTENUATION_COLOR+1]=n.g,r[i+U.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+U.ATTENUATION_DISTANCE]=n;break;case`dispersion`:r[i+U.DISPERSION]=n;break;case`sheen`:r[i+U.SHEEN]=n;break;case`sheenRoughness`:r[i+U.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.SHEEN_COLOR]=n[0],r[i+U.SHEEN_COLOR+1]=n[1],r[i+U.SHEEN_COLOR+2]=n[2]):(r[i+U.SHEEN_COLOR]=n.r,r[i+U.SHEEN_COLOR+1]=n.g,r[i+U.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+U.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.SPECULAR_COLOR]=n[0],r[i+U.SPECULAR_COLOR+1]=n[1],r[i+U.SPECULAR_COLOR+2]=n[2]):(r[i+U.SPECULAR_COLOR]=n.r,r[i+U.SPECULAR_COLOR+1]=n.g,r[i+U.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+U.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+U.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+U.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+U.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+U.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+U.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+U.OPACITY]=n;break;case`side`:r[i+U.SIDE]=n;break;case`transparent`:r[i+U.TRANSPARENT]=n;break;case`alphaTest`:r[i+U.ALPHA_TEST]=n;break;case`alphaMode`:r[i+U.ALPHA_MODE]=n;break;case`depthWrite`:r[i+U.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+U.NORMAL_SCALE]=n,r[i+U.NORMAL_SCALE+1]=n):(r[i+U.NORMAL_SCALE]=n.x,r[i+U.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+U.BUMP_SCALE]=n;break;case`displacementScale`:r[i+U.DISPLACEMENT_SCALE]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*U.FLOATS_PER_MATERIAL;t.color&&(n[r+U.COLOR]=t.color.r??t.color[0]??1,n[r+U.COLOR+1]=t.color.g??t.color[1]??1,n[r+U.COLOR+2]=t.color.b??t.color[2]??1),n[r+U.METALNESS]=t.metalness??0,t.emissive&&(n[r+U.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+U.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+U.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+U.ROUGHNESS]=t.roughness??1,n[r+U.IOR]=t.ior??1.5,n[r+U.TRANSMISSION]=t.transmission??0,n[r+U.THICKNESS]=t.thickness??.1,n[r+U.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+U.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+U.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+U.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+U.ATTENUATION_DISTANCE]=t.attenuationDistance??1/0,n[r+U.DISPERSION]=t.dispersion??0,n[r+U.VISIBLE]=1,n[r+U.SHEEN]=t.sheen??0,n[r+U.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+U.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+U.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+U.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+U.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+U.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+U.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+U.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+U.IRIDESCENCE]=t.iridescence??0,n[r+U.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+U.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+U.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+U.ALBEDO_MAP_INDEX]=t.map??-1,n[r+U.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+U.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+U.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+U.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+U.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+U.CLEARCOAT]=t.clearcoat??0,n[r+U.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+U.OPACITY]=t.opacity??1,n[r+U.SIDE]=t.side??0,n[r+U.TRANSPARENT]=t.transparent??0,n[r+U.ALPHA_TEST]=t.alphaTest??0,n[r+U.ALPHA_MODE]=t.alphaMode??0,n[r+U.DEPTH_WRITE]=t.depthWrite??1,n[r+U.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+U.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+U.BUMP_SCALE]=t.bumpScale??1,n[r+U.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+U.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:U.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:U.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:U.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:U.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:U.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:U.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:U.DISPLACEMENT_TRANSFORM}];for(let{key:e,offset:o}of a){let a=t[e]??i;for(let e=0;e<9;e++)r+o+e<n.length&&(n[r+o+e]=a[e])}this.materialStorageAttr.needsUpdate=!0,this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*U.FLOATS_PER_MATERIAL,a={map:U.ALBEDO_TRANSFORM,normalMap:U.NORMAL_TRANSFORM,roughnessMap:U.ROUGHNESS_TRANSFORM,metalnessMap:U.METALNESS_TRANSFORM,emissiveMap:U.EMISSIVE_TRANSFORM,bumpMap:U.BUMP_TRANSFORM,displacementMap:U.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){console.warn(`Unknown texture name for transform update: ${t}`);return}for(let e=0;e<9;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}rescanMaterialFeatures(){if(!this.materialStorageAttr?.array)return console.warn(`[MaterialDataManager] Material storage buffer not available for feature scanning`),!1;let e=this.materialStorageAttr.array,t=this.sdfs.materialCount||1,n={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let r=0;r<t;r++){let t=r*U.FLOATS_PER_MATERIAL,i=e[t+U.TRANSMISSION],a=e[t+U.DISPERSION],o=e[t+U.SHEEN],s=e[t+U.IRIDESCENCE],c=e[t+U.CLEARCOAT],l=e[t+U.OPACITY],u=e[t+U.TRANSPARENT],d=e[t+U.ALPHA_TEST];c>0&&(n.hasClearcoat=!0),i>0&&(n.hasTransmission=!0),a>0&&(n.hasDispersion=!0),s>0&&(n.hasIridescence=!0),o>0&&(n.hasSheen=!0),(u>0||l<1||d>0)&&(n.hasTransparency=!0),[c>0,i>0,s>0,o>0].filter(Boolean).length>=2&&(n.hasMultiLobeMaterials=!0)}let r=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(n);return r&&(this.sdfs.sceneFeatures=n),r}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){console.warn(`[MaterialDataManager] No sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(console.log(`[MaterialDataManager] Material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null}};function Ge(e,t,n=0,r=e.length){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function Ke(e,t,n){return .2126*e+.7152*t+.0722*n}function qe(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function Je(e){let{width:t,height:r}=e.image,i=e.image.data,a=!1;if(!i){let n=new OffscreenCanvas(t,r).getContext(`2d`);n.drawImage(e.image,0,0,t,r),i=n.getImageData(0,0,t,r).data,a=!0}let o;if(e.type===n.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===n.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=n.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===n.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=qe(o[e]),o[e+1]=qe(o[e+1]),o[e+2]=qe(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let n=0;n<r;n++){let i=r-n-1,a=n*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:r}}var Ye=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=Je(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=Je(e);this._worker||=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-2MoynL4F.js`).href:new URL(`assets/CDFWorker-2MoynL4F.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});let i=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=i.marginalData,this.conditionalData=i.conditionalData,this.totalSum=i.totalSum,this.width=i.width,this.height=i.height}static computeCDF(e,t,n){let r=new Float32Array(t*n),i=new Float32Array(n),a=0,o=0;for(let s=0;s<n;s++){let n=0;for(let i=0;i<t;i++){let o=s*t+i,c=e[4*o],l=e[4*o+1],u=e[4*o+2],d=Ke(c,l,u);n+=d,a+=d,r[o]=n}if(n!==0)for(let e=s*t,i=s*t+t;e<i;e++)r[e]/=n;o+=n,i[s]=o}if(o!==0)for(let e=0,t=i.length;e<t;e++)i[e]/=o;let s=new Float32Array(n),c=new Float32Array(t*n);for(let e=0;e<n;e++)s[e]=(Ge(i,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let i=e*t+n;c[i]=(Ge(r,(n+1)/t,e*t,t)+.5)/t}return{marginalData:s,conditionalData:c,totalSum:a}}},Xe=Math.PI,Ze=Math.PI*2,Qe=Math.E,$e=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],et=[183999185144339.78,277980239196605.28,407904795438610.94],tt=1.6110731556870734,nt=1.5,rt=1e3,it=8400,at=1250,ot=.9999566769464484,st=.05968310365946075,ct=.07957747154594767;function lt(e){return rt*Math.max(0,1-Qe**+(-(tt-Math.acos(Math.max(-1,Math.min(1,e))))/nt))}function ut(e){let t=.2*e*1e-17;return[.434*t*et[0],.434*t*et[1],.434*t*et[2]]}function dt(e){return st*(1+e**2)}function ft(e,t){let n=t*t;return ct*((1-n)/(1-2*t*e+n)**1.5)}function pt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function mt(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return t===0?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]}function ht(e,t,n,r,i,a,o,s){let c=(1-t)*Xe,l=(e-.5)*Ze,u=Math.sin(c),d=mt([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=mt(n),p=lt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[$e[0]*m,$e[1]*m,$e[2]*m],g=ut(s),_=[g[0]*a,g[1]*a,g[2]*a],v=Math.acos(Math.max(0,d[1])),y=Math.cos(v)+.15*(93.885-180/Xe*v)**-1.253,b=it/y,x=at/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=pt(d,f),w=dt(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=ft(C,o),D=[_[0]*E,_[1]*E,_[2]*E],O=[T[0]+D[0],T[1]+D[1],T[2]+D[2]],k=[h[0]+_[0],h[1]+_[1],h[2]+_[2]],A=[(p*(O[0]/k[0])*(1-S[0]))**1.5,(p*(O[1]/k[1])*(1-S[1]))**1.5,(p*(O[2]/k[2])*(1-S[2]))**1.5],j=Math.max(0,Math.min(1,1-(1-f[1])**5)),M=[Math.sqrt(p*(O[0]/k[0])*S[0]),Math.sqrt(p*(O[1]/k[1])*S[1]),Math.sqrt(p*(O[2]/k[2])*S[2])],N=1-j;for(let e=0;e<3;e++){let t=1*(1-N)+M[e]*N;A[e]*=t}let ee=[.1*S[0],.1*S[1],.1*S[2]],te=gt(ot,ot+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let P=65504;return[Math.min((A[0]+ee[0])*.04,P),Math.min((A[1]+ee[1])*.04+3e-4,P),Math.min((A[2]+ee[2])*.04+75e-5,P),1]}function gt(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var _t=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=ht((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},vt=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},yt=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Ye,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new n.DataTexture(new Float32Array([0,0,0,1]),1,1,n.RGBAFormat,n.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new n.Vector2,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new n.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new n.Color(V.gradientZenithColor),gradientHorizonColor:new n.Color(V.gradientHorizonColor),gradientGroundColor:new n.Color(V.gradientGroundColor),solidSkyColor:new n.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFStorageBuffers(){this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,1]),1),this.envMarginalStorageNode=(0,o.storage)(this.envMarginalStorageAttr,`float`,2).toReadOnly(),this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,0,1,1]),1),this.envConditionalStorageNode=(0,o.storage)(this.envConditionalStorageAttr,`float`,4).toReadOnly()}setEnvMarginalData(e){e&&(this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envMarginalStorageNode.value=this.envMarginalStorageAttr,this.envMarginalStorageNode.bufferCount=e.length)}setEnvConditionalData(e){e&&(this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envConditionalStorageNode.value=this.envConditionalStorageAttr,this.envConditionalStorageNode.bufferCount=e.length)}_updateCDFStorageBuffers(){this.setEnvMarginalData(this.equirectHdrInfo.marginalData),this.setEnvConditionalData(this.equirectHdrInfo.conditionalData)}getCDFStorageNodes(){return{marginalNode:this.envMarginalStorageNode,conditionalNode:this.envConditionalStorageNode}}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),console.log(`EnvironmentManager: Environment map ${e.image.width}x${e.image.height}`))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`useEnvMapIS`,1);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),console.log(`Environment CDF built in ${this.cdfBuildTime.toFixed(2)}ms (worker: ${e})`)}catch(e){console.error(`Error building environment CDF:`,e),this.uniforms.set(`useEnvMapIS`,0),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e){this.scene.environment=e,this.setEnvironmentTexture(e),e?await this.buildEnvironmentCDF():(this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0));let t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}async generateGradientTexture(){this.simpleSkyRenderer||=new vt(512,256);let e={zenithColor:this.envParams.gradientZenithColor,horizonColor:this.envParams.gradientHorizonColor,groundColor:this.envParams.gradientGroundColor};try{let t=this.simpleSkyRenderer.renderGradient(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){console.error(`Error generating gradient sky:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new vt(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){console.error(`Error generating solid color sky:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new _t(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),console.log(`Sun parameters synced: dir=${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){console.error(`Error generating procedural sky:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.skySunElevation*(Math.PI/180);return new n.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null}};function bt(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>bt(i.apply(e,n),t):i}})}function K(e,t=null){let n=(0,o.struct)(e,t),r=new Set(Object.keys(e)),i=(...e)=>bt(n(...e),r);return i.layout=n.layout,i.isStruct=!0,i.wrap=e=>bt(e,r),i}var xt=K({origin:`vec3`,direction:`vec3`}),St=K({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`}),Ct=K({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`});K({position:`vec3`,radius:`float`,material:St});var wt=K({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});K({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:St,materialIndex:`int`,meshIndex:`int`}),K({color:`vec4`,samples:`int`});var Tt=K({direction:`vec3`,value:`vec3`,pdf:`float`}),Et=K({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Dt=K({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),Ot=K({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),kt=K({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),At=K({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),jt=K({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Mt=K({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,specularColor:`vec3`,isMetallic:`bool`,isPurelyDiffuse:`bool`,hasSpecialFeatures:`bool`,alpha:`float`,k:`float`,alpha2:`float`,tsAlbedo:`vec4`,tsEmissive:`vec3`,tsMetalness:`float`,tsRoughness:`float`,tsNormal:`vec3`,tsHasTextures:`bool`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});K({brdfWeights:Et,samplingInfo:Dt,materialCache:Mt,materialClass:At,weightsComputed:`bool`,texturesLoaded:`bool`,classificationCached:`bool`,materialCacheCached:`bool`,pathImportance:`float`,lastMaterialIndex:`int`});var Nt=K({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Pt=K({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),Ft=K({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});K({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),K({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var q=3.14159,It=1/q,Lt=2*q,J=1e-6,Rt=.05,zt=.089,Bt=.001,Vt=(0,o.vec3)(.2126,.7152,.0722),Y=U.SLOTS_PER_MATERIAL,Ht=U.SLOT,X=Ht,Ut=(0,o.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,o.wgslFn)(`
|
|
149
|
+
`,[ne,P]),I={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},L=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||I.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case I.ALWAYS:return!0;case I.PER_CYCLE:return t===0?!0:n===!0;case I.PER_TILE:return!0;case I.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},ge=class{constructor(e,t,n){this.width=e,this.height=t,this.tiles=n,this.tileIndex=0,this.tileBoundsCache=new Map,this.totalTilesCache=n*n,this.currentTileBounds=null,this.spiralOrder=this.generateSpiralOrder(n)}calculateTileBounds(e,t,n,r){let i=`${e}-${t}-${n}-${r}`;if(this.tileBoundsCache.has(i))return this.tileBoundsCache.get(i);let a=Math.ceil(n/t),o=Math.ceil(r/t),s=e%t,c=Math.floor(e/t),l=s*a,u=c*o,d={x:l,y:u,width:Math.min(a,n-l),height:Math.min(o,r-u)};return this.tileBoundsCache.set(i,d),d}generateSpiralOrder(e){let t=e*e,n=[];for(let r=0;r<t;r++){let t=r%e,i=Math.floor(r/e),a=(e-1)/2,o=t-a,s=i-a,c=Math.abs(o)+Math.abs(s),l=Math.sqrt(o*o+s*s),u=Math.atan(s,o);u<0&&(u+=2*Math.PI);let d=(t+i*e)*.001;n.push({index:r,x:t,y:i,manhattanDistance:c,euclideanDistance:l,angle:u,positionOffset:d})}return n.sort((e,t)=>{let n=e.manhattanDistance-t.manhattanDistance;if(Math.abs(n)>.01)return n;let r=e.euclideanDistance-t.euclideanDistance;if(Math.abs(r)>.01)return r;let i=e.angle-t.angle;return Math.abs(i)>.01?i:e.positionOffset-t.positionOffset}),n.map(e=>e.index)}handleTileRendering(e,t,n){let r=!0,i=-1,a=null,o=!0;if(t===1)if(n===0)i=-1,o=!0;else{let e=(n-1)%this.totalTilesCache;i=this.spiralOrder[e],a=this.calculateTileBounds(i,this.tiles,this.width,this.height),o=e===this.totalTilesCache-1,r=o}else i=-1,o=!0;return this.tileIndex=i,{tileIndex:i,tileBounds:a,shouldSwapTargets:r,isCompleteCycle:o}}setTileCount(e){if(e<1&&(console.warn(`TileManager: Tile count must be at least 1, clamping to 1`),e=1),e>10&&console.warn(`TileManager: Tile count > 10 may cause performance issues`),e>6){let t=e*e;console.warn(`TileManager: ${e}x${e} = ${t} tiles may impact performance and memory usage`)}this.tiles=e,this.totalTilesCache=e*e,this.tileIndex=0,this.spiralOrder=this.generateSpiralOrder(e),this.tileBoundsCache.clear()}setSize(e,t){this.width=e,this.height=t,this.tileBoundsCache.clear()}calculateCompletionThreshold(e){return this.totalTilesCache*e}getCurrentTileInfo(){return{tileIndex:this.tileIndex,tiles:this.tiles,totalTiles:this.totalTilesCache,currentBounds:this.currentTileBounds}}dispose(){this.tileBoundsCache.clear(),this.currentTileBounds=null}},_e=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!0,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,numRaysPerPixel:1,useAdaptiveSampling:!0,useEnvMapIS:!0,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},R={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`},ve=null;function ye(e){ve=e}var be=()=>ve?.({type:R.LOADING_RESET}),z=e=>{ve?.({type:R.LOADING_UPDATE,...e})},xe=e=>{ve?.({type:R.STATS_UPDATE,...e})};function Se(e){let t=e.frameCount||0;if(e.renderMode?.value===1&&t>0){let n=e.tileManager?.totalTilesCache||1;return 1+Math.floor((t-1)/n)}return t}function Ce(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(we(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;we(e),e.dispose()}}function we(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function Te({material:e,geometry:t,children:n}){if(e&&Ce(e),t&&t.dispose(),n.length>0)for(let e of n)Te(e)}function B(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Ce(e);return}for(;e.children.length>0;)for(let t of e.children)B(t);Te(e),e.removeFromParent(),e.clear()}}function Ee(e,t,n){return e===1?n*t:t}function De(e,t,n,r=!1){return r?1:t===0?1/(e+1):e===0?1:1/(1+Math.floor((e-1)/n)+1)}function Oe(){let e=0,t=0,n=0,r=0;return{start(){e=performance.now()},end(){t=performance.now();let i=t-e;return r+=i,n++,i},getAverageFrameTime(){return n>0?r/n:0},getFPS(){let e=this.getAverageFrameTime();return e>0?1e3/e:0},reset(){n=0,r=0}}}function ke(e,r){let i=new t.StorageTexture(e,r);return i.type=n.FloatType,i.format=n.RGBAFormat,i.minFilter=n.LinearFilter,i.magFilter=n.LinearFilter,i}var Ae=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,e>0&&t>0&&this.create(e,t)}create(e,r){this.dispose(),this.renderWidth=e,this.renderHeight=r,this.writeColor=ke(e,r),this.writeNormalDepth=ke(e,r),this.writeAlbedo=ke(e,r),this.readTarget=new t.RenderTarget(e,r,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,console.log(`StorageTexturePool: Created ${e}x${r} (3 write StorageTextures + 1 MRT RenderTarget)`)}ensureSize(e,t){return this.renderWidth!==e||this.renderHeight!==t||!this.writeColor?(this.create(e,t),!0):!1}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e){e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0]),e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1]),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2])}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.writeColor?.setSize(e,t),this.writeNormalDepth?.setSize(e,t),this.writeAlbedo?.setSize(e,t),this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},V={resolution:512,canvasWidth:512,canvasHeight:512,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,useImportanceSampledEnvironment:!0,environmentIntensity:1,backgroundIntensity:1,environmentRotation:270,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,samplesPerPixel:1,transmissiveBounces:5,samplingTechnique:3,enableEmissiveTriangleSampling:!1,emissiveBoost:1,adaptiveSampling:!1,adaptiveSamplingMin:1,adaptiveSamplingMax:8,adaptiveSamplingVarianceThreshold:.1,temporalVarianceWeight:.6,enableEarlyTermination:!0,earlyTerminationThreshold:.002,showAdaptiveSamplingHelper:!1,performanceModeAdaptive:`medium`,fireflyThreshold:3,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tiles:3,tilesHelper:!1,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,pixelEdgeSharpness:.75,edgeSharpenSpeed:.05,edgeThreshold:1,enableOIDN:!1,oidnQuality:`fast`,debugGbufferMaps:!1,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,debugVisScale:100,denoiserStrategy:`edgeaware`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,ssrcTemporalAlpha:.1,ssrcSpatialRadius:4,ssrcSpatialWeight:.4,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},je={low:{temporalAlpha:.3,atrousIterations:1,phiColor:30,phiNormal:64,phiDepth:2,phiLuminance:6,maxAccumFrames:8,varianceBoost:.5},medium:{temporalAlpha:.1,atrousIterations:3,phiColor:20,phiNormal:128,phiDepth:1,phiLuminance:2,maxAccumFrames:32,varianceBoost:1},high:{temporalAlpha:.05,atrousIterations:8,phiColor:5,phiNormal:256,phiDepth:.5,phiLuminance:2,maxAccumFrames:64,varianceBoost:1.5}},Me={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},Ne={clearMorning:{name:`Clear Morning`,sunAzimuth:90,sunElevation:20,sunIntensity:15,rayleighDensity:.9,turbidity:.8},clearNoon:{name:`Clear Noon`,sunAzimuth:0,sunElevation:75,sunIntensity:20,rayleighDensity:1,turbidity:.3},overcast:{name:`Overcast`,sunAzimuth:0,sunElevation:45,sunIntensity:6,rayleighDensity:.6,turbidity:4},goldenHour:{name:`Golden Hour`,sunAzimuth:270,sunElevation:10,sunIntensity:19,rayleighDensity:.8,turbidity:1.2},sunset:{name:`Sunset`,sunAzimuth:270,sunElevation:2,sunIntensity:18,rayleighDensity:.7,turbidity:2},dusk:{name:`Dusk`,sunAzimuth:270,sunElevation:-8,sunIntensity:8,rayleighDensity:.5,turbidity:1.5}},Pe={portrait:{name:`Portrait`,description:`Shallow depth of field, background blur`,fov:45,focusDistance:1.5,aperture:1.4,focalLength:135,apertureScale:1.5},landscape:{name:`Landscape`,description:`Maximum depth of field, everything in focus`,fov:65,focusDistance:10,aperture:16,focalLength:24,apertureScale:.5},macro:{name:`Macro`,description:`Extreme close-up with thin focus plane`,fov:40,focusDistance:.3,aperture:2,focalLength:100,apertureScale:2},product:{name:`Product`,description:`Sharp detail with subtle background separation`,fov:50,focusDistance:.8,aperture:2.8,focalLength:85,apertureScale:1},architectural:{name:`Architectural`,description:`Wide view with deep focus`,fov:75,focusDistance:5,aperture:11,focalLength:16,apertureScale:.5},cinematic:{name:`Cinematic`,description:`Dramatic depth separation with anamorphic bokeh`,fov:35,focusDistance:3,aperture:1.4,focalLength:200,apertureScale:1.8,anamorphicRatio:1.5}},Fe={MANUAL:`manual`,AUTO:`auto`},Ie={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},H={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},U={SLOTS_PER_MATERIAL:27,FLOATS_PER_MATERIAL:108,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26}},W={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},Le={PIXELS_PER_MATERIAL:27,RGBA_COMPONENTS:4,VEC4_PER_TRIANGLE:8,VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192},Re=[0,0,1,1,0,0,0,1],ze={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,enableAlphaShadows:!0,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},G={maxSamples:V.maxSamples,bounces:V.bounces,samplesPerPixel:V.samplesPerPixel,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:V.transmissiveBounces,tiles:V.tiles,tilesHelper:V.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},Be={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,CHUNK_SIZE_THRESHOLD:64*1024*1024,STREAM_BATCH_SIZE:4},Ve={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},He=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=t?1:0:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let r=(e,t,n)=>{let r=(0,o.uniform)(t,n);return this._uniforms.set(e,r),r},i=(e,t)=>(this._booleans.add(e),r(e,t?1:0,`int`));r(`frame`,0,`uint`),r(`maxBounces`,V.bounces,`int`),r(`samplesPerPixel`,V.samplesPerPixel,`int`),r(`maxSamples`,V.maxSamples,`int`),r(`transmissiveBounces`,V.transmissiveBounces,`int`),r(`visMode`,V.debugMode,`int`),r(`debugVisScale`,V.debugVisScale,`float`),i(`enableAccumulation`,!0),r(`accumulationAlpha`,0,`float`),i(`cameraIsMoving`,!1),i(`hasPreviousAccumulated`,!1),r(`environmentIntensity`,V.environmentIntensity,`float`),r(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`showBackground`,V.showBackground),i(`transparentBackground`,V.transparentBackground),i(`enableEnvironment`,V.enableEnvironment),r(`environmentMatrix`,new n.Matrix4,`mat4`),i(`useEnvMapIS`,V.useImportanceSampledEnvironment),r(`envTotalSum`,0,`float`),r(`envResolution`,new n.Vector2(1,1),`vec2`),r(`sunDirection`,new n.Vector3(0,1,0),`vec3`),r(`sunAngularSize`,.0087,`float`),i(`hasSun`,!1),r(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),r(`exposure`,V.exposure,`float`),r(`numDirectionalLights`,0,`int`),r(`numAreaLights`,0,`int`),r(`numPointLights`,0,`int`),r(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,o.uniformArray)(new Float32Array(128),`float`),area:(0,o.uniformArray)(new Float32Array(208),`float`),point:(0,o.uniformArray)(new Float32Array(144),`float`),spot:(0,o.uniformArray)(new Float32Array(224),`float`)},r(`cameraWorldMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrixInverse`,new n.Matrix4,`mat4`),r(`cameraViewMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrix`,new n.Matrix4,`mat4`),i(`enableDOF`,V.enableDOF),r(`focusDistance`,V.focusDistance,`float`),r(`focalLength`,V.focalLength,`float`),r(`aperture`,V.aperture,`float`),r(`apertureScale`,1,`float`),r(`anamorphicRatio`,V.anamorphicRatio??1,`float`),r(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,O),O.value=V.samplingTechnique,i(`useAdaptiveSampling`,V.adaptiveSampling),r(`adaptiveSamplingMin`,V.adaptiveSamplingMin??1,`int`),r(`adaptiveSamplingMax`,V.adaptiveSamplingMax,`int`),r(`fireflyThreshold`,V.fireflyThreshold,`float`),i(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),r(`emissiveBoost`,V.emissiveBoost,`float`),r(`emissiveTriangleCount`,0,`int`),r(`emissiveTotalPower`,0,`float`),r(`lightBVHNodeCount`,0,`int`),r(`renderMode`,V.renderMode,`int`),i(`enableAlphaShadows`,V.enableAlphaShadows),r(`resolution`,new n.Vector2(e,t),`vec2`),r(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Ve[e]||e}},Ue=U.SLOTS_PER_MATERIAL,We=class{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let n=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=n):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,o.storage)(this.materialStorageAttr,`vec4`,n).toReadOnly()),this.materialCount=Math.floor(n/Ue),console.log(`MaterialDataManager: ${this.materialCount} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.albedoMaps&&(this.albedoMaps=e.albedoMaps),e.emissiveMaps&&(this.emissiveMaps=e.emissiveMaps),e.normalMaps&&(this.normalMaps=e.normalMaps),e.bumpMaps&&(this.bumpMaps=e.bumpMaps),e.roughnessMaps&&(this.roughnessMaps=e.roughnessMaps),e.metalnessMaps&&(this.metalnessMaps=e.metalnessMaps),e.displacementMaps&&(this.displacementMaps=e.displacementMaps)}loadTexturesFromSdfs(){this.albedoMaps=this.sdfs.albedoTextures,this.emissiveMaps=this.sdfs.emissiveTextures,this.normalMaps=this.sdfs.normalTextures,this.bumpMaps=this.sdfs.bumpTextures,this.roughnessMaps=this.sdfs.roughnessTextures,this.metalnessMaps=this.sdfs.metalnessTextures,this.displacementMaps=this.sdfs.displacementTextures}getTextureArrays(){return{albedoMaps:this.albedoMaps,emissiveMaps:this.emissiveMaps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,displacementMaps:this.displacementMaps}}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*U.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+U.COLOR]=n[0],r[i+U.COLOR+1]=n[1],r[i+U.COLOR+2]=n[2]):(r[i+U.COLOR]=n.r,r[i+U.COLOR+1]=n.g,r[i+U.COLOR+2]=n.b);break;case`metalness`:r[i+U.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+U.EMISSIVE]=n[0],r[i+U.EMISSIVE+1]=n[1],r[i+U.EMISSIVE+2]=n[2]):(r[i+U.EMISSIVE]=n.r,r[i+U.EMISSIVE+1]=n.g,r[i+U.EMISSIVE+2]=n.b);break;case`roughness`:r[i+U.ROUGHNESS]=n;break;case`ior`:r[i+U.IOR]=n;break;case`transmission`:r[i+U.TRANSMISSION]=n;break;case`thickness`:r[i+U.THICKNESS]=n;break;case`emissiveIntensity`:r[i+U.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.ATTENUATION_COLOR]=n[0],r[i+U.ATTENUATION_COLOR+1]=n[1],r[i+U.ATTENUATION_COLOR+2]=n[2]):(r[i+U.ATTENUATION_COLOR]=n.r,r[i+U.ATTENUATION_COLOR+1]=n.g,r[i+U.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+U.ATTENUATION_DISTANCE]=n;break;case`dispersion`:r[i+U.DISPERSION]=n;break;case`sheen`:r[i+U.SHEEN]=n;break;case`sheenRoughness`:r[i+U.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.SHEEN_COLOR]=n[0],r[i+U.SHEEN_COLOR+1]=n[1],r[i+U.SHEEN_COLOR+2]=n[2]):(r[i+U.SHEEN_COLOR]=n.r,r[i+U.SHEEN_COLOR+1]=n.g,r[i+U.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+U.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+U.SPECULAR_COLOR]=n[0],r[i+U.SPECULAR_COLOR+1]=n[1],r[i+U.SPECULAR_COLOR+2]=n[2]):(r[i+U.SPECULAR_COLOR]=n.r,r[i+U.SPECULAR_COLOR+1]=n.g,r[i+U.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+U.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+U.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+U.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+U.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+U.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+U.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+U.OPACITY]=n;break;case`side`:r[i+U.SIDE]=n;break;case`transparent`:r[i+U.TRANSPARENT]=n;break;case`alphaTest`:r[i+U.ALPHA_TEST]=n;break;case`alphaMode`:r[i+U.ALPHA_MODE]=n;break;case`depthWrite`:r[i+U.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+U.NORMAL_SCALE]=n,r[i+U.NORMAL_SCALE+1]=n):(r[i+U.NORMAL_SCALE]=n.x,r[i+U.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+U.BUMP_SCALE]=n;break;case`displacementScale`:r[i+U.DISPLACEMENT_SCALE]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*U.FLOATS_PER_MATERIAL;t.color&&(n[r+U.COLOR]=t.color.r??t.color[0]??1,n[r+U.COLOR+1]=t.color.g??t.color[1]??1,n[r+U.COLOR+2]=t.color.b??t.color[2]??1),n[r+U.METALNESS]=t.metalness??0,t.emissive&&(n[r+U.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+U.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+U.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+U.ROUGHNESS]=t.roughness??1,n[r+U.IOR]=t.ior??1.5,n[r+U.TRANSMISSION]=t.transmission??0,n[r+U.THICKNESS]=t.thickness??.1,n[r+U.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+U.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+U.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+U.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+U.ATTENUATION_DISTANCE]=t.attenuationDistance??1/0,n[r+U.DISPERSION]=t.dispersion??0,n[r+U.VISIBLE]=1,n[r+U.SHEEN]=t.sheen??0,n[r+U.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+U.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+U.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+U.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+U.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+U.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+U.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+U.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+U.IRIDESCENCE]=t.iridescence??0,n[r+U.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+U.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+U.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+U.ALBEDO_MAP_INDEX]=t.map??-1,n[r+U.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+U.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+U.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+U.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+U.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+U.CLEARCOAT]=t.clearcoat??0,n[r+U.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+U.OPACITY]=t.opacity??1,n[r+U.SIDE]=t.side??0,n[r+U.TRANSPARENT]=t.transparent??0,n[r+U.ALPHA_TEST]=t.alphaTest??0,n[r+U.ALPHA_MODE]=t.alphaMode??0,n[r+U.DEPTH_WRITE]=t.depthWrite??1,n[r+U.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+U.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+U.BUMP_SCALE]=t.bumpScale??1,n[r+U.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+U.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:U.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:U.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:U.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:U.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:U.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:U.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:U.DISPLACEMENT_TRANSFORM}];for(let{key:e,offset:o}of a){let a=t[e]??i;for(let e=0;e<9;e++)r+o+e<n.length&&(n[r+o+e]=a[e])}this.materialStorageAttr.needsUpdate=!0,this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*U.FLOATS_PER_MATERIAL,a={map:U.ALBEDO_TRANSFORM,normalMap:U.NORMAL_TRANSFORM,roughnessMap:U.ROUGHNESS_TRANSFORM,metalnessMap:U.METALNESS_TRANSFORM,emissiveMap:U.EMISSIVE_TRANSFORM,bumpMap:U.BUMP_TRANSFORM,displacementMap:U.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){console.warn(`Unknown texture name for transform update: ${t}`);return}for(let e=0;e<9;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}rescanMaterialFeatures(){if(!this.materialStorageAttr?.array)return console.warn(`[MaterialDataManager] Material storage buffer not available for feature scanning`),!1;let e=this.materialStorageAttr.array,t=this.sdfs.materialCount||1,n={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let r=0;r<t;r++){let t=r*U.FLOATS_PER_MATERIAL,i=e[t+U.TRANSMISSION],a=e[t+U.DISPERSION],o=e[t+U.SHEEN],s=e[t+U.IRIDESCENCE],c=e[t+U.CLEARCOAT],l=e[t+U.OPACITY],u=e[t+U.TRANSPARENT],d=e[t+U.ALPHA_TEST];c>0&&(n.hasClearcoat=!0),i>0&&(n.hasTransmission=!0),a>0&&(n.hasDispersion=!0),s>0&&(n.hasIridescence=!0),o>0&&(n.hasSheen=!0),(u>0||l<1||d>0)&&(n.hasTransparency=!0),[c>0,i>0,s>0,o>0].filter(Boolean).length>=2&&(n.hasMultiLobeMaterials=!0)}let r=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(n);return r&&(this.sdfs.sceneFeatures=n),r}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){console.warn(`[MaterialDataManager] No sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(console.log(`[MaterialDataManager] Material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null}};async function Ge(e){let t=e instanceof URL?e.href:e,n=await fetch(t);if(!n.ok)throw Error(`Failed to fetch worker script: ${n.status}`);let r=new Blob([await n.text()],{type:`application/javascript`});return new Worker(URL.createObjectURL(r))}function Ke(e,t,n=0,r=e.length){let i=n,a=n+r-1;for(;i<a;){let n=i+a>>1;e[n]<t?i=n+1:a=n}return i-n}function qe(e,t,n){return .2126*e+.7152*t+.0722*n}function Je(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function Ye(e){let{width:t,height:r}=e.image,i=e.image.data,a=!1;if(!i){let n=new OffscreenCanvas(t,r).getContext(`2d`);n.drawImage(e.image,0,0,t,r),i=n.getImageData(0,0,t,r).data,a=!0}let o;if(e.type===n.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===n.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=n.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===n.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=Je(o[e]),o[e+1]=Je(o[e+1]),o[e+2]=Je(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let n=0;n<r;n++){let i=r-n-1,a=n*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:r}}var Xe=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=Ye(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=Ye(e);if(!this._worker)try{this._worker=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-2MoynL4F.js`).href:new URL(`assets/CDFWorker-2MoynL4F.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;this._worker=await Ge(new URL(`data:text/javascript;base64,LyoqCiAqIFdlYiBXb3JrZXIgZm9yIGNvbXB1dGluZyBlbnZpcm9ubWVudCBtYXAgQ0RGIChDdW11bGF0aXZlIERpc3RyaWJ1dGlvbiBGdW5jdGlvbikKICogZm9yIGltcG9ydGFuY2Ugc2FtcGxpbmcuIFB1cmUgbWF0aCDigJQgbm8gVGhyZWUuanMgZGVwZW5kZW5jaWVzLgogKgogKiBJbnB1dDogIHsgZmxvYXREYXRhOiBGbG9hdDMyQXJyYX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bGYub25tZXNzYWdlID0gZnVuY3Rpb24gKCBlICkgewoKCWNvbnN0IHsgZmxvYXREYXRhLCB3aWR0aCwgaGVpZ2h0IH0gPSBlLmRhdGE7CgoJdHJ5IHsKCgkJY29uc3QgcmVzdWx0ID0gYnVpbGRDREYoIGZsb2F0RGF0YSwgd2lkdGgsIGhlaWdodCApOwoKCQkvLyBUcmFuc2ZlciBhcnJheXMgYmFjayB6ZXJvLWNvcHkKCQlzZWxmLnBvc3RNZXNzYWdlKAoJCQl7CgkJCQltYXJnaW5hbERhdGE6IHJlc3VsdC5tYXJnaW5hbERhdGEsCgkJCQljb25kaXRpb25hbERhdGE6IHJlc3VsdC5jb25kaXRpb25hbERhdGEsCgkJCQl0b3RhbFN1bTogcmVzdWx0LnRvdGFsU3VtLAoJCQkJd2lkdGgsCgkJCQloZWlnaHQsCgkJCX0sCgkJCVsgcmVzdWx0Lm1hcmdpbmFsRGF0YS5idWZmZXIsIHJlc3VsdC5jb25kaXRpb25hbERhdGEuYnVmZmVyIF0KCQkpOwoKCX0gY2F0Y2ggKCBlcnJvciApIHsKCgkJc2VsZi5wb3N0TWVzc2FnZSggeyBlcnJvcjogZXJyb3IubWVzc2FnZSB9ICk7CgoJfQoKfTsK`,``+{}.url))}let i=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=i.marginalData,this.conditionalData=i.conditionalData,this.totalSum=i.totalSum,this.width=i.width,this.height=i.height}static computeCDF(e,t,n){let r=new Float32Array(t*n),i=new Float32Array(n),a=0,o=0;for(let s=0;s<n;s++){let n=0;for(let i=0;i<t;i++){let o=s*t+i,c=e[4*o],l=e[4*o+1],u=e[4*o+2],d=qe(c,l,u);n+=d,a+=d,r[o]=n}if(n!==0)for(let e=s*t,i=s*t+t;e<i;e++)r[e]/=n;o+=n,i[s]=o}if(o!==0)for(let e=0,t=i.length;e<t;e++)i[e]/=o;let s=new Float32Array(n),c=new Float32Array(t*n);for(let e=0;e<n;e++)s[e]=(Ke(i,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let i=e*t+n;c[i]=(Ke(r,(n+1)/t,e*t,t)+.5)/t}return{marginalData:s,conditionalData:c,totalSum:a}}},Ze=Math.PI,Qe=Math.PI*2,$e=Math.E,et=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],tt=[183999185144339.78,277980239196605.28,407904795438610.94],nt=1.6110731556870734,rt=1.5,it=1e3,at=8400,ot=1250,st=.9999566769464484,ct=.05968310365946075,lt=.07957747154594767;function ut(e){return it*Math.max(0,1-$e**+(-(nt-Math.acos(Math.max(-1,Math.min(1,e))))/rt))}function dt(e){let t=.2*e*1e-17;return[.434*t*tt[0],.434*t*tt[1],.434*t*tt[2]]}function ft(e){return ct*(1+e**2)}function pt(e,t){let n=t*t;return lt*((1-n)/(1-2*t*e+n)**1.5)}function mt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function ht(e){let t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return t===0?[0,0,0]:[e[0]/t,e[1]/t,e[2]/t]}function gt(e,t,n,r,i,a,o,s){let c=(1-t)*Ze,l=(e-.5)*Qe,u=Math.sin(c),d=ht([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=ht(n),p=ut(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[et[0]*m,et[1]*m,et[2]*m],g=dt(s),_=[g[0]*a,g[1]*a,g[2]*a],v=Math.acos(Math.max(0,d[1])),y=Math.cos(v)+.15*(93.885-180/Ze*v)**-1.253,b=at/y,x=ot/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=mt(d,f),w=ft(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=pt(C,o),D=[_[0]*E,_[1]*E,_[2]*E],O=[T[0]+D[0],T[1]+D[1],T[2]+D[2]],k=[h[0]+_[0],h[1]+_[1],h[2]+_[2]],A=[(p*(O[0]/k[0])*(1-S[0]))**1.5,(p*(O[1]/k[1])*(1-S[1]))**1.5,(p*(O[2]/k[2])*(1-S[2]))**1.5],j=Math.max(0,Math.min(1,1-(1-f[1])**5)),M=[Math.sqrt(p*(O[0]/k[0])*S[0]),Math.sqrt(p*(O[1]/k[1])*S[1]),Math.sqrt(p*(O[2]/k[2])*S[2])],N=1-j;for(let e=0;e<3;e++){let t=1*(1-N)+M[e]*N;A[e]*=t}let ee=[.1*S[0],.1*S[1],.1*S[2]],te=_t(st,st+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let P=65504;return[Math.min((A[0]+ee[0])*.04,P),Math.min((A[1]+ee[1])*.04+3e-4,P),Math.min((A[2]+ee[2])*.04+75e-5,P),1]}function _t(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var vt=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=gt((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},yt=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},bt=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Xe,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new n.DataTexture(new Float32Array([0,0,0,1]),1,1,n.RGBAFormat,n.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new n.Vector2,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new n.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new n.Color(V.gradientZenithColor),gradientHorizonColor:new n.Color(V.gradientHorizonColor),gradientGroundColor:new n.Color(V.gradientGroundColor),solidSkyColor:new n.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFStorageBuffers(){this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,1]),1),this.envMarginalStorageNode=(0,o.storage)(this.envMarginalStorageAttr,`float`,2).toReadOnly(),this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,0,1,1]),1),this.envConditionalStorageNode=(0,o.storage)(this.envConditionalStorageAttr,`float`,4).toReadOnly()}setEnvMarginalData(e){e&&(this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envMarginalStorageNode.value=this.envMarginalStorageAttr,this.envMarginalStorageNode.bufferCount=e.length)}setEnvConditionalData(e){e&&(this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envConditionalStorageNode.value=this.envConditionalStorageAttr,this.envConditionalStorageNode.bufferCount=e.length)}_updateCDFStorageBuffers(){this.setEnvMarginalData(this.equirectHdrInfo.marginalData),this.setEnvConditionalData(this.equirectHdrInfo.conditionalData)}getCDFStorageNodes(){return{marginalNode:this.envMarginalStorageNode,conditionalNode:this.envConditionalStorageNode}}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),console.log(`EnvironmentManager: Environment map ${e.image.width}x${e.image.height}`))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`useEnvMapIS`,1);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),console.log(`Environment CDF built in ${this.cdfBuildTime.toFixed(2)}ms (worker: ${e})`)}catch(e){console.error(`Error building environment CDF:`,e),this.uniforms.set(`useEnvMapIS`,0),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e){this.scene.environment=e,this.setEnvironmentTexture(e),e?await this.buildEnvironmentCDF():(this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0));let t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}async generateGradientTexture(){this.simpleSkyRenderer||=new yt(512,256);let e={zenithColor:this.envParams.gradientZenithColor,horizonColor:this.envParams.gradientHorizonColor,groundColor:this.envParams.gradientGroundColor};try{let t=this.simpleSkyRenderer.renderGradient(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){console.error(`Error generating gradient sky:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new yt(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){console.error(`Error generating solid color sky:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new vt(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),console.log(`Sun parameters synced: dir=${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){console.error(`Error generating procedural sky:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.skySunElevation*(Math.PI/180);return new n.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null}};function xt(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>xt(i.apply(e,n),t):i}})}function K(e,t=null){let n=(0,o.struct)(e,t),r=new Set(Object.keys(e)),i=(...e)=>xt(n(...e),r);return i.layout=n.layout,i.isStruct=!0,i.wrap=e=>xt(e,r),i}var St=K({origin:`vec3`,direction:`vec3`}),Ct=K({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`}),wt=K({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`});K({position:`vec3`,radius:`float`,material:Ct});var Tt=K({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});K({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:Ct,materialIndex:`int`,meshIndex:`int`}),K({color:`vec4`,samples:`int`});var Et=K({direction:`vec3`,value:`vec3`,pdf:`float`}),Dt=K({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Ot=K({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),kt=K({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),At=K({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),jt=K({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Mt=K({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Nt=K({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,specularColor:`vec3`,isMetallic:`bool`,isPurelyDiffuse:`bool`,hasSpecialFeatures:`bool`,alpha:`float`,k:`float`,alpha2:`float`,tsAlbedo:`vec4`,tsEmissive:`vec3`,tsMetalness:`float`,tsRoughness:`float`,tsNormal:`vec3`,tsHasTextures:`bool`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});K({brdfWeights:Dt,samplingInfo:Ot,materialCache:Nt,materialClass:jt,weightsComputed:`bool`,texturesLoaded:`bool`,classificationCached:`bool`,materialCacheCached:`bool`,pathImportance:`float`,lastMaterialIndex:`int`});var Pt=K({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Ft=K({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),It=K({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});K({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),K({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var q=3.14159,Lt=1/q,Rt=2*q,J=1e-6,zt=.05,Bt=.089,Vt=.001,Ht=(0,o.vec3)(.2126,.7152,.0722),Y=U.SLOTS_PER_MATERIAL,Ut=U.SLOT,X=Ut,Wt=(0,o.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,o.wgslFn)(`
|
|
150
150
|
fn sRGBToLinear( srgbColor: vec3f ) -> vec3f {
|
|
151
151
|
|
|
152
152
|
return pow( srgbColor, vec3f( 2.2 ) );
|
|
@@ -158,7 +158,7 @@
|
|
|
158
158
|
return pow( color, vec3f( 1.0 / 2.2 ) );
|
|
159
159
|
|
|
160
160
|
}
|
|
161
|
-
`);var
|
|
161
|
+
`);var Gt=(0,o.wgslFn)(`
|
|
162
162
|
fn square( x: f32 ) -> f32 {
|
|
163
163
|
|
|
164
164
|
return x * x;
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
return x * x;
|
|
171
171
|
|
|
172
172
|
}
|
|
173
|
-
`);var
|
|
173
|
+
`);var Kt=(0,o.wgslFn)(`
|
|
174
174
|
fn maxComponent( v: vec3f ) -> f32 {
|
|
175
175
|
|
|
176
176
|
return max( max( v.r, v.g ), v.b );
|
|
@@ -182,18 +182,18 @@
|
|
|
182
182
|
return min( min( v.r, v.g ), v.b );
|
|
183
183
|
|
|
184
184
|
}
|
|
185
|
-
`);var
|
|
185
|
+
`);var qt=(0,o.wgslFn)(`
|
|
186
186
|
fn luminance( color: vec3f ) -> f32 {
|
|
187
187
|
|
|
188
188
|
return dot( color, vec3f( 0.2126, 0.7152, 0.0722 ) );
|
|
189
189
|
|
|
190
190
|
}
|
|
191
|
-
`),
|
|
191
|
+
`),Jt=(0,o.wgslFn)(`
|
|
192
192
|
fn powerHeuristic( pdf1: f32, pdf2: f32 ) -> f32 {
|
|
193
193
|
|
|
194
194
|
let p1 = pdf1 * pdf1;
|
|
195
195
|
let p2 = pdf2 * pdf2;
|
|
196
|
-
return p1 / max( p1 + p2, ${
|
|
196
|
+
return p1 / max( p1 + p2, ${Vt} );
|
|
197
197
|
|
|
198
198
|
}
|
|
199
199
|
`);(0,o.wgslFn)(`
|
|
@@ -221,7 +221,7 @@
|
|
|
221
221
|
return color;
|
|
222
222
|
|
|
223
223
|
}
|
|
224
|
-
`);var
|
|
224
|
+
`);var Yt=(0,o.wgslFn)(`
|
|
225
225
|
fn constructTBN( N: vec3f ) -> mat3x3f {
|
|
226
226
|
|
|
227
227
|
var majorAxis: vec3f;
|
|
@@ -235,7 +235,7 @@
|
|
|
235
235
|
return mat3x3f( T, B, N );
|
|
236
236
|
|
|
237
237
|
}
|
|
238
|
-
`),
|
|
238
|
+
`),Xt=(0,o.Fn)(([e,t,n])=>{let r=t.add(n).toVar(),i=(0,o.dot)(r,r).toVar();return r.assign(i.greaterThan(J).select(r.div(i.sqrt()),(0,o.vec3)(0,0,1))),kt({NoL:(0,o.max)((0,o.dot)(e,n),.001),NoV:(0,o.max)((0,o.dot)(e,t),.001),NoH:(0,o.max)((0,o.dot)(e,r),.001),VoH:(0,o.max)((0,o.dot)(t,r),.001),LoH:(0,o.max)((0,o.dot)(n,r),.001)})}),Zt=(0,o.wgslFn)(`
|
|
239
239
|
fn calculateFireflyThreshold( baseThreshold: f32, bounceIndex: i32, frame: i32 ) -> f32 {
|
|
240
240
|
|
|
241
241
|
let depthFactor = 1.0 / ( 1.0 + f32( bounceIndex ) * 0.1 );
|
|
@@ -243,7 +243,7 @@
|
|
|
243
243
|
return baseThreshold * depthFactor * relaxation;
|
|
244
244
|
|
|
245
245
|
}
|
|
246
|
-
`),
|
|
246
|
+
`),Qt=(0,o.wgslFn)(`
|
|
247
247
|
fn applySoftSuppression( value: f32, threshold: f32, dampingFactor: f32 ) -> f32 {
|
|
248
248
|
|
|
249
249
|
if ( value <= threshold ) {
|
|
@@ -254,7 +254,7 @@
|
|
|
254
254
|
return value * suppressionFactor;
|
|
255
255
|
|
|
256
256
|
}
|
|
257
|
-
`)
|
|
257
|
+
`),$t=(0,o.wgslFn)(`
|
|
258
258
|
fn applySoftSuppressionRGB( color: vec3f, threshold: f32, dampingFactor: f32 ) -> vec3f {
|
|
259
259
|
|
|
260
260
|
let lum = dot( color, vec3f( 0.2126, 0.7152, 0.0722 ) );
|
|
@@ -268,7 +268,7 @@
|
|
|
268
268
|
return color;
|
|
269
269
|
|
|
270
270
|
}
|
|
271
|
-
`,[
|
|
271
|
+
`,[Qt]),en=(0,o.Fn)(([e,t,n,r,i])=>{let a=e.greaterThan(.7).toVar(),s=t.greaterThan(.8).toVar(),c=t.lessThan(.3).toVar(),l=n.greaterThan(.5).toVar(),u=r.greaterThan(.5).toVar(),d=i.x.add(i.y).add(i.z).greaterThan(0).toVar(),f=(0,o.float)(.15).mul((0,o.float)(a)).add((0,o.float)(.25).mul((0,o.float)(c))).add((0,o.float)(.45).mul((0,o.float)(l))).add((0,o.float)(.35).mul((0,o.float)(u))).add((0,o.float)(.3).mul((0,o.float)(d))).toVar(),p=(0,o.float)(0).toVar();return(0,o.If)(a.and(c),()=>{p.addAssign(.15)}),(0,o.If)(l.and(u),()=>{p.addAssign(.2)}),(0,o.If)(d.and(l.or(a)),()=>{p.addAssign(.1)}),jt({isMetallic:a,isRough:s,isSmooth:c,isTransmissive:l,hasClearcoat:u,isEmissive:d,complexityScore:(0,o.clamp)(f.add(p),0,1)})}),tn=(0,o.Fn)(([e,t,n,r,i])=>{let a=Kt({v:i}).toVar(),s=(0,o.float)(.5).toVar(),c=(0,o.float)(.5).toVar(),l=(0,o.bool)(!0),u=a.greaterThan(.01).toVar();return(0,o.If)(e.lessThan(.1).and(t.greaterThan(.8)),()=>{s.assign(.7),c.assign(.3)}).ElseIf(e.greaterThan(.7),()=>{s.assign(.4),c.assign(.6)}),(0,o.If)(r.greaterThan((0,o.int)(5)),()=>{s.assign(.6),c.assign(.4)}),Ft({brdfWeight:s,lightWeight:c,envWeight:(0,o.float)(0),useBRDFSampling:l,useLightSampling:u,useEnvSampling:(0,o.bool)(!1)})}),Z=(0,o.Fn)(([e,t,n,r])=>{let i=t.mul(r).add(n);return e.element(i)}),nn=(0,o.wgslFn)(`
|
|
272
272
|
fn arrayToMat3( data1: vec4f, data2: vec4f ) -> mat3x3f {
|
|
273
273
|
|
|
274
274
|
return mat3x3f(
|
|
@@ -278,7 +278,7 @@
|
|
|
278
278
|
);
|
|
279
279
|
|
|
280
280
|
}
|
|
281
|
-
`),
|
|
281
|
+
`),rn=(0,o.Fn)(([e,t])=>{let n=Z(t,e,(0,o.int)(X.COLOR_METALNESS),(0,o.int)(Y)).toVar(),r=Z(t,e,(0,o.int)(X.EMISSIVE_ROUGHNESS),(0,o.int)(Y)).toVar(),i=Z(t,e,(0,o.int)(X.IOR_TRANSMISSION),(0,o.int)(Y)).toVar(),a=Z(t,e,(0,o.int)(X.ATTENUATION),(0,o.int)(Y)).toVar(),s=Z(t,e,(0,o.int)(X.DISPERSION_SHEEN),(0,o.int)(Y)).toVar(),c=Z(t,e,(0,o.int)(X.SHEEN_COLOR),(0,o.int)(Y)).toVar(),l=Z(t,e,(0,o.int)(X.SPECULAR),(0,o.int)(Y)).toVar(),u=Z(t,e,(0,o.int)(X.IRIDESCENCE),(0,o.int)(Y)).toVar(),d=Z(t,e,(0,o.int)(X.MAP_INDICES_A),(0,o.int)(Y)).toVar(),f=Z(t,e,(0,o.int)(X.MAP_INDICES_B),(0,o.int)(Y)).toVar(),p=Z(t,e,(0,o.int)(X.OPACITY_ALPHA),(0,o.int)(Y)).toVar(),m=Z(t,e,(0,o.int)(X.ALPHA_MODE),(0,o.int)(Y)).toVar(),h=Z(t,e,(0,o.int)(X.BUMP_DISPLACEMENT),(0,o.int)(Y)).toVar(),g=Z(t,e,(0,o.int)(X.ALBEDO_TRANSFORM_A),(0,o.int)(Y)).toVar(),_=Z(t,e,(0,o.int)(X.ALBEDO_TRANSFORM_B),(0,o.int)(Y)).toVar(),v=Z(t,e,(0,o.int)(X.NORMAL_TRANSFORM_A),(0,o.int)(Y)).toVar(),y=Z(t,e,(0,o.int)(X.NORMAL_TRANSFORM_B),(0,o.int)(Y)).toVar(),b=Z(t,e,(0,o.int)(X.ROUGHNESS_TRANSFORM_A),(0,o.int)(Y)).toVar(),x=Z(t,e,(0,o.int)(X.ROUGHNESS_TRANSFORM_B),(0,o.int)(Y)).toVar(),S=Z(t,e,(0,o.int)(X.METALNESS_TRANSFORM_A),(0,o.int)(Y)).toVar(),C=Z(t,e,(0,o.int)(X.METALNESS_TRANSFORM_B),(0,o.int)(Y)).toVar(),w=Z(t,e,(0,o.int)(X.EMISSIVE_TRANSFORM_A),(0,o.int)(Y)).toVar(),T=Z(t,e,(0,o.int)(X.EMISSIVE_TRANSFORM_B),(0,o.int)(Y)).toVar(),E=Z(t,e,(0,o.int)(X.BUMP_TRANSFORM_A),(0,o.int)(Y)).toVar(),D=Z(t,e,(0,o.int)(X.BUMP_TRANSFORM_B),(0,o.int)(Y)).toVar(),O=Z(t,e,(0,o.int)(X.DISPLACEMENT_TRANSFORM_A),(0,o.int)(Y)).toVar(),k=Z(t,e,(0,o.int)(X.DISPLACEMENT_TRANSFORM_B),(0,o.int)(Y)).toVar();return Ct({color:(0,o.vec4)(n.rgb,1),metalness:n.a,emissive:r.rgb,roughness:r.a,ior:i.r,transmission:i.g,thickness:i.b,emissiveIntensity:i.a,attenuationColor:a.rgb,attenuationDistance:a.a,dispersion:s.r,sheen:s.b,sheenRoughness:s.a,sheenColor:c.rgb,specularIntensity:l.r,specularColor:l.gba,iridescence:u.r,iridescenceIOR:u.g,iridescenceThicknessRange:u.ba,albedoMapIndex:(0,o.int)(d.r),normalMapIndex:(0,o.int)(d.g),roughnessMapIndex:(0,o.int)(d.b),metalnessMapIndex:(0,o.int)(d.a),emissiveMapIndex:(0,o.int)(f.r),bumpMapIndex:(0,o.int)(f.g),clearcoat:f.b,clearcoatRoughness:f.a,opacity:p.r,side:(0,o.int)(p.g),transparent:p.b,alphaTest:p.a,alphaMode:(0,o.int)(m.r),depthWrite:(0,o.int)(m.g),normalScale:(0,o.vec2)(m.b,m.b),bumpScale:h.r,displacementScale:h.g,displacementMapIndex:(0,o.int)(h.b),albedoTransform:nn({data1:g,data2:_}),normalTransform:nn({data1:v,data2:y}),roughnessTransform:nn({data1:b,data2:x}),metalnessTransform:nn({data1:S,data2:C}),emissiveTransform:nn({data1:w,data2:T}),bumpTransform:nn({data1:E,data2:D}),displacementTransform:nn({data1:O,data2:k})})}),an=(0,o.Fn)(([e,t])=>{let n=Z(t,e,(0,o.int)(X.IOR_TRANSMISSION),(0,o.int)(Y)).toVar(),r=Z(t,e,(0,o.int)(X.ATTENUATION),(0,o.int)(Y)).toVar(),i=Z(t,e,(0,o.int)(X.MAP_INDICES_A),(0,o.int)(Y)).toVar(),a=Z(t,e,(0,o.int)(X.OPACITY_ALPHA),(0,o.int)(Y)).toVar(),s=Z(t,e,(0,o.int)(X.ALPHA_MODE),(0,o.int)(Y)).toVar(),c=Z(t,e,(0,o.int)(X.ALBEDO_TRANSFORM_A),(0,o.int)(Y)).toVar(),l=Z(t,e,(0,o.int)(X.ALBEDO_TRANSFORM_B),(0,o.int)(Y)).toVar();return wt({color:(0,o.vec4)(1),ior:n.r,transmission:n.g,attenuationColor:r.rgb,attenuationDistance:r.a,albedoMapIndex:(0,o.int)(i.r),opacity:a.r,transparent:a.b,alphaTest:a.a,alphaMode:(0,o.int)(s.r),albedoTransform:nn({data1:c,data2:l})})}),on=(0,o.wgslFn)(`
|
|
282
282
|
fn normalDepthWeight(
|
|
283
283
|
n1: vec3f, n2: vec3f,
|
|
284
284
|
d1: f32, d2: f32,
|
|
@@ -290,7 +290,7 @@
|
|
|
290
290
|
return normalW * depthW;
|
|
291
291
|
|
|
292
292
|
}
|
|
293
|
-
`),
|
|
293
|
+
`),sn=32,cn=512,ln=4,un=8,dn=1e8,fn=null;function pn(e){fn=e}var mn=()=>(0,o.array)(`int`,sn).toVar(),hn=(0,o.wgslFn)(`
|
|
294
294
|
fn RayTriangleGeometry( rayOrigin: vec3f, rayDir: vec3f, pA: vec3f, pB: vec3f, pC: vec3f, closestHitDst: f32 ) -> vec4f {
|
|
295
295
|
|
|
296
296
|
// Returns vec4(t, u, v, hit) where hit > 0.5 means intersection
|
|
@@ -331,7 +331,7 @@
|
|
|
331
331
|
return result;
|
|
332
332
|
|
|
333
333
|
}
|
|
334
|
-
`),
|
|
334
|
+
`),gn=(0,o.wgslFn)(`
|
|
335
335
|
fn fastRayAABBDst( rayOrigin: vec3f, invDir: vec3f, boxMin: vec3f, boxMax: vec3f ) -> f32 {
|
|
336
336
|
|
|
337
337
|
let t1 = ( boxMin - rayOrigin ) * invDir;
|
|
@@ -347,7 +347,7 @@
|
|
|
347
347
|
return select( 1e20f, max( tNear, 0.0f ), isHit );
|
|
348
348
|
|
|
349
349
|
}
|
|
350
|
-
`),
|
|
350
|
+
`),_n=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.int)(Z(r,e,(0,o.int)(Ut.OPACITY_ALPHA),(0,o.int)(Y)).g),a=t.dot(n),s=i.equal((0,o.int)(2)),c=i.equal((0,o.int)(0)).and(a.lessThan(-1e-4)),l=i.equal((0,o.int)(1)).and(a.greaterThan(1e-4));return s.or(c).or(l)}),vn=(0,o.Fn)(([e,t,n,r])=>{let i=Tt({didHit:!1,dst:(0,o.float)(0x56bc75e2d63100000),hitPoint:(0,o.vec3)(0),normal:(0,o.vec3)(0),uv:(0,o.vec2)(0),materialIndex:(0,o.int)(-1),meshIndex:(0,o.int)(-1),boxTests:(0,o.int)(0),triTests:(0,o.int)(0)}).toVar(),a=(0,o.int)(-1).toVar(),s=(0,o.float)(0).toVar(),c=(0,o.float)(0).toVar(),l=mn(),u=(0,o.int)(1).toVar();l.element((0,o.int)(0)).assign((0,o.int)(0));let d=(0,o.mix)((0,o.vec3)(1),(0,o.sign)(e.direction),(0,o.notEqual)(e.direction,(0,o.vec3)(0))),f=(0,o.mix)((0,o.vec3)(1).div(e.direction),(0,o.vec3)(dn).mul(d),(0,o.lessThan)((0,o.abs)(e.direction),(0,o.vec3)(1e-8))).toVar(),p=e.origin,m=e.direction,h=(0,o.int)(0).toVar();return(0,o.Loop)(u.greaterThan((0,o.int)(0)).and(h.lessThan((0,o.int)(cn))),()=>{h.addAssign(1),u.subAssign(1);let e=l.element(u).toVar(),d=Z(t,e,(0,o.int)(0),(0,o.int)(ln));i.boxTests.addAssign(1),(0,o.If)(d.w.lessThan(0),()=>{(0,o.If)(d.w.greaterThan((0,o.float)(-1.5)),()=>{let e=(0,o.int)(d.x).toVar(),t=(0,o.int)(d.y).toVar();(0,o.Loop)({start:(0,o.int)(0),end:t},({i:t})=>{i.triTests.addAssign(1);let l=e.add(t).toVar(),u=Z(n,l,(0,o.int)(0),(0,o.int)(un)).xyz,d=Z(n,l,(0,o.int)(1),(0,o.int)(un)).xyz,f=Z(n,l,(0,o.int)(2),(0,o.int)(un)).xyz,h=hn({rayOrigin:p,rayDir:m,pA:u,pB:d,pC:f,closestHitDst:i.dst});(0,o.If)(h.w.greaterThan(.5),()=>{let e=h.x,t=h.y,u=h.z,d=Z(n,l,(0,o.int)(3),(0,o.int)(un)).xyz,f=Z(n,l,(0,o.int)(4),(0,o.int)(un)).xyz,p=Z(n,l,(0,o.int)(5),(0,o.int)(un)).xyz,g=Z(n,l,(0,o.int)(7),(0,o.int)(un)),_=(0,o.int)(g.z),v=(0,o.float)(1).sub(t).sub(u),y=(0,o.normalize)(d.mul(v).add(f.mul(t)).add(p.mul(u))).toVar();(0,o.If)(_n(_,m,y,r),()=>{i.didHit.assign(!0),i.dst.assign(e),i.normal.assign(y),i.materialIndex.assign(_),i.meshIndex.assign((0,o.int)(g.w)),a.assign(l),s.assign(t),c.assign(u)})})}),(0,o.If)(i.didHit.and(i.dst.lessThan(.001)),()=>{(0,o.Break)()})}).Else(()=>{let e=(0,o.int)(d.x).toVar();if(fn){let t=(0,o.int)(d.y).toVar(),n=Z(fn,(0,o.int)(1),t,(0,o.int)(0)).x;(0,o.If)(n.greaterThan(.5).and(u.lessThan((0,o.int)(sn))),()=>{l.element(u).assign(e),u.addAssign(1)})}else (0,o.If)(u.lessThan((0,o.int)(sn)),()=>{l.element(u).assign(e),u.addAssign(1)})})}).Else(()=>{let n=Z(t,e,(0,o.int)(1),(0,o.int)(ln)),r=Z(t,e,(0,o.int)(2),(0,o.int)(ln)),a=Z(t,e,(0,o.int)(3),(0,o.int)(ln)),s=(0,o.int)(d.w).toVar(),c=(0,o.int)(n.w).toVar(),m=gn({rayOrigin:p,invDir:f,boxMin:d.xyz,boxMax:n.xyz}).toVar(),h=gn({rayOrigin:p,invDir:f,boxMin:r.xyz,boxMax:a.xyz}).toVar();(0,o.If)((0,o.min)(m,h).lessThan(i.dst),()=>{let e=m.lessThan(h),t=(0,o.select)(e,s,c).toVar(),n=(0,o.select)(e,c,s).toVar();(0,o.If)((0,o.select)(e,h,m).toVar().lessThan(i.dst).and(u.lessThan((0,o.int)(sn))),()=>{l.element(u).assign(n),u.addAssign(1)}),(0,o.If)(u.lessThan((0,o.int)(sn)),()=>{l.element(u).assign(t),u.addAssign(1)})})})}),(0,o.If)(i.didHit,()=>{i.hitPoint.assign(e.origin.add(e.direction.mul(i.dst)));let t=(0,o.float)(1).sub(s).sub(c),r=Z(n,a,(0,o.int)(6),(0,o.int)(un)),l=Z(n,a,(0,o.int)(7),(0,o.int)(un));i.uv.assign(r.xy.mul(t).add(r.zw.mul(s)).add(l.xy.mul(c))),i.triangleIndex.assign(a)}),i}),yn=(0,o.Fn)(([e,t,n,r,i])=>{let a=Tt({didHit:!1,dst:i,hitPoint:(0,o.vec3)(0),normal:(0,o.vec3)(0),uv:(0,o.vec2)(0),materialIndex:(0,o.int)(-1),meshIndex:(0,o.int)(-1),boxTests:(0,o.int)(0),triTests:(0,o.int)(0)}).toVar(),s=mn(),c=(0,o.int)(1).toVar();s.element((0,o.int)(0)).assign((0,o.int)(0));let l=(0,o.mix)((0,o.vec3)(1),(0,o.sign)(e.direction),(0,o.notEqual)(e.direction,(0,o.vec3)(0))),u=(0,o.mix)((0,o.vec3)(1).div(e.direction),(0,o.vec3)(dn).mul(l),(0,o.lessThan)((0,o.abs)(e.direction),(0,o.vec3)(1e-8))).toVar(),d=(0,o.int)(0).toVar();return(0,o.Loop)(c.greaterThan((0,o.int)(0)).and(a.didHit.not()).and(d.lessThan((0,o.int)(cn))),()=>{d.addAssign(1),c.subAssign(1);let r=s.element(c).toVar(),i=Z(t,r,(0,o.int)(0),(0,o.int)(ln));(0,o.If)(i.w.lessThan(0),()=>{(0,o.If)(i.w.greaterThan((0,o.float)(-1.5)),()=>{let t=(0,o.int)(i.x).toVar(),r=(0,o.int)(i.y).toVar();(0,o.Loop)({start:(0,o.int)(0),end:r},({i:r})=>{let i=t.add(r).toVar(),s=Z(n,i,(0,o.int)(0),(0,o.int)(un)).xyz,c=Z(n,i,(0,o.int)(1),(0,o.int)(un)).xyz,l=Z(n,i,(0,o.int)(2),(0,o.int)(un)).xyz,u=hn({rayOrigin:e.origin,rayDir:e.direction,pA:s,pB:c,pC:l,closestHitDst:a.dst});(0,o.If)(u.w.greaterThan(.5),()=>{let t=Z(n,i,(0,o.int)(7),(0,o.int)(un));a.didHit.assign(!0),a.dst.assign(u.x),a.materialIndex.assign((0,o.int)(t.z)),a.meshIndex.assign((0,o.int)(t.w)),a.hitPoint.assign(e.origin.add(e.direction.mul(u.x))),a.normal.assign((0,o.normalize)((0,o.cross)(c.sub(s),l.sub(s)))),a.uv.assign((0,o.vec2)(u.y,u.z)),a.triangleIndex.assign(i),(0,o.Break)()})})}).Else(()=>{let e=(0,o.int)(i.x).toVar();if(fn){let t=(0,o.int)(i.y).toVar(),n=Z(fn,(0,o.int)(1),t,(0,o.int)(0)).x;(0,o.If)(n.greaterThan(.5).and(c.lessThan((0,o.int)(sn))),()=>{s.element(c).assign(e),c.addAssign(1)})}else (0,o.If)(c.lessThan((0,o.int)(sn)),()=>{s.element(c).assign(e),c.addAssign(1)})})}).Else(()=>{let n=Z(t,r,(0,o.int)(1),(0,o.int)(ln)),l=Z(t,r,(0,o.int)(2),(0,o.int)(ln)),d=Z(t,r,(0,o.int)(3),(0,o.int)(ln)),f=(0,o.int)(i.w).toVar(),p=(0,o.int)(n.w).toVar(),m=gn({rayOrigin:e.origin,invDir:u,boxMin:i.xyz,boxMax:n.xyz}).toVar(),h=gn({rayOrigin:e.origin,invDir:u,boxMin:l.xyz,boxMax:d.xyz}).toVar();(0,o.If)((0,o.min)(m,h).lessThan(a.dst),()=>{let e=m.lessThan(h),t=(0,o.select)(e,f,p).toVar(),n=(0,o.select)(e,p,f).toVar();(0,o.If)((0,o.select)(e,h,m).toVar().lessThan(a.dst).and(c.lessThan((0,o.int)(sn))),()=>{s.element(c).assign(n),c.addAssign(1)}),(0,o.If)(c.lessThan((0,o.int)(sn)),()=>{s.element(c).assign(t),c.addAssign(1)})})})}),a}),bn=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(e.xy,1),p=r.mul((0,o.vec4)(f,1)),m=(0,o.normalize)((0,o.mat3)(n[0].xyz,n[1].xyz,n[2].xyz).mul(p.xyz.div(p.w))).toVar(),h=(0,o.vec3)(n[3]).toVar(),g=h.toVar(),_=m.toVar();return(0,o.If)(i.and(a.greaterThan(0)).and(s.lessThan(64)).and(c.greaterThan(.001)),()=>{let e=h.add(m.mul(c)).toVar(),r=a.div(s).mul(.001).mul(l).mul(u),i=ie(t),f=i.x.mul(d.max(.01)),p=i.y,v=(0,o.normalize)((0,o.vec3)(n[0])),y=(0,o.normalize)((0,o.vec3)(n[1])),b=v.mul(f).add(y.mul(p)).mul(r);g.assign(h.add(b)),_.assign((0,o.normalize)(e.sub(g)))}),St({origin:g,direction:_})}),xn=(0,o.wgslFn)(`
|
|
351
351
|
fn equirectDirectionToUv( direction: vec3f, environmentMatrix: mat4x4f ) -> vec2f {
|
|
352
352
|
let d = normalize( ( environmentMatrix * vec4f( direction, 0.0f ) ).xyz );
|
|
353
353
|
var uv = vec2f( atan2( d.z, d.x ), acos( d.y ) );
|
|
@@ -356,7 +356,7 @@
|
|
|
356
356
|
uv.y = 1.0f - uv.y;
|
|
357
357
|
return uv;
|
|
358
358
|
}
|
|
359
|
-
`),
|
|
359
|
+
`),Sn=(0,o.wgslFn)(`
|
|
360
360
|
fn equirectUvToDirection( uv: vec2f, environmentMatrix: mat4x4f ) -> vec3f {
|
|
361
361
|
let adjustedUv = vec2f( uv.x - 0.5f, 1.0f - uv.y );
|
|
362
362
|
let theta = adjustedUv.x * 6.28318530717958647692f;
|
|
@@ -365,7 +365,7 @@
|
|
|
365
365
|
let localDir = vec3f( sinPhi * cos( theta ), cos( phi ), sinPhi * sin( theta ) );
|
|
366
366
|
return normalize( ( transpose( environmentMatrix ) * vec4f( localDir, 0.0f ) ).xyz );
|
|
367
367
|
}
|
|
368
|
-
`);(0,o.Fn)(([e,t,n])=>(0,o.texture)(e,
|
|
368
|
+
`);(0,o.Fn)(([e,t,n])=>(0,o.texture)(e,xn({direction:t,environmentMatrix:n}),0).rgb);var Cn=(0,o.wgslFn)(`
|
|
369
369
|
fn equirectDirectionPdf( direction: vec3f, environmentMatrix: mat4x4f ) -> f32 {
|
|
370
370
|
let uv = equirectDirectionToUv( direction, environmentMatrix );
|
|
371
371
|
let theta = uv.y * 3.14159265358979323846f;
|
|
@@ -373,7 +373,7 @@
|
|
|
373
373
|
if ( sinTheta == 0.0f ) { return 0.0f; }
|
|
374
374
|
return 1.0f / ( 6.28318530717958647692f * 3.14159265358979323846f * sinTheta );
|
|
375
375
|
}
|
|
376
|
-
`,[
|
|
376
|
+
`,[xn]),wn=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.vec4)(0).toVar();return(0,o.If)(r.equal(0),()=>{a.assign((0,o.vec4)(0))}).Else(()=>{let s=(0,o.texture)(e,xn({direction:t,environmentMatrix:n}).toVar(),0).rgb.toVar(),c=(0,o.dot)(s,Ht).toVar().div(r).toVar(),l=Cn({direction:t,environmentMatrix:n}).toVar(),u=(0,o.float)(i.x).mul((0,o.float)(i.y)).mul(c).mul(l).toVar();a.assign((0,o.vec4)(s,u))}),a}),Tn=(0,o.Fn)(([e,t,n,r,i,a,s,c,l])=>{let u=s.y,d=(0,o.clamp)(c.x.mul(u.sub(1)),0,u.sub(1)),f=(0,o.int)((0,o.floor)(d)),p=(0,o.min)(f.add(1),(0,o.int)(u).sub(1)),m=(0,o.fract)(d),h=(0,o.mix)(t.element(f),t.element(p),m).toVar(),g=s.x,_=s.y,v=(0,o.clamp)(c.y.mul(g.sub(1)),0,g.sub(1)),y=(0,o.clamp)(h.mul(_.sub(1)),0,_.sub(1)),b=(0,o.int)((0,o.floor)(v)),x=(0,o.int)((0,o.floor)(y)),S=(0,o.min)(b.add(1),(0,o.int)(g).sub(1)),C=(0,o.min)(x.add(1),(0,o.int)(_).sub(1)),w=(0,o.fract)(v),T=(0,o.fract)(y),E=(0,o.int)(g),D=n.element(x.mul(E).add(b)),O=n.element(x.mul(E).add(S)),k=n.element(C.mul(E).add(b)),A=n.element(C.mul(E).add(S)),j=(0,o.vec2)((0,o.mix)((0,o.mix)(D,O,w),(0,o.mix)(k,A,w),T).toVar(),h).toVar(),M=Sn({uv:j,environmentMatrix:r}).toVar(),N=(0,o.texture)(e,j,0).rgb.mul(i).toVar();l.assign(N);let ee=(0,o.dot)(N.div(i),Ht).toVar().div(a).toVar(),te=Cn({direction:M,environmentMatrix:r}).toVar();return(0,o.vec4)(M,(0,o.float)(s.x).mul((0,o.float)(s.y)).mul(ee).mul(te).toVar())}),En=(0,o.wgslFn)(`
|
|
377
377
|
fn sampleEnvironment(
|
|
378
378
|
tex: texture_2d<f32>,
|
|
379
379
|
samp: sampler,
|
|
@@ -387,7 +387,7 @@
|
|
|
387
387
|
let texSample = textureSampleLevel( tex, samp, uv, 0.0 );
|
|
388
388
|
return texSample * environmentIntensity;
|
|
389
389
|
}
|
|
390
|
-
`,[
|
|
390
|
+
`,[xn]),Dn=(0,o.wgslFn)(`
|
|
391
391
|
fn isIdentityTransform( transform: mat3x3f ) -> bool {
|
|
392
392
|
return transform[0][0] == 1.0f
|
|
393
393
|
&& transform[1][1] == 1.0f
|
|
@@ -396,7 +396,7 @@
|
|
|
396
396
|
&& transform[2][0] == 0.0f
|
|
397
397
|
&& transform[2][1] == 0.0f;
|
|
398
398
|
}
|
|
399
|
-
`),
|
|
399
|
+
`),On=(0,o.wgslFn)(`
|
|
400
400
|
fn getTransformedUV( uv: vec2f, transform: mat3x3f ) -> vec2f {
|
|
401
401
|
if ( !isIdentityTransform( transform ) ) {
|
|
402
402
|
return fract( vec2f(
|
|
@@ -406,11 +406,11 @@
|
|
|
406
406
|
}
|
|
407
407
|
return uv;
|
|
408
408
|
}
|
|
409
|
-
`,[
|
|
409
|
+
`,[Dn]),kn=(0,o.Fn)(([e])=>e.albedoMapIndex.greaterThanEqual((0,o.int)(0)).or(e.normalMapIndex.greaterThanEqual((0,o.int)(0))).or(e.roughnessMapIndex.greaterThanEqual((0,o.int)(0))).or(e.metalnessMapIndex.greaterThanEqual((0,o.int)(0))).or(e.emissiveMapIndex.greaterThanEqual((0,o.int)(0))).or(e.bumpMapIndex.greaterThanEqual((0,o.int)(0))).or(e.displacementMapIndex.greaterThanEqual((0,o.int)(0)))),An=(0,o.wgslFn)(`
|
|
410
410
|
fn hashTransform( t: mat3x3f ) -> f32 {
|
|
411
411
|
return t[0][0] + t[1][1] * 7.0f + t[2][0] * 13.0f + t[2][1] * 17.0f;
|
|
412
412
|
}
|
|
413
|
-
`),An=(0,o.Fn)(([e,t])=>{let n=kn({t:t.albedoTransform}).toVar(),r=kn({t:t.normalTransform}).toVar(),i=kn({t:t.metalnessTransform}).toVar(),a=kn({t:t.roughnessTransform}).toVar(),s=kn({t:t.emissiveTransform}).toVar(),c=kn({t:t.bumpTransform}).toVar(),l=.001,u=(0,o.abs)(n.sub(r)).lessThan(l).toVar(),d=(0,o.abs)(r.sub(c)).lessThan(l).toVar(),f=(0,o.abs)(i.sub(a)).lessThan(l).toVar(),p=(0,o.abs)(n.sub(s)).lessThan(l).toVar(),m=u.and((0,o.abs)(n.sub(i)).lessThan(l)).and((0,o.abs)(n.sub(s)).lessThan(l)).and((0,o.abs)(n.sub(c)).lessThan(l)).toVar(),h=(0,o.vec2)(0).toVar(),g=(0,o.vec2)(0).toVar(),_=(0,o.vec2)(0).toVar(),v=(0,o.vec2)(0).toVar(),y=(0,o.vec2)(0).toVar(),b=(0,o.vec2)(0).toVar(),x=d.or(m).toVar(),S=f.or(m).toVar(),C=p.or(m).toVar();return(0,o.If)(m,()=>{let n=Dn({uv:e,transform:t.albedoTransform});h.assign(n),g.assign(n),_.assign(n),v.assign(n),y.assign(n),b.assign(n)}).Else(()=>{h.assign(Dn({uv:e,transform:t.albedoTransform})),g.assign(u.select(h,Dn({uv:e,transform:t.normalTransform}))),y.assign(p.select(h,Dn({uv:e,transform:t.emissiveTransform}))),(0,o.If)(d,()=>{b.assign(g)}).ElseIf((0,o.abs)(c.sub(n)).lessThan(l),()=>{b.assign(h)}).Else(()=>{b.assign(Dn({uv:e,transform:t.bumpTransform}))}),(0,o.If)(f,()=>{_.assign(Dn({uv:e,transform:t.metalnessTransform})),v.assign(_)}).Else(()=>{(0,o.If)((0,o.abs)(i.sub(n)).lessThan(l),()=>{_.assign(h)}).ElseIf((0,o.abs)(i.sub(r)).lessThan(l),()=>{_.assign(g)}).Else(()=>{_.assign(Dn({uv:e,transform:t.metalnessTransform}))}),(0,o.If)((0,o.abs)(a.sub(n)).lessThan(l),()=>{v.assign(h)}).ElseIf((0,o.abs)(a.sub(r)).lessThan(l),()=>{v.assign(g)}).ElseIf((0,o.abs)(a.sub(i)).lessThan(l),()=>{v.assign(_)}).Else(()=>{v.assign(Dn({uv:e,transform:t.roughnessTransform}))})})}),jt({albedoUV:h,normalUV:g,metalnessUV:_,roughnessUV:v,emissiveUV:y,bumpUV:b,allSameUV:m,normalBumpSameUV:x,metalRoughSameUV:S,albedoEmissiveSameUV:C})}),jn=(0,o.Fn)(([e,t,n])=>{let r=t.color.toVar();return(0,o.If)(t.albedoMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let i=(0,o.texture)(e,n.albedoUV).depth((0,o.int)(t.albedoMapIndex)).toVar();r.assign((0,o.vec4)(t.color.rgb.mul(i.rgb),t.color.a.mul(i.a)))}),r}),Mn=(0,o.Fn)(([e,t,n,r])=>{let i=n.metalness.toVar(),a=n.roughness.toVar();return(0,o.If)(n.metalnessMapIndex.greaterThanEqual((0,o.int)(0)).and(n.metalnessMapIndex.equal(n.roughnessMapIndex)),()=>{let t=(0,o.texture)(e,r.metalnessUV).depth((0,o.int)(n.metalnessMapIndex));i.assign(n.metalness.mul(t.b)),a.assign(n.roughness.mul(t.g))}).Else(()=>{(0,o.If)(n.metalnessMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let t=(0,o.texture)(e,r.metalnessUV).depth((0,o.int)(n.metalnessMapIndex));i.assign(n.metalness.mul(t.b))}),(0,o.If)(n.roughnessMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let e=(0,o.texture)(t,r.roughnessUV).depth((0,o.int)(n.roughnessMapIndex));a.assign(n.roughness.mul(e.g))})}),(0,o.vec2)(i,a)}),Nn=(0,o.Fn)(([e,t,n,r])=>{let i=t.toVar();return(0,o.If)(n.normalMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let a=(0,o.texture)(e,r.normalUV).depth((0,o.int)(n.normalMapIndex)).xyz.mul(2).sub(1).toVar();a.x.mulAssign(n.normalScale.x),a.y.assign(a.y.negate().mul(n.normalScale.x));let s=(0,o.normalize)((0,o.cross)((0,o.abs)(t.z).lessThan(.999).select((0,o.vec3)(0,0,1),(0,o.vec3)(1,0,0)),t)),c=(0,o.cross)(t,s);i.assign((0,o.normalize)(s.mul(a.x).add(c.mul(a.y)).add(t.mul(a.z))))}),i}),Pn=(0,o.Fn)(([e,t,n,r])=>{let i=t.toVar();return(0,o.If)(n.bumpMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let a=(0,o.vec2)(1/1024).toVar(),s=(0,o.texture)(e,r.bumpUV).depth((0,o.int)(n.bumpMapIndex)).r,c=(0,o.texture)(e,(0,o.vec2)(r.bumpUV.x.add(a.x),r.bumpUV.y)).depth((0,o.int)(n.bumpMapIndex)).r,l=(0,o.texture)(e,(0,o.vec2)(r.bumpUV.x,r.bumpUV.y.add(a.y))).depth((0,o.int)(n.bumpMapIndex)).r,u=(0,o.vec2)(c.sub(s),l.sub(s)).mul(n.bumpScale),d=(0,o.normalize)((0,o.vec3)(u.x.negate(),u.y.negate(),1)),f=(0,o.normalize)((0,o.cross)((0,o.abs)(t.z).lessThan(.999).select((0,o.vec3)(0,0,1),(0,o.vec3)(1,0,0)),t)),p=(0,o.cross)(t,f),m=f.mul(d.x).add(p.mul(d.y)).add(t.mul(d.z));i.assign((0,o.normalize)((0,o.mix)(t,m,(0,o.clamp)(n.bumpScale,0,1))))}),i}),Fn=(0,o.Fn)(([e,t,n,r])=>{let i=t.emissive.mul(t.emissiveIntensity).toVar();return(0,o.If)(t.emissiveMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let n=(0,o.texture)(e,r.emissiveUV).depth((0,o.int)(t.emissiveMapIndex)).toVar();i.assign(i.mul(n.rgb))}),i}),In=(0,o.Fn)(([e,t,n,r,i,a,s,c,l])=>{let u=(0,o.vec4)(0).toVar(),d=(0,o.vec3)(0).toVar(),f=(0,o.float)(0).toVar(),p=(0,o.float)(0).toVar(),m=(0,o.vec3)(0).toVar(),h=On(s).toVar();return u.assign(s.color),d.assign(s.emissive.mul(s.emissiveIntensity)),f.assign(s.metalness),p.assign(s.roughness),m.assign(l),(0,o.If)(h,()=>{let o=jt.wrap(An(c,s)).toVar();u.assign(jn(e,s,o));let h=Mn(r,i,s,o);f.assign(h.x),p.assign(h.y);let g=Nn(t,l,s,o).toVar();m.assign(Pn(n,g,s,o)),d.assign(Fn(a,s,u,o))}),kt({albedo:u,emissive:d,metalness:f,roughness:p,normal:m,hasTextures:h})});(0,o.Fn)(([e,t,n,r,i,a,s,c])=>kt.wrap(In(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).albedo),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>kt.wrap(In(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).emissive),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>kt.wrap(In(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).metalness),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>kt.wrap(In(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).roughness),(0,o.Fn)(([e,t,n,r,i,a,o,s,c])=>kt.wrap(In(e,t,n,r,i,a,o,s,c)).normal);var Ln=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.float)(0).toVar();return(0,o.If)(t.greaterThanEqual((0,o.int)(0)),()=>{let a=Dn({uv:n,transform:r});i.assign((0,o.texture)(e,a).depth((0,o.int)(t)).r)}),i}),Rn=32,zn=16,Bn=5,Vn=1/1024,Hn=8,Un=K({hitPoint:`vec3`,uv:`vec2`,normal:`vec3`,height:`float`}),Wn=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=t.hitPoint.toVar(),c=t.uv.toVar(),l=t.normal.toVar(),u=(0,o.float)(0).toVar(),d=t.triangleIndex,f=Z(n,d,(0,o.int)(0),(0,o.int)(Hn)).xyz.toVar(),p=Z(n,d,(0,o.int)(1),(0,o.int)(Hn)).xyz.toVar(),m=Z(n,d,(0,o.int)(2),(0,o.int)(Hn)).xyz.toVar(),h=Z(n,d,(0,o.int)(6),(0,o.int)(Hn)).toVar(),g=Z(n,d,(0,o.int)(7),(0,o.int)(Hn)).toVar(),_=h.xy.toVar(),v=h.zw.toVar(),y=g.xy.toVar(),b=p.sub(f).toVar(),x=m.sub(f).toVar(),S=v.sub(_).toVar(),C=y.sub(_).toVar(),w=S.x.mul(C.y).sub(C.x.mul(S.y)).toVar();return(0,o.If)((0,o.abs)(w).greaterThan(1e-8),()=>{let n=(0,o.float)(1).div(w),d=b.mul(C.y).sub(x.mul(S.y)).mul(n).toVar(),f=x.mul(S.x).sub(b.mul(C.x)).mul(n).toVar(),p=t.normal.toVar(),m=i.displacementScale.div((0,o.float)(10)),h=e.direction,g=(0,o.dot)(h,p).toVar(),_=h.sub(p.mul(g)).toVar(),v=(0,o.dot)(d,d),y=(0,o.dot)(d,f),T=(0,o.dot)(f,f),E=v.mul(T).sub(y.mul(y)).toVar();(0,o.If)((0,o.abs)(E).greaterThan(1e-10),()=>{let e=(0,o.float)(1).div(E),n=(0,o.dot)(_,d),b=(0,o.dot)(_,f),x=(0,o.vec2)(T.mul(n).sub(y.mul(b)).mul(e).toVar(),v.mul(b).sub(y.mul(n)).mul(e).toVar()).toVar(),S=g.toVar(),C=(0,o.max)((0,o.abs)(S),.001).toVar(),w=m.div(C).toVar(),D=(0,o.int)(a.equal((0,o.int)(0)).select((0,o.int)(Rn),(0,o.int)(zn))).toVar(),O=w.negate().toVar(),k=w.toVar().sub(O).div((0,o.float)(D)).toVar(),A=O.toVar(),j=O.toVar(),M=(0,o.int)(0).toVar();(0,o.Loop)({start:(0,o.int)(0),end:D,type:`int`,condition:`<`},({i:e})=>{(0,o.If)(M.equal((0,o.int)(0)),()=>{let n=O.add(k.mul((0,o.float)(e))).toVar(),a=t.uv.add(x.mul(n)).toVar(),s=n.mul(S).toVar(),c=Ln(r,i.displacementMapIndex,a,i.displacementTransform).sub(.5).mul(m);(0,o.If)(s.lessThanEqual(c).and(e.greaterThan((0,o.int)(0))),()=>{M.assign(1),j.assign(n)}).Else(()=>{A.assign(n)})})}),(0,o.If)(M.equal((0,o.int)(1)),()=>{let e=A.toVar(),n=j.toVar();(0,o.Loop)({start:(0,o.int)(0),end:(0,o.int)(Bn),type:`int`,condition:`<`},()=>{let a=e.add(n).mul(.5).toVar(),s=t.uv.add(x.mul(a)).toVar(),c=a.mul(S),l=Ln(r,i.displacementMapIndex,s,i.displacementTransform).sub(.5).mul(m);(0,o.If)(c.lessThanEqual(l),()=>{n.assign(a)}).Else(()=>{e.assign(a)})});let a=e.add(n).mul(.5).toVar(),g=t.uv.add(x.mul(a)).toVar(),_=t.hitPoint.add(h.mul(a)).toVar(),v=Ln(r,i.displacementMapIndex,g,i.displacementTransform),y=v.sub(.5).mul(m),b=(0,o.float)(Vn),C=v,w=Ln(r,i.displacementMapIndex,g.add((0,o.vec2)(b,0)),i.displacementTransform),T=Ln(r,i.displacementMapIndex,g.add((0,o.vec2)(0,b)),i.displacementTransform),E=(0,o.normalize)(d).toVar(),D=(0,o.normalize)(f).toVar(),O=w.sub(C).mul(m),k=T.sub(C).mul(m),M=(0,o.normalize)(p.sub(E.mul(O)).sub(D.mul(k)));s.assign(_),c.assign(g),l.assign(M),u.assign(y)})})}),Un({hitPoint:s,uv:c,normal:l,height:u})}),Gn=1e-6;(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.vec3)((0,o.float)(1).sub(n)),e);return e.add(r.sub(e).mul((0,o.pow)((0,o.float)(1).sub(t),5)))});var Kn=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)(e,0,1);return t.add((0,o.float)(1).sub(t).mul((0,o.pow)((0,o.float)(1).sub(n),5)))}),qn=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)(e,0,1);return t.add((0,o.vec3)(1).sub(t).mul((0,o.pow)((0,o.float)(1).sub(n),5)))}),Jn=(0,o.Fn)(([e])=>{let t=(0,o.sqrt)(e);return(0,o.vec3)(1).add(t).div((0,o.max)((0,o.vec3)(1).sub(t),(0,o.vec3)(Gn)))}),Yn=(0,o.Fn)(([e,t])=>{let n=e.sub((0,o.vec3)(t)),r=(0,o.max)(e.add((0,o.vec3)(t)),(0,o.vec3)(Gn)),i=n.div(r);return i.mul(i)}),Xn=(0,o.Fn)(([e,t])=>{let n=e.sub(t),r=(0,o.max)(e.add(t),Gn),i=n.div(r);return i.mul(i)}),Zn=e=>(0,o.vec3)(Xn(e,(0,o.float)(1))),Qn=(0,o.Fn)(([e,t])=>{let n=t.mul(t),r=n.mul(n),i=e.mul(e).mul(r.sub(1)).add(1);return r.div((0,o.max)((0,o.float)(q).mul(i).mul(i),J))}),$n=(0,o.Fn)(([e,t])=>{let n=(0,o.max)(t,Rt),r=n.mul(n),i=(0,o.float)(1).div(r),a=e.mul(e).mul(i.mul(i).sub(1)).add(1);return(0,o.min)(i.mul(i).div((0,o.max)((0,o.float)(q).mul(a).mul(a),J)),100)}),er=(0,o.Fn)(([e,t])=>{let n=t.add(1),r=n.mul(n).div(8);return e.div((0,o.max)(e.mul((0,o.float)(1).sub(r)).add(r),J))}),tr=(0,o.Fn)(([e,t,n])=>{let r=er(e,n);return er(t,n).mul(r)}),nr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).sub(n),i=n.mul(-.0275).add(.0425),a=n.mul(-.572).add(1.04),s=n.mul(.022).sub(.04),c=(0,o.min)(r.mul(r),(0,o.exp)((0,o.float)(-6.4308).mul(t))).mul(r).add(i),l=(0,o.float)(-1.04).mul(c).add(a),u=(0,o.float)(1.04).mul(c).add(s),d=(0,o.max)(l.add(u),.1);return(0,o.vec3)(1).add(e.mul((0,o.float)(1).div(d).sub(1)))}),rr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).sub(n),i=n.mul(-.0275).add(.0425),a=n.mul(-.572).add(1.04),s=n.mul(.022).sub(.04),c=(0,o.min)(r.mul(r),(0,o.exp)((0,o.float)(-6.4308).mul(t))).mul(r).add(i),l=(0,o.float)(-1.04).mul(c).add(a),u=(0,o.float)(1.04).mul(c).add(s),d=(0,o.max)(e.mul(l).add((0,o.vec3)(u)),(0,o.vec3)(0)),f=(0,o.max)(l.add(u),.1),p=(0,o.vec3)(1).add(e.mul((0,o.float)(1).div(f).sub(1)));return(0,o.clamp)(d.mul(p),(0,o.vec3)(0),(0,o.vec3)(1))}),ir=(0,o.Fn)(([e,t,n])=>Qn(e,n).mul(e).div((0,o.max)((0,o.float)(4).mul(t),J))),ar=(0,o.Fn)(([e,t,n])=>{let r=Qn(e,n),i=er(t,n);return r.mul(i).div((0,o.max)(t.mul(4),J))}),or=(0,o.Fn)(([e,t])=>{let n=(0,o.float)(Lt).mul(e).mul(1e-9),r=(0,o.vec3)(54856e-17,44201e-17,52481e-17),i=(0,o.vec3)(1681e3,1795300,2208400),a=(0,o.vec3)(43278e5,93046e5,66121e5),s=r.mul((0,o.sqrt)((0,o.float)(Lt).mul(a))).mul((0,o.cos)(i.mul(n).add(t))).mul((0,o.exp)(Wt({x:n}).negate().mul(a))).toVar();return s.x.addAssign((0,o.float)(9747e-17).mul((0,o.sqrt)((0,o.float)(Lt).mul(45282e5))).mul((0,o.cos)((0,o.float)(2239900).mul(n).add(t.x))).mul((0,o.exp)((0,o.float)(-45282e5).mul(Wt({x:n}))))),Ut.mul(s.div(1.0685e-7))}),sr=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.mix)(e,t,(0,o.smoothstep)(0,.03,r)).toVar(),s=Wt({x:e.div(a)}).mul((0,o.float)(1).sub(Wt({x:n}))).toVar(),c=(0,o.float)(1).sub(s).toVar(),l=(0,o.vec3)(0).toVar();return(0,o.If)(c.lessThan(0),()=>{l.assign((0,o.vec3)(1))}).Else(()=>{let t=(0,o.sqrt)(c).toVar(),s=Kn(n,Xn(a,e).toVar()).toVar(),u=(0,o.float)(1).sub(s).toVar(),d=a.lessThan(e).select((0,o.float)(q),(0,o.float)(0)).toVar(),f=(0,o.float)(q).sub(d).toVar(),p=Jn((0,o.clamp)(i,0,.9999)).toVar(),m=Yn(p,a).toVar(),h=(0,o.vec3)(Kn(t,m.x),Kn(t,m.y),Kn(t,m.z)).toVar(),g=(0,o.vec3)(p.x.lessThan(a).select((0,o.float)(q),(0,o.float)(0)),p.y.lessThan(a).select((0,o.float)(q),(0,o.float)(0)),p.z.lessThan(a).select((0,o.float)(q),(0,o.float)(0))).toVar(),_=(0,o.float)(2).mul(a).mul(r).mul(t).toVar(),v=(0,o.vec3)(f).add(g).toVar(),y=(0,o.clamp)((0,o.vec3)(s).mul(h),1e-5,.9999).toVar(),b=(0,o.sqrt)(y).toVar(),x=(0,o.vec3)(u.mul(u)).mul(h).div((0,o.vec3)(1).sub(y)).toVar(),S=(0,o.vec3)(s).add(x).toVar().toVar(),C=x.sub((0,o.vec3)(u)).toVar();C.mulAssign(b),S.addAssign(C.mul((0,o.float)(2).mul(or((0,o.float)(1).mul(_),(0,o.float)(1).mul(v))))),C.mulAssign(b),S.addAssign(C.mul((0,o.float)(2).mul(or((0,o.float)(2).mul(_),(0,o.float)(2).mul(v))))),l.assign((0,o.max)(S,(0,o.vec3)(0)))}),l}),cr=(0,o.Fn)(([e,t,n])=>{let r=n.invRoughness,i=n.metalFactor,a=(0,o.float)(0).toVar();(0,o.If)(t.isMetallic,()=>{a.assign((0,o.max)(r.mul(i),.7))}).ElseIf(t.isSmooth,()=>{a.assign(r.mul(i).mul(1.2))}).Else(()=>{a.assign((0,o.max)(r.mul(i),e.metalness.mul(.1)))});let s=a.mul(e.specularIntensity).toVar(),c=(0,o.float)(1).sub(a).mul((0,o.float)(1).sub(e.metalness)).toVar(),l=e.sheen.mul(n.maxSheenColor).toVar(),u=(0,o.float)(0).toVar();(0,o.If)(t.hasClearcoat,()=>{u.assign(e.clearcoat.mul(r).mul(.4))}).Else(()=>{u.assign(e.clearcoat.mul(r).mul(.35))});let d=(0,o.float)(0).toVar();(0,o.If)(t.isTransmissive,()=>{let t=n.iorFactor.mul(r).mul(.8);d.assign(e.transmission.mul(t).mul((0,o.float)(.6).add((0,o.float)(.4).mul(e.ior.div(2)))).mul((0,o.float)(1).add(e.dispersion.mul(.6))))}).Else(()=>{let t=n.iorFactor.mul(r).mul(.7);d.assign(e.transmission.mul(t).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.ior.div(2)))).mul((0,o.float)(1).add(e.dispersion.mul(.5))))});let f=r.mul(t.isSmooth.select((0,o.float)(.6),(0,o.float)(.5))),p=(0,o.min)(e.iridescence.mul(f).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.iridescenceThicknessRange.y.sub(e.iridescenceThicknessRange.x).div(1e3)))).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.iridescenceIOR.div(2)))),c);s.addAssign(p),c.subAssign(p);let m=s.add(c).add(l).add(u).add(d),h=(0,o.float)(1).div((0,o.max)(m,.001));return Et({specular:s.mul(h),diffuse:c.mul(h),sheen:l.mul(h),clearcoat:u.mul(h),transmission:d.mul(h),iridescence:(0,o.float)(0)})});(0,o.Fn)(([e,t])=>{let n=(0,o.float)(0).toVar();return(0,o.If)(e.transmission.greaterThan(0).or(e.clearcoat.greaterThan(0)),()=>{n.assign(.95)}).Else(()=>{let r=t.complexityScore.toVar(),i=(0,o.float)(0).toVar();(0,o.If)(t.isEmissive,()=>{let t=(0,o.dot)(e.emissive,Vt);i.assign((0,o.min)((0,o.float)(.6),t.mul(e.emissiveIntensity).mul(.25)))});let a=(0,o.float)(0).toVar();(0,o.If)(t.isMetallic.and(t.isSmooth),()=>{a.addAssign(.25)}).ElseIf(t.isMetallic,()=>{a.addAssign(.15)}),(0,o.If)(t.isTransmissive,()=>{a.addAssign(.2)}),(0,o.If)(t.hasClearcoat,()=>{a.addAssign(.1)});let s=(0,o.max)(r.add(a),i);n.assign((0,o.clamp)(s,0,1))}),n});var lr=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=(0,o.float)(1).sub(e.roughness),c=(0,o.float)(.5).add((0,o.float)(.5).mul(e.metalness)),l=(0,o.min)((0,o.float)(2).div(e.ior),1),u=(0,o.max)(e.sheenColor.r,(0,o.max)(e.sheenColor.g,e.sheenColor.b)),d=Mt({NoV:(0,o.float)(.5),isPurelyDiffuse:!1,isMetallic:n.isMetallic,hasSpecialFeatures:!1,alpha:e.roughness.mul(e.roughness),alpha2:e.roughness.mul(e.roughness).mul(e.roughness).mul(e.roughness),k:e.roughness.add(1).mul(e.roughness.add(1)).div(8),F0:Zn(e.ior),diffuseColor:e.color.rgb,specularColor:e.color.rgb,tsAlbedo:e.color,tsEmissive:e.emissive,tsMetalness:e.metalness,tsRoughness:e.roughness,tsNormal:(0,o.vec3)(0,1,0),tsHasTextures:!1,invRoughness:s,metalFactor:c,iorFactor:l,maxSheenColor:u}),f=Et.wrap(cr(e,n,d)),p=f.diffuse.toVar(),m=f.specular.toVar(),h=f.transmission.toVar(),g=f.clearcoat.toVar();(0,o.If)(t.greaterThan((0,o.int)(2)),()=>{let e=(0,o.float)(1).div((0,o.float)(t).sub(1));m.mulAssign((0,o.float)(.8).add(e.mul(.2))),g.mulAssign((0,o.float)(.7).add(e.mul(.3))),p.mulAssign((0,o.float)(1).add(e.mul(.2)))}),(0,o.If)(n.isMetallic.and(t.lessThan((0,o.int)(3))),()=>{m.assign((0,o.max)(m,.6)),p.mulAssign(.4)}),(0,o.If)(n.isTransmissive,()=>{h.assign((0,o.max)(h,.8)),p.mulAssign(.2),m.mulAssign(.6)}),(0,o.If)(n.hasClearcoat,()=>{g.assign((0,o.max)(g,.4))});let _=p.add(m).add(h).add(g).toVar();return(0,o.If)(_.greaterThan(.001),()=>{let e=(0,o.float)(1).div(_);p.mulAssign(e),m.mulAssign(e),h.mulAssign(e),g.mulAssign(e)}).Else(()=>{p.assign(1),m.assign(0),h.assign(0),g.assign(0)}),Dt({diffuseImportance:p,specularImportance:m,transmissionImportance:h,clearcoatImportance:g,envmapImportance:(0,o.float)(0)})}),ur=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.max)((0,o.dot)(e,t),.001).toVar(),s=i.isRough.and(i.isMetallic.not()).and(n.transmission.equal(0)).and(n.clearcoat.equal(0)).toVar(),c=i.isMetallic.toVar(),l=i.isTransmissive.or(i.hasClearcoat).or(n.sheen.greaterThan(0)).or(n.iridescence.greaterThan(0)).toVar(),u=r.roughness.mul(r.roughness).toVar(),d=u.mul(u).toVar(),f=r.roughness.add(1),p=f.mul(f).div(8).toVar(),m=(0,o.mix)(Zn(n.ior).mul(n.specularColor),r.albedo.rgb,r.metalness).mul(n.specularIntensity).toVar(),h=r.albedo.rgb.mul((0,o.float)(1).sub(r.metalness)).toVar(),g=r.albedo.rgb.toVar(),_=(0,o.float)(1).sub(r.roughness).toVar(),v=(0,o.float)(.5).add((0,o.float)(.5).mul(r.metalness)).toVar(),y=(0,o.min)((0,o.float)(2).div(n.ior),1).toVar(),b=(0,o.max)(n.sheenColor.r,(0,o.max)(n.sheenColor.g,n.sheenColor.b)).toVar();return Mt({NoV:a,isPurelyDiffuse:s,isMetallic:c,hasSpecialFeatures:l,alpha:u,alpha2:d,k:p,F0:m,diffuseColor:h,specularColor:g,tsAlbedo:r.albedo,tsEmissive:r.emissive,tsMetalness:r.metalness,tsRoughness:r.roughness,tsNormal:r.normal,tsHasTextures:r.hasTextures,invRoughness:_,metalFactor:v,iorFactor:y,maxSheenColor:b})});(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.dot)(e,t),.001).toVar(),i=n.roughness.greaterThan(.98).and(n.metalness.lessThan(.02)).and(n.transmission.equal(0)).and(n.clearcoat.equal(0)).toVar(),a=n.metalness.greaterThan(.7).toVar(),s=n.transmission.greaterThan(0).or(n.clearcoat.greaterThan(0)).or(n.sheen.greaterThan(0)).or(n.iridescence.greaterThan(0)).toVar(),c=n.roughness.mul(n.roughness).toVar(),l=c.mul(c).toVar(),u=n.roughness.add(1),d=u.mul(u).div(8).toVar(),f=(0,o.mix)(Zn(n.ior).mul(n.specularColor),n.color.rgb,n.metalness).mul(n.specularIntensity).toVar(),p=n.color.rgb.mul((0,o.float)(1).sub(n.metalness)).toVar(),m=n.color.rgb.toVar(),h=kt({albedo:n.color,emissive:n.emissive.mul(n.emissiveIntensity),metalness:n.metalness,roughness:n.roughness,normal:e,hasTextures:!1}),g=(0,o.float)(1).sub(n.roughness).toVar(),_=(0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness)).toVar(),v=(0,o.min)((0,o.float)(2).div(n.ior),1).toVar(),y=(0,o.max)(n.sheenColor.r,(0,o.max)(n.sheenColor.g,n.sheenColor.b)).toVar();return Mt({NoV:r,isPurelyDiffuse:i,isMetallic:a,hasSpecialFeatures:s,alpha:c,alpha2:l,k:d,F0:f,diffuseColor:p,specularColor:m,tsAlbedo:h.albedo,tsEmissive:h.emissive,tsMetalness:h.metalness,tsRoughness:h.roughness,tsNormal:h.normal,tsHasTextures:h.hasTextures,invRoughness:g,metalFactor:_,iorFactor:v,maxSheenColor:y})});var dr=(0,o.wgslFn)(`
|
|
413
|
+
`),jn=(0,o.Fn)(([e,t])=>{let n=An({t:t.albedoTransform}).toVar(),r=An({t:t.normalTransform}).toVar(),i=An({t:t.metalnessTransform}).toVar(),a=An({t:t.roughnessTransform}).toVar(),s=An({t:t.emissiveTransform}).toVar(),c=An({t:t.bumpTransform}).toVar(),l=.001,u=(0,o.abs)(n.sub(r)).lessThan(l).toVar(),d=(0,o.abs)(r.sub(c)).lessThan(l).toVar(),f=(0,o.abs)(i.sub(a)).lessThan(l).toVar(),p=(0,o.abs)(n.sub(s)).lessThan(l).toVar(),m=u.and((0,o.abs)(n.sub(i)).lessThan(l)).and((0,o.abs)(n.sub(s)).lessThan(l)).and((0,o.abs)(n.sub(c)).lessThan(l)).toVar(),h=(0,o.vec2)(0).toVar(),g=(0,o.vec2)(0).toVar(),_=(0,o.vec2)(0).toVar(),v=(0,o.vec2)(0).toVar(),y=(0,o.vec2)(0).toVar(),b=(0,o.vec2)(0).toVar(),x=d.or(m).toVar(),S=f.or(m).toVar(),C=p.or(m).toVar();return(0,o.If)(m,()=>{let n=On({uv:e,transform:t.albedoTransform});h.assign(n),g.assign(n),_.assign(n),v.assign(n),y.assign(n),b.assign(n)}).Else(()=>{h.assign(On({uv:e,transform:t.albedoTransform})),g.assign(u.select(h,On({uv:e,transform:t.normalTransform}))),y.assign(p.select(h,On({uv:e,transform:t.emissiveTransform}))),(0,o.If)(d,()=>{b.assign(g)}).ElseIf((0,o.abs)(c.sub(n)).lessThan(l),()=>{b.assign(h)}).Else(()=>{b.assign(On({uv:e,transform:t.bumpTransform}))}),(0,o.If)(f,()=>{_.assign(On({uv:e,transform:t.metalnessTransform})),v.assign(_)}).Else(()=>{(0,o.If)((0,o.abs)(i.sub(n)).lessThan(l),()=>{_.assign(h)}).ElseIf((0,o.abs)(i.sub(r)).lessThan(l),()=>{_.assign(g)}).Else(()=>{_.assign(On({uv:e,transform:t.metalnessTransform}))}),(0,o.If)((0,o.abs)(a.sub(n)).lessThan(l),()=>{v.assign(h)}).ElseIf((0,o.abs)(a.sub(r)).lessThan(l),()=>{v.assign(g)}).ElseIf((0,o.abs)(a.sub(i)).lessThan(l),()=>{v.assign(_)}).Else(()=>{v.assign(On({uv:e,transform:t.roughnessTransform}))})})}),Mt({albedoUV:h,normalUV:g,metalnessUV:_,roughnessUV:v,emissiveUV:y,bumpUV:b,allSameUV:m,normalBumpSameUV:x,metalRoughSameUV:S,albedoEmissiveSameUV:C})}),Mn=(0,o.Fn)(([e,t,n])=>{let r=t.color.toVar();return(0,o.If)(t.albedoMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let i=(0,o.texture)(e,n.albedoUV).depth((0,o.int)(t.albedoMapIndex)).toVar();r.assign((0,o.vec4)(t.color.rgb.mul(i.rgb),t.color.a.mul(i.a)))}),r}),Nn=(0,o.Fn)(([e,t,n,r])=>{let i=n.metalness.toVar(),a=n.roughness.toVar();return(0,o.If)(n.metalnessMapIndex.greaterThanEqual((0,o.int)(0)).and(n.metalnessMapIndex.equal(n.roughnessMapIndex)),()=>{let t=(0,o.texture)(e,r.metalnessUV).depth((0,o.int)(n.metalnessMapIndex));i.assign(n.metalness.mul(t.b)),a.assign(n.roughness.mul(t.g))}).Else(()=>{(0,o.If)(n.metalnessMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let t=(0,o.texture)(e,r.metalnessUV).depth((0,o.int)(n.metalnessMapIndex));i.assign(n.metalness.mul(t.b))}),(0,o.If)(n.roughnessMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let e=(0,o.texture)(t,r.roughnessUV).depth((0,o.int)(n.roughnessMapIndex));a.assign(n.roughness.mul(e.g))})}),(0,o.vec2)(i,a)}),Pn=(0,o.Fn)(([e,t,n,r])=>{let i=t.toVar();return(0,o.If)(n.normalMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let a=(0,o.texture)(e,r.normalUV).depth((0,o.int)(n.normalMapIndex)).xyz.mul(2).sub(1).toVar();a.x.mulAssign(n.normalScale.x),a.y.assign(a.y.negate().mul(n.normalScale.x));let s=(0,o.normalize)((0,o.cross)((0,o.abs)(t.z).lessThan(.999).select((0,o.vec3)(0,0,1),(0,o.vec3)(1,0,0)),t)),c=(0,o.cross)(t,s);i.assign((0,o.normalize)(s.mul(a.x).add(c.mul(a.y)).add(t.mul(a.z))))}),i}),Fn=(0,o.Fn)(([e,t,n,r])=>{let i=t.toVar();return(0,o.If)(n.bumpMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let a=(0,o.vec2)(1/1024).toVar(),s=(0,o.texture)(e,r.bumpUV).depth((0,o.int)(n.bumpMapIndex)).r,c=(0,o.texture)(e,(0,o.vec2)(r.bumpUV.x.add(a.x),r.bumpUV.y)).depth((0,o.int)(n.bumpMapIndex)).r,l=(0,o.texture)(e,(0,o.vec2)(r.bumpUV.x,r.bumpUV.y.add(a.y))).depth((0,o.int)(n.bumpMapIndex)).r,u=(0,o.vec2)(c.sub(s),l.sub(s)).mul(n.bumpScale),d=(0,o.normalize)((0,o.vec3)(u.x.negate(),u.y.negate(),1)),f=(0,o.normalize)((0,o.cross)((0,o.abs)(t.z).lessThan(.999).select((0,o.vec3)(0,0,1),(0,o.vec3)(1,0,0)),t)),p=(0,o.cross)(t,f),m=f.mul(d.x).add(p.mul(d.y)).add(t.mul(d.z));i.assign((0,o.normalize)((0,o.mix)(t,m,(0,o.clamp)(n.bumpScale,0,1))))}),i}),In=(0,o.Fn)(([e,t,n,r])=>{let i=t.emissive.mul(t.emissiveIntensity).toVar();return(0,o.If)(t.emissiveMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let n=(0,o.texture)(e,r.emissiveUV).depth((0,o.int)(t.emissiveMapIndex)).toVar();i.assign(i.mul(n.rgb))}),i}),Ln=(0,o.Fn)(([e,t,n,r,i,a,s,c,l])=>{let u=(0,o.vec4)(0).toVar(),d=(0,o.vec3)(0).toVar(),f=(0,o.float)(0).toVar(),p=(0,o.float)(0).toVar(),m=(0,o.vec3)(0).toVar(),h=kn(s).toVar();return u.assign(s.color),d.assign(s.emissive.mul(s.emissiveIntensity)),f.assign(s.metalness),p.assign(s.roughness),m.assign(l),(0,o.If)(h,()=>{let o=Mt.wrap(jn(c,s)).toVar();u.assign(Mn(e,s,o));let h=Nn(r,i,s,o);f.assign(h.x),p.assign(h.y);let g=Pn(t,l,s,o).toVar();m.assign(Fn(n,g,s,o)),d.assign(In(a,s,u,o))}),At({albedo:u,emissive:d,metalness:f,roughness:p,normal:m,hasTextures:h})});(0,o.Fn)(([e,t,n,r,i,a,s,c])=>At.wrap(Ln(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).albedo),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>At.wrap(Ln(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).emissive),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>At.wrap(Ln(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).metalness),(0,o.Fn)(([e,t,n,r,i,a,s,c])=>At.wrap(Ln(e,t,n,r,i,a,s,c,(0,o.vec3)(0,1,0))).roughness),(0,o.Fn)(([e,t,n,r,i,a,o,s,c])=>At.wrap(Ln(e,t,n,r,i,a,o,s,c)).normal);var Rn=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.float)(0).toVar();return(0,o.If)(t.greaterThanEqual((0,o.int)(0)),()=>{let a=On({uv:n,transform:r});i.assign((0,o.texture)(e,a).depth((0,o.int)(t)).r)}),i}),zn=32,Bn=16,Vn=5,Hn=1/1024,Un=8,Wn=K({hitPoint:`vec3`,uv:`vec2`,normal:`vec3`,height:`float`}),Gn=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=t.hitPoint.toVar(),c=t.uv.toVar(),l=t.normal.toVar(),u=(0,o.float)(0).toVar(),d=t.triangleIndex,f=Z(n,d,(0,o.int)(0),(0,o.int)(Un)).xyz.toVar(),p=Z(n,d,(0,o.int)(1),(0,o.int)(Un)).xyz.toVar(),m=Z(n,d,(0,o.int)(2),(0,o.int)(Un)).xyz.toVar(),h=Z(n,d,(0,o.int)(6),(0,o.int)(Un)).toVar(),g=Z(n,d,(0,o.int)(7),(0,o.int)(Un)).toVar(),_=h.xy.toVar(),v=h.zw.toVar(),y=g.xy.toVar(),b=p.sub(f).toVar(),x=m.sub(f).toVar(),S=v.sub(_).toVar(),C=y.sub(_).toVar(),w=S.x.mul(C.y).sub(C.x.mul(S.y)).toVar();return(0,o.If)((0,o.abs)(w).greaterThan(1e-8),()=>{let n=(0,o.float)(1).div(w),d=b.mul(C.y).sub(x.mul(S.y)).mul(n).toVar(),f=x.mul(S.x).sub(b.mul(C.x)).mul(n).toVar(),p=t.normal.toVar(),m=i.displacementScale.div((0,o.float)(10)),h=e.direction,g=(0,o.dot)(h,p).toVar(),_=h.sub(p.mul(g)).toVar(),v=(0,o.dot)(d,d),y=(0,o.dot)(d,f),T=(0,o.dot)(f,f),E=v.mul(T).sub(y.mul(y)).toVar();(0,o.If)((0,o.abs)(E).greaterThan(1e-10),()=>{let e=(0,o.float)(1).div(E),n=(0,o.dot)(_,d),b=(0,o.dot)(_,f),x=(0,o.vec2)(T.mul(n).sub(y.mul(b)).mul(e).toVar(),v.mul(b).sub(y.mul(n)).mul(e).toVar()).toVar(),S=g.toVar(),C=(0,o.max)((0,o.abs)(S),.001).toVar(),w=m.div(C).toVar(),D=(0,o.int)(a.equal((0,o.int)(0)).select((0,o.int)(zn),(0,o.int)(Bn))).toVar(),O=w.negate().toVar(),k=w.toVar().sub(O).div((0,o.float)(D)).toVar(),A=O.toVar(),j=O.toVar(),M=(0,o.int)(0).toVar();(0,o.Loop)({start:(0,o.int)(0),end:D,type:`int`,condition:`<`},({i:e})=>{(0,o.If)(M.equal((0,o.int)(0)),()=>{let n=O.add(k.mul((0,o.float)(e))).toVar(),a=t.uv.add(x.mul(n)).toVar(),s=n.mul(S).toVar(),c=Rn(r,i.displacementMapIndex,a,i.displacementTransform).sub(.5).mul(m);(0,o.If)(s.lessThanEqual(c).and(e.greaterThan((0,o.int)(0))),()=>{M.assign(1),j.assign(n)}).Else(()=>{A.assign(n)})})}),(0,o.If)(M.equal((0,o.int)(1)),()=>{let e=A.toVar(),n=j.toVar();(0,o.Loop)({start:(0,o.int)(0),end:(0,o.int)(Vn),type:`int`,condition:`<`},()=>{let a=e.add(n).mul(.5).toVar(),s=t.uv.add(x.mul(a)).toVar(),c=a.mul(S),l=Rn(r,i.displacementMapIndex,s,i.displacementTransform).sub(.5).mul(m);(0,o.If)(c.lessThanEqual(l),()=>{n.assign(a)}).Else(()=>{e.assign(a)})});let a=e.add(n).mul(.5).toVar(),g=t.uv.add(x.mul(a)).toVar(),_=t.hitPoint.add(h.mul(a)).toVar(),v=Rn(r,i.displacementMapIndex,g,i.displacementTransform),y=v.sub(.5).mul(m),b=(0,o.float)(Hn),C=v,w=Rn(r,i.displacementMapIndex,g.add((0,o.vec2)(b,0)),i.displacementTransform),T=Rn(r,i.displacementMapIndex,g.add((0,o.vec2)(0,b)),i.displacementTransform),E=(0,o.normalize)(d).toVar(),D=(0,o.normalize)(f).toVar(),O=w.sub(C).mul(m),k=T.sub(C).mul(m),M=(0,o.normalize)(p.sub(E.mul(O)).sub(D.mul(k)));s.assign(_),c.assign(g),l.assign(M),u.assign(y)})})}),Wn({hitPoint:s,uv:c,normal:l,height:u})}),Kn=1e-6;(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.vec3)((0,o.float)(1).sub(n)),e);return e.add(r.sub(e).mul((0,o.pow)((0,o.float)(1).sub(t),5)))});var qn=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)(e,0,1);return t.add((0,o.float)(1).sub(t).mul((0,o.pow)((0,o.float)(1).sub(n),5)))}),Jn=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)(e,0,1);return t.add((0,o.vec3)(1).sub(t).mul((0,o.pow)((0,o.float)(1).sub(n),5)))}),Yn=(0,o.Fn)(([e])=>{let t=(0,o.sqrt)(e);return(0,o.vec3)(1).add(t).div((0,o.max)((0,o.vec3)(1).sub(t),(0,o.vec3)(Kn)))}),Xn=(0,o.Fn)(([e,t])=>{let n=e.sub((0,o.vec3)(t)),r=(0,o.max)(e.add((0,o.vec3)(t)),(0,o.vec3)(Kn)),i=n.div(r);return i.mul(i)}),Zn=(0,o.Fn)(([e,t])=>{let n=e.sub(t),r=(0,o.max)(e.add(t),Kn),i=n.div(r);return i.mul(i)}),Qn=e=>(0,o.vec3)(Zn(e,(0,o.float)(1))),$n=(0,o.Fn)(([e,t])=>{let n=t.mul(t),r=n.mul(n),i=e.mul(e).mul(r.sub(1)).add(1);return r.div((0,o.max)((0,o.float)(q).mul(i).mul(i),J))}),er=(0,o.Fn)(([e,t])=>{let n=(0,o.max)(t,zt),r=n.mul(n),i=(0,o.float)(1).div(r),a=e.mul(e).mul(i.mul(i).sub(1)).add(1);return(0,o.min)(i.mul(i).div((0,o.max)((0,o.float)(q).mul(a).mul(a),J)),100)}),tr=(0,o.Fn)(([e,t])=>{let n=t.add(1),r=n.mul(n).div(8);return e.div((0,o.max)(e.mul((0,o.float)(1).sub(r)).add(r),J))}),nr=(0,o.Fn)(([e,t,n])=>{let r=tr(e,n);return tr(t,n).mul(r)}),rr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).sub(n),i=n.mul(-.0275).add(.0425),a=n.mul(-.572).add(1.04),s=n.mul(.022).sub(.04),c=(0,o.min)(r.mul(r),(0,o.exp)((0,o.float)(-6.4308).mul(t))).mul(r).add(i),l=(0,o.float)(-1.04).mul(c).add(a),u=(0,o.float)(1.04).mul(c).add(s),d=(0,o.max)(l.add(u),.1);return(0,o.vec3)(1).add(e.mul((0,o.float)(1).div(d).sub(1)))}),ir=(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).sub(n),i=n.mul(-.0275).add(.0425),a=n.mul(-.572).add(1.04),s=n.mul(.022).sub(.04),c=(0,o.min)(r.mul(r),(0,o.exp)((0,o.float)(-6.4308).mul(t))).mul(r).add(i),l=(0,o.float)(-1.04).mul(c).add(a),u=(0,o.float)(1.04).mul(c).add(s),d=(0,o.max)(e.mul(l).add((0,o.vec3)(u)),(0,o.vec3)(0)),f=(0,o.max)(l.add(u),.1),p=(0,o.vec3)(1).add(e.mul((0,o.float)(1).div(f).sub(1)));return(0,o.clamp)(d.mul(p),(0,o.vec3)(0),(0,o.vec3)(1))}),ar=(0,o.Fn)(([e,t,n])=>$n(e,n).mul(e).div((0,o.max)((0,o.float)(4).mul(t),J))),or=(0,o.Fn)(([e,t,n])=>{let r=$n(e,n),i=tr(t,n);return r.mul(i).div((0,o.max)(t.mul(4),J))}),sr=(0,o.Fn)(([e,t])=>{let n=(0,o.float)(Rt).mul(e).mul(1e-9),r=(0,o.vec3)(54856e-17,44201e-17,52481e-17),i=(0,o.vec3)(1681e3,1795300,2208400),a=(0,o.vec3)(43278e5,93046e5,66121e5),s=r.mul((0,o.sqrt)((0,o.float)(Rt).mul(a))).mul((0,o.cos)(i.mul(n).add(t))).mul((0,o.exp)(Gt({x:n}).negate().mul(a))).toVar();return s.x.addAssign((0,o.float)(9747e-17).mul((0,o.sqrt)((0,o.float)(Rt).mul(45282e5))).mul((0,o.cos)((0,o.float)(2239900).mul(n).add(t.x))).mul((0,o.exp)((0,o.float)(-45282e5).mul(Gt({x:n}))))),Wt.mul(s.div(1.0685e-7))}),cr=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.mix)(e,t,(0,o.smoothstep)(0,.03,r)).toVar(),s=Gt({x:e.div(a)}).mul((0,o.float)(1).sub(Gt({x:n}))).toVar(),c=(0,o.float)(1).sub(s).toVar(),l=(0,o.vec3)(0).toVar();return(0,o.If)(c.lessThan(0),()=>{l.assign((0,o.vec3)(1))}).Else(()=>{let t=(0,o.sqrt)(c).toVar(),s=qn(n,Zn(a,e).toVar()).toVar(),u=(0,o.float)(1).sub(s).toVar(),d=a.lessThan(e).select((0,o.float)(q),(0,o.float)(0)).toVar(),f=(0,o.float)(q).sub(d).toVar(),p=Yn((0,o.clamp)(i,0,.9999)).toVar(),m=Xn(p,a).toVar(),h=(0,o.vec3)(qn(t,m.x),qn(t,m.y),qn(t,m.z)).toVar(),g=(0,o.vec3)(p.x.lessThan(a).select((0,o.float)(q),(0,o.float)(0)),p.y.lessThan(a).select((0,o.float)(q),(0,o.float)(0)),p.z.lessThan(a).select((0,o.float)(q),(0,o.float)(0))).toVar(),_=(0,o.float)(2).mul(a).mul(r).mul(t).toVar(),v=(0,o.vec3)(f).add(g).toVar(),y=(0,o.clamp)((0,o.vec3)(s).mul(h),1e-5,.9999).toVar(),b=(0,o.sqrt)(y).toVar(),x=(0,o.vec3)(u.mul(u)).mul(h).div((0,o.vec3)(1).sub(y)).toVar(),S=(0,o.vec3)(s).add(x).toVar().toVar(),C=x.sub((0,o.vec3)(u)).toVar();C.mulAssign(b),S.addAssign(C.mul((0,o.float)(2).mul(sr((0,o.float)(1).mul(_),(0,o.float)(1).mul(v))))),C.mulAssign(b),S.addAssign(C.mul((0,o.float)(2).mul(sr((0,o.float)(2).mul(_),(0,o.float)(2).mul(v))))),l.assign((0,o.max)(S,(0,o.vec3)(0)))}),l}),lr=(0,o.Fn)(([e,t,n])=>{let r=n.invRoughness,i=n.metalFactor,a=(0,o.float)(0).toVar();(0,o.If)(t.isMetallic,()=>{a.assign((0,o.max)(r.mul(i),.7))}).ElseIf(t.isSmooth,()=>{a.assign(r.mul(i).mul(1.2))}).Else(()=>{a.assign((0,o.max)(r.mul(i),e.metalness.mul(.1)))});let s=a.mul(e.specularIntensity).toVar(),c=(0,o.float)(1).sub(a).mul((0,o.float)(1).sub(e.metalness)).toVar(),l=e.sheen.mul(n.maxSheenColor).toVar(),u=(0,o.float)(0).toVar();(0,o.If)(t.hasClearcoat,()=>{u.assign(e.clearcoat.mul(r).mul(.4))}).Else(()=>{u.assign(e.clearcoat.mul(r).mul(.35))});let d=(0,o.float)(0).toVar();(0,o.If)(t.isTransmissive,()=>{let t=n.iorFactor.mul(r).mul(.8);d.assign(e.transmission.mul(t).mul((0,o.float)(.6).add((0,o.float)(.4).mul(e.ior.div(2)))).mul((0,o.float)(1).add(e.dispersion.mul(.6))))}).Else(()=>{let t=n.iorFactor.mul(r).mul(.7);d.assign(e.transmission.mul(t).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.ior.div(2)))).mul((0,o.float)(1).add(e.dispersion.mul(.5))))});let f=r.mul(t.isSmooth.select((0,o.float)(.6),(0,o.float)(.5))),p=(0,o.min)(e.iridescence.mul(f).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.iridescenceThicknessRange.y.sub(e.iridescenceThicknessRange.x).div(1e3)))).mul((0,o.float)(.5).add((0,o.float)(.5).mul(e.iridescenceIOR.div(2)))),c);s.addAssign(p),c.subAssign(p);let m=s.add(c).add(l).add(u).add(d),h=(0,o.float)(1).div((0,o.max)(m,.001));return Dt({specular:s.mul(h),diffuse:c.mul(h),sheen:l.mul(h),clearcoat:u.mul(h),transmission:d.mul(h),iridescence:(0,o.float)(0)})});(0,o.Fn)(([e,t])=>{let n=(0,o.float)(0).toVar();return(0,o.If)(e.transmission.greaterThan(0).or(e.clearcoat.greaterThan(0)),()=>{n.assign(.95)}).Else(()=>{let r=t.complexityScore.toVar(),i=(0,o.float)(0).toVar();(0,o.If)(t.isEmissive,()=>{let t=(0,o.dot)(e.emissive,Ht);i.assign((0,o.min)((0,o.float)(.6),t.mul(e.emissiveIntensity).mul(.25)))});let a=(0,o.float)(0).toVar();(0,o.If)(t.isMetallic.and(t.isSmooth),()=>{a.addAssign(.25)}).ElseIf(t.isMetallic,()=>{a.addAssign(.15)}),(0,o.If)(t.isTransmissive,()=>{a.addAssign(.2)}),(0,o.If)(t.hasClearcoat,()=>{a.addAssign(.1)});let s=(0,o.max)(r.add(a),i);n.assign((0,o.clamp)(s,0,1))}),n});var ur=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=(0,o.float)(1).sub(e.roughness),c=(0,o.float)(.5).add((0,o.float)(.5).mul(e.metalness)),l=(0,o.min)((0,o.float)(2).div(e.ior),1),u=(0,o.max)(e.sheenColor.r,(0,o.max)(e.sheenColor.g,e.sheenColor.b)),d=Nt({NoV:(0,o.float)(.5),isPurelyDiffuse:!1,isMetallic:n.isMetallic,hasSpecialFeatures:!1,alpha:e.roughness.mul(e.roughness),alpha2:e.roughness.mul(e.roughness).mul(e.roughness).mul(e.roughness),k:e.roughness.add(1).mul(e.roughness.add(1)).div(8),F0:Qn(e.ior),diffuseColor:e.color.rgb,specularColor:e.color.rgb,tsAlbedo:e.color,tsEmissive:e.emissive,tsMetalness:e.metalness,tsRoughness:e.roughness,tsNormal:(0,o.vec3)(0,1,0),tsHasTextures:!1,invRoughness:s,metalFactor:c,iorFactor:l,maxSheenColor:u}),f=Dt.wrap(lr(e,n,d)),p=f.diffuse.toVar(),m=f.specular.toVar(),h=f.transmission.toVar(),g=f.clearcoat.toVar();(0,o.If)(t.greaterThan((0,o.int)(2)),()=>{let e=(0,o.float)(1).div((0,o.float)(t).sub(1));m.mulAssign((0,o.float)(.8).add(e.mul(.2))),g.mulAssign((0,o.float)(.7).add(e.mul(.3))),p.mulAssign((0,o.float)(1).add(e.mul(.2)))}),(0,o.If)(n.isMetallic.and(t.lessThan((0,o.int)(3))),()=>{m.assign((0,o.max)(m,.6)),p.mulAssign(.4)}),(0,o.If)(n.isTransmissive,()=>{h.assign((0,o.max)(h,.8)),p.mulAssign(.2),m.mulAssign(.6)}),(0,o.If)(n.hasClearcoat,()=>{g.assign((0,o.max)(g,.4))});let _=p.add(m).add(h).add(g).toVar();return(0,o.If)(_.greaterThan(.001),()=>{let e=(0,o.float)(1).div(_);p.mulAssign(e),m.mulAssign(e),h.mulAssign(e),g.mulAssign(e)}).Else(()=>{p.assign(1),m.assign(0),h.assign(0),g.assign(0)}),Ot({diffuseImportance:p,specularImportance:m,transmissionImportance:h,clearcoatImportance:g,envmapImportance:(0,o.float)(0)})}),dr=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.max)((0,o.dot)(e,t),.001).toVar(),s=i.isRough.and(i.isMetallic.not()).and(n.transmission.equal(0)).and(n.clearcoat.equal(0)).toVar(),c=i.isMetallic.toVar(),l=i.isTransmissive.or(i.hasClearcoat).or(n.sheen.greaterThan(0)).or(n.iridescence.greaterThan(0)).toVar(),u=r.roughness.mul(r.roughness).toVar(),d=u.mul(u).toVar(),f=r.roughness.add(1),p=f.mul(f).div(8).toVar(),m=(0,o.mix)(Qn(n.ior).mul(n.specularColor),r.albedo.rgb,r.metalness).mul(n.specularIntensity).toVar(),h=r.albedo.rgb.mul((0,o.float)(1).sub(r.metalness)).toVar(),g=r.albedo.rgb.toVar(),_=(0,o.float)(1).sub(r.roughness).toVar(),v=(0,o.float)(.5).add((0,o.float)(.5).mul(r.metalness)).toVar(),y=(0,o.min)((0,o.float)(2).div(n.ior),1).toVar(),b=(0,o.max)(n.sheenColor.r,(0,o.max)(n.sheenColor.g,n.sheenColor.b)).toVar();return Nt({NoV:a,isPurelyDiffuse:s,isMetallic:c,hasSpecialFeatures:l,alpha:u,alpha2:d,k:p,F0:m,diffuseColor:h,specularColor:g,tsAlbedo:r.albedo,tsEmissive:r.emissive,tsMetalness:r.metalness,tsRoughness:r.roughness,tsNormal:r.normal,tsHasTextures:r.hasTextures,invRoughness:_,metalFactor:v,iorFactor:y,maxSheenColor:b})});(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.dot)(e,t),.001).toVar(),i=n.roughness.greaterThan(.98).and(n.metalness.lessThan(.02)).and(n.transmission.equal(0)).and(n.clearcoat.equal(0)).toVar(),a=n.metalness.greaterThan(.7).toVar(),s=n.transmission.greaterThan(0).or(n.clearcoat.greaterThan(0)).or(n.sheen.greaterThan(0)).or(n.iridescence.greaterThan(0)).toVar(),c=n.roughness.mul(n.roughness).toVar(),l=c.mul(c).toVar(),u=n.roughness.add(1),d=u.mul(u).div(8).toVar(),f=(0,o.mix)(Qn(n.ior).mul(n.specularColor),n.color.rgb,n.metalness).mul(n.specularIntensity).toVar(),p=n.color.rgb.mul((0,o.float)(1).sub(n.metalness)).toVar(),m=n.color.rgb.toVar(),h=At({albedo:n.color,emissive:n.emissive.mul(n.emissiveIntensity),metalness:n.metalness,roughness:n.roughness,normal:e,hasTextures:!1}),g=(0,o.float)(1).sub(n.roughness).toVar(),_=(0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness)).toVar(),v=(0,o.min)((0,o.float)(2).div(n.ior),1).toVar(),y=(0,o.max)(n.sheenColor.r,(0,o.max)(n.sheenColor.g,n.sheenColor.b)).toVar();return Nt({NoV:r,isPurelyDiffuse:i,isMetallic:a,hasSpecialFeatures:s,alpha:c,alpha2:l,k:d,F0:f,diffuseColor:p,specularColor:m,tsAlbedo:h.albedo,tsEmissive:h.emissive,tsMetalness:h.metalness,tsRoughness:h.roughness,tsNormal:h.normal,tsHasTextures:h.hasTextures,invRoughness:g,metalFactor:_,iorFactor:v,maxSheenColor:y})});var fr=(0,o.wgslFn)(`
|
|
414
414
|
fn ImportanceSampleGGX( N: vec3f, roughness: f32, Xi: vec2f ) -> vec3f {
|
|
415
415
|
let alpha = roughness * roughness;
|
|
416
416
|
let phi = 6.28318530717958647692f * Xi.x;
|
|
@@ -423,7 +423,7 @@
|
|
|
423
423
|
let bitangent = cross( N, tangent );
|
|
424
424
|
return normalize( tangent * H.x + bitangent * H.y + N * H.z );
|
|
425
425
|
}
|
|
426
|
-
`),
|
|
426
|
+
`),pr=(0,o.wgslFn)(`
|
|
427
427
|
fn ImportanceSampleCosine( N: vec3f, xi: vec2f ) -> vec3f {
|
|
428
428
|
let T = normalize( cross( N, N.yzx + vec3f( 0.1f, 0.2f, 0.3f ) ) );
|
|
429
429
|
let B = cross( N, T );
|
|
@@ -433,7 +433,7 @@
|
|
|
433
433
|
let localDir = vec3f( sinTheta * cos( phi ), sinTheta * sin( phi ), cosTheta );
|
|
434
434
|
return normalize( T * localDir.x + B * localDir.y + N * localDir.z );
|
|
435
435
|
}
|
|
436
|
-
`),
|
|
436
|
+
`),mr=(0,o.wgslFn)(`
|
|
437
437
|
fn cosineWeightedSample( N: vec3f, xi: vec2f ) -> vec3f {
|
|
438
438
|
let T = normalize( cross( N, N.yzx + vec3f( 0.1f, 0.2f, 0.3f ) ) );
|
|
439
439
|
let B = cross( N, T );
|
|
@@ -443,7 +443,7 @@
|
|
|
443
443
|
let localDir = vec3f( sinTheta * cos( phi ), sinTheta * sin( phi ), cosTheta );
|
|
444
444
|
return normalize( T * localDir.x + B * localDir.y + N * localDir.z );
|
|
445
445
|
}
|
|
446
|
-
`);(0,o.Fn)(([e])=>(0,o.max)(e,
|
|
446
|
+
`);(0,o.Fn)(([e])=>(0,o.max)(e,Vt).mul(Lt));var hr=(0,o.wgslFn)(`
|
|
447
447
|
fn sampleGGXVNDF( V: vec3f, roughness: f32, Xi: vec2f ) -> vec3f {
|
|
448
448
|
let alpha = roughness * roughness;
|
|
449
449
|
// Transform view direction to local space
|
|
@@ -464,7 +464,7 @@
|
|
|
464
464
|
// Transform the normal back to the ellipsoid configuration
|
|
465
465
|
return normalize( vec3f( alpha * Nh.x, alpha * Nh.y, max( 0.0f, Nh.z ) ) );
|
|
466
466
|
}
|
|
467
|
-
`),
|
|
467
|
+
`),gr=(0,o.Fn)(([e,t,n])=>{let r=jt.wrap(en(n)),i=(0,o.float)(1).sub(n.roughness),a=(0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness)),s=(0,o.min)((0,o.float)(2).div(n.ior),1),c=(0,o.max)(n.sheenColor.r,(0,o.max)(n.sheenColor.g,n.sheenColor.b)),l=Nt({NoV:(0,o.float)(.5),isPurelyDiffuse:!1,isMetallic:r.isMetallic,hasSpecialFeatures:!1,alpha:n.roughness.mul(n.roughness),alpha2:n.roughness.mul(n.roughness).mul(n.roughness).mul(n.roughness),k:n.roughness.add(1).mul(n.roughness.add(1)).div(8),F0:Qn(n.ior),diffuseColor:n.color.rgb,specularColor:n.color.rgb,tsAlbedo:n.color,tsEmissive:(0,o.vec3)(0),tsMetalness:(0,o.float)(0),tsRoughness:n.roughness,tsNormal:(0,o.vec3)(0,1,0),tsHasTextures:!1,invRoughness:i,metalFactor:a,iorFactor:s,maxSheenColor:c}),u=BRDFWeights.wrap(lr(n,r,l)),d=(0,o.max)((0,o.dot)(t,e),0),f=(0,o.pow)((0,o.float)(1).sub(d),5),p=u.diffuse.mul(f),m=u.diffuse.sub(p).toVar(),h=u.specular.add(p).toVar(),g=u.clearcoat.toVar(),_=u.transmission.mul(s).toVar(),v=u.sheen.toVar(),y=u.iridescence.toVar(),b=(0,o.max)(m.add(h).add(g).add(_).add(v).add(y),1e-6).toVar(),x=(0,o.float)(1).div(b);return It({diffuse:m.mul(x),specular:h.mul(x),clearcoat:g.mul(x),transmission:_.mul(x),sheen:v.mul(x),iridescence:y.mul(x),totalWeight:b})}),_r=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=(0,o.float)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.float)(0).toVar(),d=(0,o.float)(0).toVar(),f=(0,o.dot)(n,e);(0,o.If)(f.greaterThan(0),()=>{s.assign(f.div(q))});let p=(0,o.normalize)(t.add(e)).toVar(),m=(0,o.max)((0,o.dot)(n,p),0),h=(0,o.max)((0,o.dot)(t,p),0),g=(0,o.max)((0,o.dot)(n,t),0);(0,o.If)(m.greaterThan(0).and(h.greaterThan(0)).and(g.greaterThan(0)),()=>{c.assign(ar(m,h,r.roughness)),(0,o.If)(r.clearcoat.greaterThan(0),()=>{l.assign(ar(m,h,r.clearcoatRoughness))})}),(0,o.If)(r.transmission.greaterThan(0).and(f.lessThan(0)),()=>{u.assign((0,o.abs)(f).div(q))}),(0,o.If)(r.sheen.greaterThan(0).and(f.greaterThan(0)),()=>{d.assign(f.div(q))});let _=i.diffuse.mul(s),v=i.specular.mul(c),y=i.clearcoat.mul(l),b=i.transmission.mul(u),x=i.sheen.mul(d),S=i.iridescence.mul(s),C=_.mul(_).add(v.mul(v)).add(y.mul(y)).add(b.mul(b)).add(x.mul(x)).add(S.mul(S)),w=(0,o.float)(1).toVar();return(0,o.If)(C.greaterThan(0).and(a.greaterThan(0)),()=>{let e=a.mul(a);w.assign(e.div(C))}),w});(0,o.Fn)(([e,t,n,r,i,a])=>{let s=gr(e,t,n),c=F(i),l=s.diffuse,u=l.add(s.specular),d=u.add(s.clearcoat),f=d.add(s.transmission),p=(0,o.vec3)(0).toVar(),m=(0,o.float)(0).toVar(),h=(0,o.float)(0).toVar();(0,o.If)(c.lessThan(l),()=>{p.assign(pr({N:t,xi:r})),m.assign((0,o.max)((0,o.dot)(t,p),0).div(q)),h.assign(m.mul(s.diffuse))}).ElseIf(c.lessThan(u),()=>{let i=fr({N:t,roughness:n.roughness,Xi:r}).toVar();p.assign((0,o.reflect)(e.negate(),i)),(0,o.If)((0,o.dot)(t,p).greaterThan(0),()=>{let r=(0,o.max)((0,o.dot)(t,i),0),a=(0,o.max)((0,o.dot)(e,i),0);m.assign(ar(r,a,n.roughness))}),h.assign(m.mul(s.specular))}).ElseIf(c.lessThan(d).and(n.clearcoat.greaterThan(0)),()=>{let i=fr({N:t,roughness:n.clearcoatRoughness,Xi:r}).toVar();p.assign((0,o.reflect)(e.negate(),i)),(0,o.If)((0,o.dot)(t,p).greaterThan(0),()=>{let r=(0,o.max)((0,o.dot)(t,i),0),a=(0,o.max)((0,o.dot)(e,i),0);m.assign(ar(r,a,n.clearcoatRoughness))}),h.assign(m.mul(s.clearcoat))}).ElseIf(c.lessThan(f).and(n.transmission.greaterThan(0)),()=>{let i=fr({N:t,roughness:n.roughness,Xi:r}).toVar(),a=(0,o.refract)(e.negate(),i,(0,o.float)(1).div(n.ior)).toVar();(0,o.If)((0,o.dot)(a,a).greaterThan(.001),()=>{p.assign((0,o.normalize)(a));let r=(0,o.max)((0,o.dot)(t,i),0),s=(0,o.max)((0,o.dot)(e,i),0);m.assign(ar(r,s,n.roughness))}).Else(()=>{p.assign((0,o.reflect)(e.negate(),i)),m.assign(.1)}),h.assign(m.mul(s.transmission))}).Else(()=>{p.assign(pr({N:t,xi:r})),m.assign((0,o.max)((0,o.dot)(t,p),0).div(q)),h.assign(m.mul(s.sheen.add(s.iridescence)))});let g=_r(p,e,t,n,s,h),_=a(e,p,t,n).toVar();return _.mulAssign(g),Et({direction:p,value:_,pdf:h})});var vr=K({direction:`vec3`,throughput:`vec3`,didReflect:`bool`}),yr=K({continueRay:`bool`,isTransmissive:`bool`,isAlphaSkip:`bool`,didReflect:`bool`,entering:`bool`,direction:`vec3`,throughput:`vec3`,alpha:`float`});K({ior:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`});var br=K({wavelength:`float`,ior:`float`,colorWeight:`vec3`}),xr=K({direction:`vec3`,halfVector:`vec3`,didReflect:`bool`,pdf:`float`});K({m0_ior:`float`,m0_attenuationColor:`vec3`,m0_attenuationDistance:`float`,m0_dispersion:`float`,m1_ior:`float`,m1_attenuationColor:`vec3`,m1_attenuationDistance:`float`,m1_dispersion:`float`,m2_ior:`float`,m2_attenuationColor:`vec3`,m2_attenuationDistance:`float`,m2_dispersion:`float`,m3_ior:`float`,m3_attenuationColor:`vec3`,m3_attenuationDistance:`float`,m3_dispersion:`float`,depth:`int`}),(0,o.Fn)(([e])=>{let t=(0,o.float)(1).toVar();return(0,o.If)(e.depth.greaterThan((0,o.int)(0)),()=>{(0,o.If)(e.depth.equal((0,o.int)(1)),()=>{t.assign(e.m1_ior)}),(0,o.If)(e.depth.equal((0,o.int)(2)),()=>{t.assign(e.m2_ior)}),(0,o.If)(e.depth.equal((0,o.int)(3)),()=>{t.assign(e.m3_ior)})}),t});var Sr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.mix)((0,o.float)(380),(0,o.float)(700),n).toVar(),i=r.div(1e3),a=e,s=t.mul(.03),c=a.add(s.div(i.mul(i))).toVar(),l=(0,o.vec3)(0).toVar();return(0,o.If)(r.greaterThanEqual(380).and(r.lessThan(420)),()=>{l.assign((0,o.vec3)(.9,0,1))}),(0,o.If)(r.greaterThanEqual(420).and(r.lessThan(480)),()=>{l.assign((0,o.vec3)(0,0,1))}),(0,o.If)(r.greaterThanEqual(480).and(r.lessThan(500)),()=>{l.assign((0,o.vec3)(0,1,1))}),(0,o.If)(r.greaterThanEqual(500).and(r.lessThan(530)),()=>{l.assign((0,o.vec3)(0,1,0))}),(0,o.If)(r.greaterThanEqual(530).and(r.lessThan(570)),()=>{l.assign((0,o.vec3)(1,1,0))}),(0,o.If)(r.greaterThanEqual(570).and(r.lessThan(620)),()=>{l.assign((0,o.vec3)(1,.5,0))}),(0,o.If)(r.greaterThanEqual(620).and(r.lessThanEqual(700)),()=>{l.assign((0,o.vec3)(1,0,0))}),l.assign((0,o.pow)(l,(0,o.vec3)(.4))),l.assign((0,o.clamp)(l,(0,o.vec3)(0),(0,o.vec3)(2))),br({wavelength:r,ior:c,colorWeight:l})}),Cr=(0,o.wgslFn)(`
|
|
468
468
|
fn calculateBeerLawAbsorption( attenuationColor: vec3f, attenuationDistance: f32, thickness: f32 ) -> vec3f {
|
|
469
469
|
if ( attenuationDistance <= 0.0f ) { return vec3f( 1.0f ); }
|
|
470
470
|
// Convert RGB attenuation color to absorption coefficients
|
|
@@ -472,11 +472,11 @@
|
|
|
472
472
|
// Apply Beer's law
|
|
473
473
|
return exp( -absorption * thickness );
|
|
474
474
|
}
|
|
475
|
-
`),Cr=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.select)(r,(0,o.float)(1),n.ior).toVar(),a=(0,o.select)(r,n.ior,(0,o.float)(1)).toVar(),s=(0,o.abs)((0,o.dot)(t,e)),c=i.mul(i).div(a.mul(a)).mul((0,o.float)(1).sub(s.mul(s))),l=(0,o.float)(0).toVar();return(0,o.If)(c.lessThanEqual(1),()=>{let e=Kn(s,Xn(a,i)),t=(0,o.float)(1).sub(e).mul(n.transmission).toVar();(0,o.If)(r.not().and(n.attenuationDistance.greaterThan(0)),()=>{let e=Sr({attenuationColor:n.attenuationColor,attenuationDistance:n.attenuationDistance,thickness:n.thickness});t.assign(t.mul(e.x.add(e.y).add(e.z).div(3)))}),l.assign((0,o.clamp)(t,0,1))}),l}),wr=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=br({direction:(0,o.vec3)(0),halfVector:(0,o.vec3)(0),didReflect:!1,pdf:(0,o.float)(0)}).toVar();return(0,o.If)(r.lessThanEqual(.05).and(a.greaterThan(0)),()=>{l.halfVector.assign(t),l.didReflect.assign(!1);let r=n,s=(0,o.select)(i,(0,o.float)(1).div(r),r).toVar(),u=yr.wrap(xr(n,a,F(c)));s.assign((0,o.select)(i,(0,o.float)(1).div(u.ior),u.ior));let d=(0,o.refract)(e.negate(),t,s).toVar();(0,o.If)((0,o.dot)(d,d).lessThan(.001),()=>{l.direction.assign((0,o.reflect)(e.negate(),t)),l.didReflect.assign(!0),l.pdf.assign(1)}).Else(()=>{l.direction.assign(d),l.pdf.assign(1)})}).Else(()=>{let u=(0,o.max)(Rt,r),d=dr({N:t,roughness:u,Xi:s}).toVar();l.halfVector.assign(d);let f=(0,o.select)(i,(0,o.float)(1).div(n),n).toVar();(0,o.If)(a.greaterThan(0),()=>{let e=yr.wrap(xr(n,a,F(c)));f.assign((0,o.select)(i,(0,o.float)(1).div(e.ior),e.ior))});let p=(0,o.clamp)((0,o.dot)(d,e),.001,1),m=(0,o.refract)(e.negate(),d,f).toVar();(0,o.If)((0,o.dot)(m,m).lessThan(.001),()=>{l.direction.assign((0,o.reflect)(e.negate(),d)),l.didReflect.assign(!0);let n=(0,o.clamp)((0,o.dot)(t,d),.001,1),r=(0,o.clamp)((0,o.dot)(e,d),.001,1);l.pdf.assign(ir(n,r,u))}).Else(()=>{l.direction.assign(m),l.didReflect.assign(!1);let e=(0,o.clamp)((0,o.dot)(t,d),.001,1),n=(0,o.clamp)((0,o.dot)(d,m),.001,1),r=Qn(e,u),i=p.add(f.mul(n)),a=(0,o.abs)(n).div(i.mul(i));l.pdf.assign(r.mul(e).mul(a))})}),l}),Tr=(0,o.Fn)(([e,t,n,r,i,a,s])=>{let c=_r({direction:(0,o.vec3)(0),throughput:(0,o.vec3)(1),didReflect:!1}).toVar(),l=(0,o.select)(r,t,t.negate()).toVar(),u=e.negate().toVar(),d=(0,o.select)(r,a,n.ior).toVar(),f=(0,o.select)(r,n.ior,s).toVar(),p=(0,o.abs)((0,o.dot)(l,e)),m=d.mul(d).div(f.mul(f)).mul((0,o.float)(1).sub(p.mul(p))).greaterThan(1).toVar(),h=Xn(f,d),g=(0,o.select)(m,(0,o.float)(1),Kn(p,h)).toVar(),_=(0,o.float)(0).toVar();(0,o.If)(m,()=>{_.assign(1)}).Else(()=>{let e=(0,o.mix)(g,(0,o.float)(.95),n.metalness).toVar();_.assign(e)}),_.assign((0,o.clamp)(_,.05,.95));let v=m.or(F(i).lessThan(_)).toVar();c.didReflect.assign(v);let y=(0,o.vec2)(F(i).toVar(),F(i).toVar());return(0,o.If)(v,()=>{(0,o.If)(n.roughness.greaterThan(.05),()=>{let e=br.wrap(wr(u,l,n.ior,n.roughness,r,(0,o.float)(0),y,i));c.direction.assign(e.direction)}).Else(()=>{c.direction.assign((0,o.reflect)(e,l))}),c.throughput.assign(n.color.xyz.mul(g).div((0,o.max)(_,.05)))}).Else(()=>{(0,o.If)(n.roughness.greaterThan(.05).or(n.dispersion.greaterThan(0)),()=>{let t=br.wrap(wr(u,l,n.ior,n.roughness,r,n.dispersion,y,i));(0,o.If)(t.didReflect,()=>{c.direction.assign(t.direction),c.didReflect.assign(!0),c.throughput.assign(n.color.xyz.div((0,o.max)((0,o.float)(1).sub(_),.05)))}).Else(()=>{c.direction.assign(t.direction),(0,o.If)(n.dispersion.greaterThan(0),()=>{let t=(0,o.normalize)(e),r=(0,o.normalize)(c.direction),i=(0,o.float)(1).sub((0,o.abs)((0,o.dot)(l,t))),a=(0,o.acos)((0,o.clamp)((0,o.dot)(t,r),-1,1)),s=(0,o.normalize)(t.add(l)),u=(0,o.sin)(s.x.mul(15)).mul((0,o.cos)(s.y.mul(12))).mul((0,o.sin)(s.z.mul(18))),d=(0,o.sin)(r.x.mul(8).add(r.y.mul(6)).add(r.z.mul(10))),f=a.mul(n.dispersion).mul(3),p=u.mul(.3),m=d.mul(.2),h=i.mul(.4),g=(0,o.fract)(f.add(p).add(m).add(h)).toVar(),_=(0,o.vec3)(0).toVar();(0,o.If)(g.lessThan(.143),()=>{let e=g.div(.143);_.assign((0,o.mix)((0,o.vec3)(.8,0,0),(0,o.vec3)(1,0,0),e))}),(0,o.If)(g.greaterThanEqual(.143).and(g.lessThan(.286)),()=>{let e=g.sub(.143).div(.143);_.assign((0,o.mix)((0,o.vec3)(1,0,0),(0,o.vec3)(1,.6,0),e))}),(0,o.If)(g.greaterThanEqual(.286).and(g.lessThan(.429)),()=>{let e=g.sub(.286).div(.143);_.assign((0,o.mix)((0,o.vec3)(1,.6,0),(0,o.vec3)(1,1,0),e))}),(0,o.If)(g.greaterThanEqual(.429).and(g.lessThan(.571)),()=>{let e=g.sub(.429).div(.142);_.assign((0,o.mix)((0,o.vec3)(1,1,0),(0,o.vec3)(0,1,0),e))}),(0,o.If)(g.greaterThanEqual(.571).and(g.lessThan(.714)),()=>{let e=g.sub(.571).div(.143);_.assign((0,o.mix)((0,o.vec3)(0,1,0),(0,o.vec3)(0,.4,1),e))}),(0,o.If)(g.greaterThanEqual(.714).and(g.lessThan(.857)),()=>{let e=g.sub(.714).div(.143);_.assign((0,o.mix)((0,o.vec3)(0,.4,1),(0,o.vec3)(.3,0,.8),e))}),(0,o.If)(g.greaterThanEqual(.857),()=>{let e=g.sub(.857).div(.143);_.assign((0,o.mix)((0,o.vec3)(.3,0,.8),(0,o.vec3)(.6,0,1),e))});let v=(0,o.clamp)(n.dispersion.div(5),0,1),y=(0,o.float)(1).add(i.mul(1.5)),b=v.mul(y),x=u.add(d),S=(0,o.float)(.5).add((0,o.float)(.5).mul((0,o.sin)(x.mul(3.14159)))),C=(0,o.clamp)(b.mul(S),0,.8);c.throughput.assign((0,o.mix)((0,o.vec3)(1),_,C))}).Else(()=>{c.throughput.assign((0,o.vec3)(1))})})}).Else(()=>{c.direction.assign((0,o.refract)(e,l,d.div(f))),c.throughput.assign((0,o.vec3)(1))}),(0,o.If)(c.didReflect.not(),()=>{c.throughput.mulAssign(n.color.xyz),c.throughput.mulAssign(d.mul(d).div((0,o.max)(f.mul(f),J))),(0,o.If)(r.and(n.attenuationDistance.greaterThan(0)),()=>{c.throughput.mulAssign(Sr({attenuationColor:n.attenuationColor,attenuationDistance:n.attenuationDistance,thickness:n.thickness}))}),c.throughput.mulAssign((0,o.float)(1).sub(g).div((0,o.max)((0,o.float)(1).sub(_),.05)))})}),c}),Er=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=vr({continueRay:!1,isTransmissive:!1,isAlphaSkip:!1,didReflect:!1,entering:!1,direction:e.direction,throughput:(0,o.vec3)(1),alpha:(0,o.float)(1)}).toVar();return(0,o.If)(r.alphaMode.equal((0,o.int)(0)).and(r.transmission.lessThanEqual(0)),()=>{}).Else(()=>{let t=F(i),u=F(i),d=P({state:i}),f=(0,o.bool)(!1).toVar();(0,o.If)(r.alphaMode.equal((0,o.int)(2)),()=>{let n=r.color.a.mul(r.opacity);(0,o.If)(t.greaterThan(n),()=>{l.continueRay.assign(!0),l.direction.assign(e.direction),l.throughput.assign((0,o.vec3)(1)),l.alpha.assign(0),l.isAlphaSkip.assign(!0),f.assign(!0)}).Else(()=>{l.alpha.assign(n)})}),(0,o.If)(f.not().and(r.alphaMode.equal((0,o.int)(1))),()=>{let t=(0,o.select)(r.alphaTest.greaterThan(0),r.alphaTest,(0,o.float)(.5));(0,o.If)(r.color.a.lessThan(t),()=>{l.continueRay.assign(!0),l.direction.assign(e.direction),l.throughput.assign((0,o.vec3)(1)),l.alpha.assign(0),l.isAlphaSkip.assign(!0),f.assign(!0)}).Else(()=>{l.alpha.assign(1)})}),(0,o.If)(f.not().and(r.transmission.greaterThan(0)).and(a.greaterThan((0,o.int)(0))),()=>{(0,o.If)(u.lessThan(r.transmission),()=>{let t=(0,o.dot)(e.direction,n).lessThan(0),i=_r.wrap(Tr(e.direction,n,r,t,d,s,c));l.direction.assign(i.direction),l.throughput.assign(i.throughput),l.continueRay.assign(!0),l.isTransmissive.assign(!0),l.didReflect.assign(i.didReflect),l.entering.assign(t),l.alpha.assign((0,o.float)(1).sub(r.transmission))})})}),l}),Dr=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.vec3)(0).toVar();return(0,o.If)(r.roughness.greaterThan(.98).and(r.metalness.lessThan(.02)).and(r.transmission.equal(0)).and(r.clearcoat.equal(0)).and(r.iridescence.equal(0)),()=>{i.assign(r.color.rgb.mul((0,o.float)(1).sub(r.metalness)).mul(It))}).Else(()=>{let a=Ot.wrap(Yt(n,e,t)),s=(0,o.clamp)((0,o.mix)(Zn(r.ior).mul(r.specularColor),r.color.rgb,r.metalness).mul(r.specularIntensity),(0,o.vec3)(0),(0,o.vec3)(1)).toVar(),c=r.color.rgb.toVar();(0,o.If)(r.dispersion.greaterThan(0).and(r.transmission.greaterThan(.5)),()=>{let e=(0,o.clamp)(r.dispersion.mul(.1),0,.8),t=(0,o.max)((0,o.max)(c.r,c.g),c.b),n=(0,o.min)((0,o.min)(c.r,c.g),c.b);(0,o.If)(t.greaterThan(n),()=>{let r=c.sub(n).div(t.sub(n));c.assign((0,o.mix)(c,r,e.mul(.3)))})}),(0,o.If)(r.iridescence.greaterThan(0),()=>{let e=r.iridescenceThicknessRange.y,t=sr((0,o.float)(1),r.iridescenceIOR,a.VoH,e,s);s.assign((0,o.mix)(s,t,r.iridescence))});let l=Qn(a.NoH,r.roughness),u=tr(a.NoV,a.NoL,r.roughness),d=qn(a.VoH,s).toVar(),f=l.mul(u).mul(d).div((0,o.max)((0,o.float)(4).mul(a.NoV).mul(a.NoL),J)).mul(nr(s,a.NoV,r.roughness)),p=rr(s,a.NoV,r.roughness),m=(0,o.vec3)(1).sub(p).mul((0,o.float)(1).sub(r.metalness)).mul(c).mul(It).add(f).toVar();(0,o.If)(r.sheen.greaterThan(0),()=>{let e=$n(a.NoH,r.sheenRoughness),t=r.sheenColor.mul(r.sheen).mul(e).mul(a.NoL),n=(0,o.float)(1).sub(r.sheenRoughness).mul(.5).add(.25),s=(0,o.clamp)(r.sheenColor.mul(r.sheen).mul(n),(0,o.vec3)(0),(0,o.vec3)(1)),c=(0,o.vec3)(1).sub(s);i.assign(m.mul(c).add(t))}).Else(()=>{i.assign(m)})}),i});(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.vec3)(0).toVar();return(0,o.If)(i.isPurelyDiffuse,()=>{a.assign(i.diffuseColor)}).Else(()=>{let s=e.add(t).toVar(),c=(0,o.dot)(s,s);s.assign(c.greaterThan(J).select(s.div((0,o.sqrt)(c)),(0,o.vec3)(0,0,1)));let l=(0,o.max)((0,o.dot)(n,t),J),u=(0,o.max)((0,o.dot)(n,s),J),d=(0,o.max)((0,o.dot)(e,s),J);(0,o.If)(i.NoV.mul(l).lessThan(0).and(r.transmission.greaterThan(0)),()=>{a.assign(Dr(e,t,n,r))}).Else(()=>{let e=i.F0.toVar();(0,o.If)(r.iridescence.greaterThan(0),()=>{let t=r.iridescenceThicknessRange.y,n=sr((0,o.float)(1),r.iridescenceIOR,d,t,e);e.assign((0,o.clamp)((0,o.mix)(e,n,r.iridescence),(0,o.vec3)(0),(0,o.vec3)(1)))});let t=u.mul(u).mul(i.alpha2.sub(1)).add(1),n=i.alpha2.div((0,o.max)((0,o.float)(q).mul(t).mul(t),J)),s=l.div(l.mul((0,o.float)(1).sub(i.k)).add(i.k)),c=i.NoV.div(i.NoV.mul((0,o.float)(1).sub(i.k)).add(i.k)),f=s.mul(c),p=qn(d,e).toVar(),m=(0,o.max)((0,o.float)(4).mul(i.NoV).mul(l),J),h=n.mul(f).mul(p).div(m).mul(nr(e,i.NoV,r.roughness)),g=rr(e,i.NoV,r.roughness),_=(0,o.vec3)(1).sub(g).mul((0,o.float)(1).sub(r.metalness)).mul(r.color.rgb).mul(It).add(h).toVar();(0,o.If)(r.sheen.greaterThan(0),()=>{let e=$n(u,r.sheenRoughness),t=r.sheenColor.mul(r.sheen).mul(e).mul(l),n=(0,o.float)(1).sub(r.sheenRoughness).mul(.5).add(.25),i=(0,o.clamp)(r.sheenColor.mul(r.sheen).mul(n),(0,o.vec3)(0),(0,o.vec3)(1)),s=(0,o.vec3)(1).sub(i);a.assign(_.mul(s).add(t))}).Else(()=>{a.assign(_)})})}),a}),(0,o.Fn)(([e,t])=>{let n=Kn(t,(0,o.float)(.04));return(0,o.float)(1).sub(e.mul(n).mul((0,o.float)(2).sub(n)))});var Or=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)((0,o.mix)(Zn(t.ior).mul(t.specularColor),t.color.rgb,t.metalness).mul(t.specularIntensity),(0,o.vec3)(0),(0,o.vec3)(1)).toVar(),r=Qn(e.NoH,t.roughness),i=tr(e.NoV,e.NoL,t.roughness),a=qn(e.VoH,n).toVar(),s=r.mul(i).mul(a).div((0,o.max)((0,o.float)(4).mul(e.NoV).mul(e.NoL),J)).mul(nr(n,e.NoV,t.roughness)),c=rr(n,e.NoV,t.roughness),l=(0,o.vec3)(1).sub(c).mul((0,o.float)(1).sub(t.metalness)).mul(t.color.rgb).div(q).add(s),u=(0,o.max)(t.clearcoatRoughness,zt),d=Qn(e.NoH,u),f=tr(e.NoV,e.NoL,u),p=Kn(e.VoH,(0,o.float)(.04)),m=d.mul(f).mul(p).div((0,o.max)((0,o.float)(4).mul(e.NoV).mul(e.NoL),J)),h=(0,o.float)(1).sub(t.clearcoat.mul(p).mul((0,o.float)(2).sub(p)));return l.mul(h).add((0,o.vec3)(m).mul(t.clearcoat))}),kr=K({brdf:`vec3`,L:`vec3`,pdf:`float`}),Ar=(0,o.Fn)(([e,t,n,r,i])=>{let a=t.normal,s=e.direction.negate(),c=(0,o.max)(n.clearcoatRoughness,zt),l=(0,o.max)(n.roughness,zt),u=(0,o.float)(1).sub(l).mul((0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness))).toVar(),d=n.clearcoat.mul((0,o.float)(1).sub(c)).toVar(),f=(0,o.float)(1).sub(u).mul((0,o.float)(1).sub(n.metalness)).toVar(),p=u.add(d).add(f);u.divAssign(p),d.divAssign(p),f.divAssign(p);let m=F(i),h=(0,o.vec3)(0).toVar(),g=(0,o.vec3)(0).toVar();(0,o.If)(m.lessThan(d),()=>{g.assign(dr({N:a,roughness:c,Xi:r})),h.assign((0,o.reflect)(s.negate(),g))}).ElseIf(m.lessThan(d.add(u)),()=>{g.assign(dr({N:a,roughness:l,Xi:r})),h.assign((0,o.reflect)(s.negate(),g))}).Else(()=>{h.assign(fr({N:a,xi:r})),g.assign((0,o.normalize)(s.add(h)))});let _=Ot.wrap(Yt(a,s,h)),v=Qn(_.NoH,c).mul(_.NoH).div((0,o.float)(4).mul(_.VoH)).mul(d),y=Qn(_.NoH,l).mul(_.NoH).div((0,o.float)(4).mul(_.VoH)).mul(u),b=_.NoL.div(q).mul(f),x=(0,o.max)(v.add(y).add(b),.001);return kr({brdf:Or(_,n),L:h,pdf:x})}),jr=K({direction:`vec3`,color:`vec3`,intensity:`float`,angle:`float`}),Mr=K({position:`vec3`,u:`vec3`,v:`vec3`,color:`vec3`,intensity:`float`,normal:`vec3`,area:`float`}),Nr=K({position:`vec3`,color:`vec3`,intensity:`float`,distance:`float`,decay:`float`}),Pr=K({position:`vec3`,direction:`vec3`,color:`vec3`,intensity:`float`,angle:`float`,penumbra:`float`,distance:`float`,decay:`float`}),Fr=K({direction:`vec3`,emission:`vec3`,pdf:`float`,distance:`float`,lightType:`int`,valid:`bool`}),Ir=K({direction:`vec3`,throughput:`vec3`,misWeight:`float`,pdf:`float`,combinedPdf:`float`}),Lr=(0,o.Fn)(([e,t])=>{let n=t.mul(8);return jr({direction:(0,o.normalize)((0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2)))),color:(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))),intensity:e.element(n.add(6)),angle:e.element(n.add(7))})}),Rr=(0,o.Fn)(([e,t])=>{let n=t.mul(13),r=(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))).toVar(),i=(0,o.vec3)(e.element(n.add(6)),e.element(n.add(7)),e.element(n.add(8))).toVar(),a=(0,o.cross)(r,i);return Mr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),u:r,v:i,color:(0,o.vec3)(e.element(n.add(9)),e.element(n.add(10)),e.element(n.add(11))),intensity:e.element(n.add(12)),normal:(0,o.normalize)(a),area:(0,o.length)(a).mul(4)})}),zr=(0,o.Fn)(([e,t])=>{let n=t.mul(9);return Nr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),color:(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))),intensity:e.element(n.add(6)),distance:e.element(n.add(7)),decay:e.element(n.add(8))})}),Br=(0,o.Fn)(([e,t])=>{let n=t.mul(14);return Pr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),direction:(0,o.normalize)((0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5)))),color:(0,o.vec3)(e.element(n.add(6)),e.element(n.add(7)),e.element(n.add(8))),intensity:e.element(n.add(9)),angle:e.element(n.add(10)),penumbra:e.element(n.add(11)),distance:e.element(n.add(12)),decay:e.element(n.add(13))})}),Vr=(0,o.wgslFn)(`
|
|
475
|
+
`),wr=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.select)(r,(0,o.float)(1),n.ior).toVar(),a=(0,o.select)(r,n.ior,(0,o.float)(1)).toVar(),s=(0,o.abs)((0,o.dot)(t,e)),c=i.mul(i).div(a.mul(a)).mul((0,o.float)(1).sub(s.mul(s))),l=(0,o.float)(0).toVar();return(0,o.If)(c.lessThanEqual(1),()=>{let e=qn(s,Zn(a,i)),t=(0,o.float)(1).sub(e).mul(n.transmission).toVar();(0,o.If)(r.not().and(n.attenuationDistance.greaterThan(0)),()=>{let e=Cr({attenuationColor:n.attenuationColor,attenuationDistance:n.attenuationDistance,thickness:n.thickness});t.assign(t.mul(e.x.add(e.y).add(e.z).div(3)))}),l.assign((0,o.clamp)(t,0,1))}),l}),Tr=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=xr({direction:(0,o.vec3)(0),halfVector:(0,o.vec3)(0),didReflect:!1,pdf:(0,o.float)(0)}).toVar();return(0,o.If)(r.lessThanEqual(.05).and(a.greaterThan(0)),()=>{l.halfVector.assign(t),l.didReflect.assign(!1);let r=n,s=(0,o.select)(i,(0,o.float)(1).div(r),r).toVar(),u=br.wrap(Sr(n,a,F(c)));s.assign((0,o.select)(i,(0,o.float)(1).div(u.ior),u.ior));let d=(0,o.refract)(e.negate(),t,s).toVar();(0,o.If)((0,o.dot)(d,d).lessThan(.001),()=>{l.direction.assign((0,o.reflect)(e.negate(),t)),l.didReflect.assign(!0),l.pdf.assign(1)}).Else(()=>{l.direction.assign(d),l.pdf.assign(1)})}).Else(()=>{let u=(0,o.max)(zt,r),d=fr({N:t,roughness:u,Xi:s}).toVar();l.halfVector.assign(d);let f=(0,o.select)(i,(0,o.float)(1).div(n),n).toVar();(0,o.If)(a.greaterThan(0),()=>{let e=br.wrap(Sr(n,a,F(c)));f.assign((0,o.select)(i,(0,o.float)(1).div(e.ior),e.ior))});let p=(0,o.clamp)((0,o.dot)(d,e),.001,1),m=(0,o.refract)(e.negate(),d,f).toVar();(0,o.If)((0,o.dot)(m,m).lessThan(.001),()=>{l.direction.assign((0,o.reflect)(e.negate(),d)),l.didReflect.assign(!0);let n=(0,o.clamp)((0,o.dot)(t,d),.001,1),r=(0,o.clamp)((0,o.dot)(e,d),.001,1);l.pdf.assign(ar(n,r,u))}).Else(()=>{l.direction.assign(m),l.didReflect.assign(!1);let e=(0,o.clamp)((0,o.dot)(t,d),.001,1),n=(0,o.clamp)((0,o.dot)(d,m),.001,1),r=$n(e,u),i=p.add(f.mul(n)),a=(0,o.abs)(n).div(i.mul(i));l.pdf.assign(r.mul(e).mul(a))})}),l}),Er=(0,o.Fn)(([e,t,n,r,i,a,s])=>{let c=vr({direction:(0,o.vec3)(0),throughput:(0,o.vec3)(1),didReflect:!1}).toVar(),l=(0,o.select)(r,t,t.negate()).toVar(),u=e.negate().toVar(),d=(0,o.select)(r,a,n.ior).toVar(),f=(0,o.select)(r,n.ior,s).toVar(),p=(0,o.abs)((0,o.dot)(l,e)),m=d.mul(d).div(f.mul(f)).mul((0,o.float)(1).sub(p.mul(p))).greaterThan(1).toVar(),h=Zn(f,d),g=(0,o.select)(m,(0,o.float)(1),qn(p,h)).toVar(),_=(0,o.float)(0).toVar();(0,o.If)(m,()=>{_.assign(1)}).Else(()=>{let e=(0,o.mix)(g,(0,o.float)(.95),n.metalness).toVar();_.assign(e)}),_.assign((0,o.clamp)(_,.05,.95));let v=m.or(F(i).lessThan(_)).toVar();c.didReflect.assign(v);let y=(0,o.vec2)(F(i).toVar(),F(i).toVar());return(0,o.If)(v,()=>{(0,o.If)(n.roughness.greaterThan(.05),()=>{let e=xr.wrap(Tr(u,l,n.ior,n.roughness,r,(0,o.float)(0),y,i));c.direction.assign(e.direction)}).Else(()=>{c.direction.assign((0,o.reflect)(e,l))}),c.throughput.assign(n.color.xyz.mul(g).div((0,o.max)(_,.05)))}).Else(()=>{(0,o.If)(n.roughness.greaterThan(.05).or(n.dispersion.greaterThan(0)),()=>{let t=xr.wrap(Tr(u,l,n.ior,n.roughness,r,n.dispersion,y,i));(0,o.If)(t.didReflect,()=>{c.direction.assign(t.direction),c.didReflect.assign(!0),c.throughput.assign(n.color.xyz.div((0,o.max)((0,o.float)(1).sub(_),.05)))}).Else(()=>{c.direction.assign(t.direction),(0,o.If)(n.dispersion.greaterThan(0),()=>{let t=(0,o.normalize)(e),r=(0,o.normalize)(c.direction),i=(0,o.float)(1).sub((0,o.abs)((0,o.dot)(l,t))),a=(0,o.acos)((0,o.clamp)((0,o.dot)(t,r),-1,1)),s=(0,o.normalize)(t.add(l)),u=(0,o.sin)(s.x.mul(15)).mul((0,o.cos)(s.y.mul(12))).mul((0,o.sin)(s.z.mul(18))),d=(0,o.sin)(r.x.mul(8).add(r.y.mul(6)).add(r.z.mul(10))),f=a.mul(n.dispersion).mul(3),p=u.mul(.3),m=d.mul(.2),h=i.mul(.4),g=(0,o.fract)(f.add(p).add(m).add(h)).toVar(),_=(0,o.vec3)(0).toVar();(0,o.If)(g.lessThan(.143),()=>{let e=g.div(.143);_.assign((0,o.mix)((0,o.vec3)(.8,0,0),(0,o.vec3)(1,0,0),e))}),(0,o.If)(g.greaterThanEqual(.143).and(g.lessThan(.286)),()=>{let e=g.sub(.143).div(.143);_.assign((0,o.mix)((0,o.vec3)(1,0,0),(0,o.vec3)(1,.6,0),e))}),(0,o.If)(g.greaterThanEqual(.286).and(g.lessThan(.429)),()=>{let e=g.sub(.286).div(.143);_.assign((0,o.mix)((0,o.vec3)(1,.6,0),(0,o.vec3)(1,1,0),e))}),(0,o.If)(g.greaterThanEqual(.429).and(g.lessThan(.571)),()=>{let e=g.sub(.429).div(.142);_.assign((0,o.mix)((0,o.vec3)(1,1,0),(0,o.vec3)(0,1,0),e))}),(0,o.If)(g.greaterThanEqual(.571).and(g.lessThan(.714)),()=>{let e=g.sub(.571).div(.143);_.assign((0,o.mix)((0,o.vec3)(0,1,0),(0,o.vec3)(0,.4,1),e))}),(0,o.If)(g.greaterThanEqual(.714).and(g.lessThan(.857)),()=>{let e=g.sub(.714).div(.143);_.assign((0,o.mix)((0,o.vec3)(0,.4,1),(0,o.vec3)(.3,0,.8),e))}),(0,o.If)(g.greaterThanEqual(.857),()=>{let e=g.sub(.857).div(.143);_.assign((0,o.mix)((0,o.vec3)(.3,0,.8),(0,o.vec3)(.6,0,1),e))});let v=(0,o.clamp)(n.dispersion.div(5),0,1),y=(0,o.float)(1).add(i.mul(1.5)),b=v.mul(y),x=u.add(d),S=(0,o.float)(.5).add((0,o.float)(.5).mul((0,o.sin)(x.mul(3.14159)))),C=(0,o.clamp)(b.mul(S),0,.8);c.throughput.assign((0,o.mix)((0,o.vec3)(1),_,C))}).Else(()=>{c.throughput.assign((0,o.vec3)(1))})})}).Else(()=>{c.direction.assign((0,o.refract)(e,l,d.div(f))),c.throughput.assign((0,o.vec3)(1))}),(0,o.If)(c.didReflect.not(),()=>{c.throughput.mulAssign(n.color.xyz),c.throughput.mulAssign(d.mul(d).div((0,o.max)(f.mul(f),J))),(0,o.If)(r.and(n.attenuationDistance.greaterThan(0)),()=>{c.throughput.mulAssign(Cr({attenuationColor:n.attenuationColor,attenuationDistance:n.attenuationDistance,thickness:n.thickness}))}),c.throughput.mulAssign((0,o.float)(1).sub(g).div((0,o.max)((0,o.float)(1).sub(_),.05)))})}),c}),Dr=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=yr({continueRay:!1,isTransmissive:!1,isAlphaSkip:!1,didReflect:!1,entering:!1,direction:e.direction,throughput:(0,o.vec3)(1),alpha:(0,o.float)(1)}).toVar();return(0,o.If)(r.alphaMode.equal((0,o.int)(0)).and(r.transmission.lessThanEqual(0)),()=>{}).Else(()=>{let t=F(i),u=F(i),d=P({state:i}),f=(0,o.bool)(!1).toVar();(0,o.If)(r.alphaMode.equal((0,o.int)(2)),()=>{let n=r.color.a.mul(r.opacity);(0,o.If)(t.greaterThan(n),()=>{l.continueRay.assign(!0),l.direction.assign(e.direction),l.throughput.assign((0,o.vec3)(1)),l.alpha.assign(0),l.isAlphaSkip.assign(!0),f.assign(!0)}).Else(()=>{l.alpha.assign(n)})}),(0,o.If)(f.not().and(r.alphaMode.equal((0,o.int)(1))),()=>{let t=(0,o.select)(r.alphaTest.greaterThan(0),r.alphaTest,(0,o.float)(.5));(0,o.If)(r.color.a.lessThan(t),()=>{l.continueRay.assign(!0),l.direction.assign(e.direction),l.throughput.assign((0,o.vec3)(1)),l.alpha.assign(0),l.isAlphaSkip.assign(!0),f.assign(!0)}).Else(()=>{l.alpha.assign(1)})}),(0,o.If)(f.not().and(r.transmission.greaterThan(0)).and(a.greaterThan((0,o.int)(0))),()=>{(0,o.If)(u.lessThan(r.transmission),()=>{let t=(0,o.dot)(e.direction,n).lessThan(0),i=vr.wrap(Er(e.direction,n,r,t,d,s,c));l.direction.assign(i.direction),l.throughput.assign(i.throughput),l.continueRay.assign(!0),l.isTransmissive.assign(!0),l.didReflect.assign(i.didReflect),l.entering.assign(t),l.alpha.assign((0,o.float)(1).sub(r.transmission))})})}),l}),Or=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.vec3)(0).toVar();return(0,o.If)(r.roughness.greaterThan(.98).and(r.metalness.lessThan(.02)).and(r.transmission.equal(0)).and(r.clearcoat.equal(0)).and(r.iridescence.equal(0)),()=>{i.assign(r.color.rgb.mul((0,o.float)(1).sub(r.metalness)).mul(Lt))}).Else(()=>{let a=kt.wrap(Xt(n,e,t)),s=(0,o.clamp)((0,o.mix)(Qn(r.ior).mul(r.specularColor),r.color.rgb,r.metalness).mul(r.specularIntensity),(0,o.vec3)(0),(0,o.vec3)(1)).toVar(),c=r.color.rgb.toVar();(0,o.If)(r.dispersion.greaterThan(0).and(r.transmission.greaterThan(.5)),()=>{let e=(0,o.clamp)(r.dispersion.mul(.1),0,.8),t=(0,o.max)((0,o.max)(c.r,c.g),c.b),n=(0,o.min)((0,o.min)(c.r,c.g),c.b);(0,o.If)(t.greaterThan(n),()=>{let r=c.sub(n).div(t.sub(n));c.assign((0,o.mix)(c,r,e.mul(.3)))})}),(0,o.If)(r.iridescence.greaterThan(0),()=>{let e=r.iridescenceThicknessRange.y,t=cr((0,o.float)(1),r.iridescenceIOR,a.VoH,e,s);s.assign((0,o.mix)(s,t,r.iridescence))});let l=$n(a.NoH,r.roughness),u=nr(a.NoV,a.NoL,r.roughness),d=Jn(a.VoH,s).toVar(),f=l.mul(u).mul(d).div((0,o.max)((0,o.float)(4).mul(a.NoV).mul(a.NoL),J)).mul(rr(s,a.NoV,r.roughness)),p=ir(s,a.NoV,r.roughness),m=(0,o.vec3)(1).sub(p).mul((0,o.float)(1).sub(r.metalness)).mul(c).mul(Lt).add(f).toVar();(0,o.If)(r.sheen.greaterThan(0),()=>{let e=er(a.NoH,r.sheenRoughness),t=r.sheenColor.mul(r.sheen).mul(e).mul(a.NoL),n=(0,o.float)(1).sub(r.sheenRoughness).mul(.5).add(.25),s=(0,o.clamp)(r.sheenColor.mul(r.sheen).mul(n),(0,o.vec3)(0),(0,o.vec3)(1)),c=(0,o.vec3)(1).sub(s);i.assign(m.mul(c).add(t))}).Else(()=>{i.assign(m)})}),i});(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.vec3)(0).toVar();return(0,o.If)(i.isPurelyDiffuse,()=>{a.assign(i.diffuseColor)}).Else(()=>{let s=e.add(t).toVar(),c=(0,o.dot)(s,s);s.assign(c.greaterThan(J).select(s.div((0,o.sqrt)(c)),(0,o.vec3)(0,0,1)));let l=(0,o.max)((0,o.dot)(n,t),J),u=(0,o.max)((0,o.dot)(n,s),J),d=(0,o.max)((0,o.dot)(e,s),J);(0,o.If)(i.NoV.mul(l).lessThan(0).and(r.transmission.greaterThan(0)),()=>{a.assign(Or(e,t,n,r))}).Else(()=>{let e=i.F0.toVar();(0,o.If)(r.iridescence.greaterThan(0),()=>{let t=r.iridescenceThicknessRange.y,n=cr((0,o.float)(1),r.iridescenceIOR,d,t,e);e.assign((0,o.clamp)((0,o.mix)(e,n,r.iridescence),(0,o.vec3)(0),(0,o.vec3)(1)))});let t=u.mul(u).mul(i.alpha2.sub(1)).add(1),n=i.alpha2.div((0,o.max)((0,o.float)(q).mul(t).mul(t),J)),s=l.div(l.mul((0,o.float)(1).sub(i.k)).add(i.k)),c=i.NoV.div(i.NoV.mul((0,o.float)(1).sub(i.k)).add(i.k)),f=s.mul(c),p=Jn(d,e).toVar(),m=(0,o.max)((0,o.float)(4).mul(i.NoV).mul(l),J),h=n.mul(f).mul(p).div(m).mul(rr(e,i.NoV,r.roughness)),g=ir(e,i.NoV,r.roughness),_=(0,o.vec3)(1).sub(g).mul((0,o.float)(1).sub(r.metalness)).mul(r.color.rgb).mul(Lt).add(h).toVar();(0,o.If)(r.sheen.greaterThan(0),()=>{let e=er(u,r.sheenRoughness),t=r.sheenColor.mul(r.sheen).mul(e).mul(l),n=(0,o.float)(1).sub(r.sheenRoughness).mul(.5).add(.25),i=(0,o.clamp)(r.sheenColor.mul(r.sheen).mul(n),(0,o.vec3)(0),(0,o.vec3)(1)),s=(0,o.vec3)(1).sub(i);a.assign(_.mul(s).add(t))}).Else(()=>{a.assign(_)})})}),a}),(0,o.Fn)(([e,t])=>{let n=qn(t,(0,o.float)(.04));return(0,o.float)(1).sub(e.mul(n).mul((0,o.float)(2).sub(n)))});var kr=(0,o.Fn)(([e,t])=>{let n=(0,o.clamp)((0,o.mix)(Qn(t.ior).mul(t.specularColor),t.color.rgb,t.metalness).mul(t.specularIntensity),(0,o.vec3)(0),(0,o.vec3)(1)).toVar(),r=$n(e.NoH,t.roughness),i=nr(e.NoV,e.NoL,t.roughness),a=Jn(e.VoH,n).toVar(),s=r.mul(i).mul(a).div((0,o.max)((0,o.float)(4).mul(e.NoV).mul(e.NoL),J)).mul(rr(n,e.NoV,t.roughness)),c=ir(n,e.NoV,t.roughness),l=(0,o.vec3)(1).sub(c).mul((0,o.float)(1).sub(t.metalness)).mul(t.color.rgb).div(q).add(s),u=(0,o.max)(t.clearcoatRoughness,Bt),d=$n(e.NoH,u),f=nr(e.NoV,e.NoL,u),p=qn(e.VoH,(0,o.float)(.04)),m=d.mul(f).mul(p).div((0,o.max)((0,o.float)(4).mul(e.NoV).mul(e.NoL),J)),h=(0,o.float)(1).sub(t.clearcoat.mul(p).mul((0,o.float)(2).sub(p)));return l.mul(h).add((0,o.vec3)(m).mul(t.clearcoat))}),Ar=K({brdf:`vec3`,L:`vec3`,pdf:`float`}),jr=(0,o.Fn)(([e,t,n,r,i])=>{let a=t.normal,s=e.direction.negate(),c=(0,o.max)(n.clearcoatRoughness,Bt),l=(0,o.max)(n.roughness,Bt),u=(0,o.float)(1).sub(l).mul((0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness))).toVar(),d=n.clearcoat.mul((0,o.float)(1).sub(c)).toVar(),f=(0,o.float)(1).sub(u).mul((0,o.float)(1).sub(n.metalness)).toVar(),p=u.add(d).add(f);u.divAssign(p),d.divAssign(p),f.divAssign(p);let m=F(i),h=(0,o.vec3)(0).toVar(),g=(0,o.vec3)(0).toVar();(0,o.If)(m.lessThan(d),()=>{g.assign(fr({N:a,roughness:c,Xi:r})),h.assign((0,o.reflect)(s.negate(),g))}).ElseIf(m.lessThan(d.add(u)),()=>{g.assign(fr({N:a,roughness:l,Xi:r})),h.assign((0,o.reflect)(s.negate(),g))}).Else(()=>{h.assign(pr({N:a,xi:r})),g.assign((0,o.normalize)(s.add(h)))});let _=kt.wrap(Xt(a,s,h)),v=$n(_.NoH,c).mul(_.NoH).div((0,o.float)(4).mul(_.VoH)).mul(d),y=$n(_.NoH,l).mul(_.NoH).div((0,o.float)(4).mul(_.VoH)).mul(u),b=_.NoL.div(q).mul(f),x=(0,o.max)(v.add(y).add(b),.001);return Ar({brdf:kr(_,n),L:h,pdf:x})}),Mr=K({direction:`vec3`,color:`vec3`,intensity:`float`,angle:`float`}),Nr=K({position:`vec3`,u:`vec3`,v:`vec3`,color:`vec3`,intensity:`float`,normal:`vec3`,area:`float`}),Pr=K({position:`vec3`,color:`vec3`,intensity:`float`,distance:`float`,decay:`float`}),Fr=K({position:`vec3`,direction:`vec3`,color:`vec3`,intensity:`float`,angle:`float`,penumbra:`float`,distance:`float`,decay:`float`}),Ir=K({direction:`vec3`,emission:`vec3`,pdf:`float`,distance:`float`,lightType:`int`,valid:`bool`}),Lr=K({direction:`vec3`,throughput:`vec3`,misWeight:`float`,pdf:`float`,combinedPdf:`float`}),Rr=(0,o.Fn)(([e,t])=>{let n=t.mul(8);return Mr({direction:(0,o.normalize)((0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2)))),color:(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))),intensity:e.element(n.add(6)),angle:e.element(n.add(7))})}),zr=(0,o.Fn)(([e,t])=>{let n=t.mul(13),r=(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))).toVar(),i=(0,o.vec3)(e.element(n.add(6)),e.element(n.add(7)),e.element(n.add(8))).toVar(),a=(0,o.cross)(r,i);return Nr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),u:r,v:i,color:(0,o.vec3)(e.element(n.add(9)),e.element(n.add(10)),e.element(n.add(11))),intensity:e.element(n.add(12)),normal:(0,o.normalize)(a),area:(0,o.length)(a).mul(4)})}),Br=(0,o.Fn)(([e,t])=>{let n=t.mul(9);return Pr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),color:(0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5))),intensity:e.element(n.add(6)),distance:e.element(n.add(7)),decay:e.element(n.add(8))})}),Vr=(0,o.Fn)(([e,t])=>{let n=t.mul(14);return Fr({position:(0,o.vec3)(e.element(n),e.element(n.add(1)),e.element(n.add(2))),direction:(0,o.normalize)((0,o.vec3)(e.element(n.add(3)),e.element(n.add(4)),e.element(n.add(5)))),color:(0,o.vec3)(e.element(n.add(6)),e.element(n.add(7)),e.element(n.add(8))),intensity:e.element(n.add(9)),angle:e.element(n.add(10)),penumbra:e.element(n.add(11)),distance:e.element(n.add(12)),decay:e.element(n.add(13))})}),Hr=(0,o.wgslFn)(`
|
|
476
476
|
fn isDirectionValid( direction: vec3f, surfaceNormal: vec3f ) -> bool {
|
|
477
477
|
return dot( direction, surfaceNormal ) > 0.0f;
|
|
478
478
|
}
|
|
479
|
-
`),
|
|
479
|
+
`),Ur=(0,o.wgslFn)(`
|
|
480
480
|
fn getDistanceAttenuation( lightDistance: f32, cutoffDistance: f32, decayExponent: f32 ) -> f32 {
|
|
481
481
|
var distanceFalloff = 1.0f / max( pow( lightDistance, decayExponent ), 0.01f );
|
|
482
482
|
if ( cutoffDistance > 0.0f ) {
|
|
@@ -485,11 +485,11 @@
|
|
|
485
485
|
}
|
|
486
486
|
return distanceFalloff;
|
|
487
487
|
}
|
|
488
|
-
`),
|
|
488
|
+
`),Wr=(0,o.wgslFn)(`
|
|
489
489
|
fn getSpotAttenuation( coneCosine: f32, penumbraCosine: f32, angleCosine: f32 ) -> f32 {
|
|
490
490
|
return smoothstep( coneCosine, penumbraCosine, angleCosine );
|
|
491
491
|
}
|
|
492
|
-
`),
|
|
492
|
+
`),Gr=(0,o.wgslFn)(`
|
|
493
493
|
fn sampleCone( direction: vec3f, halfAngle: f32, xi: vec2f ) -> vec3f {
|
|
494
494
|
let cosHalfAngle = cos( halfAngle );
|
|
495
495
|
let cosTheta = cosHalfAngle + xi.x * ( 1.0f - cosHalfAngle );
|
|
@@ -503,32 +503,32 @@
|
|
|
503
503
|
let localDir = vec3f( sinTheta * cos( phi ), sinTheta * sin( phi ), cosTheta );
|
|
504
504
|
return normalize( tangent * localDir.x + bitangent * localDir.y + direction * localDir.z );
|
|
505
505
|
}
|
|
506
|
-
`),Gr=(0,o.Fn)(([e,t,n])=>{let r=e.normal,i=(0,o.dot)(r,n),a=(0,o.float)(-1).toVar();return(0,o.If)(i.lessThan(-1e-4),()=>{let s=(0,o.float)(1).div(i),c=(0,o.dot)(e.position.sub(t),r).mul(s).toVar();(0,o.If)(c.greaterThan(.001),()=>{let r=t.add(n.mul(c)).sub(e.position),i=(0,o.length)(e.u),s=(0,o.length)(e.v),l=e.u.div(i),u=e.v.div(s),d=(0,o.dot)(r,l),f=(0,o.dot)(r,u);(0,o.If)((0,o.abs)(d).lessThanEqual(i).and((0,o.abs)(f).lessThanEqual(s)),()=>{a.assign(c)})})}),a}),Kr=null,qr=null;function Jr(e){Kr=e}function Yr(e){qr=e}(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).toVar();return(0,o.If)(e.material.transmission.greaterThan(0),()=>{let n=(0,o.dot)(t,e.normal).lessThan(0),i=Cr(t,e.normal,e.material,n);r.assign((0,o.float)(1).sub(i))}).ElseIf(e.material.transparent,()=>{r.assign(e.material.opacity)}),r});var Xr=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=(0,o.float)(1).toVar(),u=e.toVar(),d=(0,o.float)(n).toVar();return(0,o.Loop)({start:(0,o.int)(0),end:(0,o.int)(8)},()=>{let e=xt({origin:u,direction:t}),n=wt.wrap(i(e,a,s,c,d));(0,o.If)(n.didHit.not(),()=>{(0,o.Break)()});let r=Ct.wrap(rn(n.materialIndex,c)),f=(0,o.bool)(!1).toVar();qr&&(0,o.If)(qr.equal((0,o.int)(1)),()=>{let e=(0,o.float)(1).toVar();Kr&&(0,o.If)(r.albedoMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let t=n.uv.x,i=n.uv.y,a=(0,o.float)(1).sub(t).sub(i),c=(0,o.int)(8),l=Z(s,n.triangleIndex,(0,o.int)(6),c),u=Z(s,n.triangleIndex,(0,o.int)(7),c),d=Dn({uv:l.xy.mul(a).add(l.zw.mul(t)).add(u.xy.mul(i)),transform:r.albedoTransform});e.assign((0,o.texture)(Kr,d).depth((0,o.int)(r.albedoMapIndex)).a)}),(0,o.If)(r.alphaMode.equal((0,o.int)(1)),()=>{let t=r.color.a.mul(e),n=(0,o.select)(r.alphaTest.greaterThan(0),r.alphaTest,(0,o.float)(.5));(0,o.If)(t.lessThan(n),()=>{f.assign(!0)})}).ElseIf(r.alphaMode.equal((0,o.int)(2)),()=>{let t=(0,o.clamp)(r.color.a.mul(r.opacity).mul(e),0,1);l.mulAssign((0,o.float)(1).sub(t)),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),f.assign(!0)})}),(0,o.If)(f,()=>{let e=(0,o.max)((0,o.float)(1e-5),(0,o.length)(n.hitPoint).mul(1e-6));u.assign(n.hitPoint.add(t.mul(e))),d.subAssign(n.dst.add(e))}).ElseIf(r.transmission.greaterThan(0),()=>{let e=(0,o.dot)(t,n.normal).lessThan(0),i=(0,o.select)(e,n.normal,n.normal.negate());(0,o.If)(e.not().and(r.attenuationDistance.greaterThan(0)),()=>{let e=(0,o.length)(n.hitPoint.sub(u)),t=Sr(r.attenuationColor,r.attenuationDistance,e);l.mulAssign(t.x.add(t.y).add(t.z).div(3))});let a=Kn((0,o.abs)((0,o.dot)(t,i)),Xn(r.ior,(0,o.float)(1))),s=(0,o.float)(1).sub(a).mul(r.transmission);l.mulAssign(s),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),u.assign(n.hitPoint.add(t.mul(.001))),d.subAssign(n.dst.add(.001))}).ElseIf(r.transparent,()=>{l.mulAssign((0,o.float)(1).sub(r.opacity)),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),u.assign(n.hitPoint.add(t.mul(.001))),d.subAssign(n.dst.add(.001))}).Else(()=>{l.assign(0),(0,o.Break)()})}),l}),Zr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.float)(1e-4),(0,o.length)(e).mul(1e-6)).toVar().toVar();return(0,o.If)(n.transmission.greaterThan(0),()=>{r.mulAssign(2)}),(0,o.If)(n.roughness.lessThan(.1),()=>{r.mulAssign(1.5)}),t.mul(r)}),Qr=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.max)((0,o.float)(0),(0,o.dot)(n,e.direction)),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThan(0),()=>{let t=e.intensity.mul((0,o.dot)(e.color,Vt)),n=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{n.assign(1.5)}).ElseIf(r.roughness.greaterThan(.8),()=>{n.assign(.7)});let c=(0,o.float)(1).div((0,o.float)(1).add((0,o.float)(i).mul(.5)));s.assign(t.mul(a).mul(n).mul(c))}),s}),$r=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.length)(i),s=a.mul(a),c=i.div(a),l=(0,o.max)((0,o.dot)(n,c),0),u=(0,o.float)(0).toVar();return(0,o.If)(l.greaterThan(0),()=>{let t=(0,o.max)((0,o.dot)(c,e.normal).negate(),0);(0,o.If)(t.greaterThan(0),()=>{let n=e.area.div((0,o.max)(s,.1)),i=e.intensity.mul((0,o.dot)(e.color,Vt)).mul(e.area),a=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{a.mulAssign(1.5),(0,o.If)(r.roughness.lessThan(.3),()=>{a.mulAssign((0,o.float)(1).add((0,o.float)(1).sub(r.roughness).mul(.5)))})}),(0,o.If)(r.roughness.greaterThan(.6).and(r.metalness.lessThan(.3)),()=>{let t=(0,o.min)(e.area.mul(2),(0,o.float)(2));a.mulAssign(t)}),(0,o.If)(r.transmission.greaterThan(.5),()=>{a.mulAssign((0,o.float)(1).add(r.transmission.mul(.3)))}),u.assign(i.mul(n).mul(l).mul(t).mul(a))})}),u}),ei=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.dot)(i,i),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThanEqual(.001),()=>{let t=(0,o.sqrt)(a),c=i.div(t),l=(0,o.max)((0,o.float)(0),(0,o.dot)(n,c));(0,o.If)(l.greaterThan(0),()=>{let t=(0,o.float)(1).div((0,o.max)(a,.1)),n=e.intensity.mul((0,o.dot)(e.color,Vt)),i=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{i.mulAssign(1.5),(0,o.If)(r.roughness.lessThan(.3),()=>{i.mulAssign((0,o.float)(1).add((0,o.float)(1).sub(r.roughness).mul(.4)))})}),(0,o.If)(r.roughness.greaterThan(.6),()=>{i.mulAssign(.9)}),(0,o.If)(r.transmission.greaterThan(.5),()=>{i.mulAssign((0,o.float)(1).add(r.transmission.mul(.2)))}),s.assign(n.mul(t).mul(l).mul(i))})}),s}),ti=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.dot)(i,i),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThanEqual(.001),()=>{let t=i.div((0,o.sqrt)(a)),c=(0,o.max)((0,o.float)(0),(0,o.dot)(n,t));(0,o.If)(c.greaterThan(0),()=>{let n=(0,o.dot)(t.negate(),e.direction),i=(0,o.cos)(e.angle);(0,o.If)(n.greaterThanEqual(i),()=>{let t=(0,o.float)(1).div((0,o.max)(a,.01)),l=(0,o.smoothstep)(i,i.add(.1),n),u=e.intensity.mul((0,o.dot)(e.color,Vt)),d=(0,o.select)(r.metalness.greaterThan(.7),(0,o.float)(1.5),(0,o.select)(r.roughness.greaterThan(.8),(0,o.float)(.8),(0,o.float)(1)));s.assign(u.mul(t).mul(l).mul(c).mul(d))})})}),s}),ni=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(t,e.direction)),a=(0,o.bool)(!1).toVar();return(0,o.If)(e.intensity.lessThanEqual(.001).or(i.lessThanEqual(.001)),()=>{a.assign(!0)}),(0,o.If)(a.not().and(r.greaterThan((0,o.int)(0))),()=>{(0,o.If)(e.intensity.lessThan(.01),()=>{a.assign(!0)}),(0,o.If)(a.not().and(n.metalness.greaterThan(.9)).and(i.lessThan(.1)),()=>{a.assign(!0)}),(0,o.If)(a.not().and(n.metalness.lessThan(.1)).and(n.roughness.greaterThan(.9)).and(e.intensity.lessThan(.1)),()=>{a.assign(!0)})}),a});(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar();return(0,o.If)(ni(e,n,i,c).not(),()=>{let p=Zr(t,n,i),m=t.add(p),h=(0,o.vec3)(0).toVar(),g=(0,o.float)(1e6).toVar();(0,o.If)(e.angle.greaterThan(.001),()=>{let t=(0,o.vec2)(F(l).toVar(),F(l).toVar()),n=e.angle.mul(.5);h.assign(Wr({direction:e.direction,halfAngle:n,xi:t}));let r=(0,o.cos)(n);g.assign((0,o.float)(1).div(Lt.mul((0,o.float)(1).sub(r))))}).Else(()=>{h.assign(e.direction)});let _=(0,o.max)((0,o.float)(0),(0,o.dot)(n,h));(0,o.If)(_.greaterThan(0),()=>{let t=u(m,h,(0,o.float)(1e6),l);(0,o.If)(t.greaterThan(0),()=>{let l=d(r,h,n,i,a),u=e.color.mul(e.intensity).mul(l).mul(_).mul(t);(0,o.If)(c.equal((0,o.int)(0)).and(s.pdf.greaterThan(0)),()=>{(0,o.If)((0,o.max)((0,o.float)(0),(0,o.dot)((0,o.normalize)(s.direction),h)).greaterThan(.996),()=>{let e=qt({pdf1:g,pdf2:s.pdf});f.assign(u.mul(e))}).Else(()=>{f.assign(u)})}).Else(()=>{f.assign(u)})})})}),f}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.vec3)(0).toVar(),h=$r(e,t,n,i);return(0,o.If)(h.greaterThanEqual(.001),()=>{let g=Zr(t,n,i),_=t.add(g),v=i.roughness.greaterThan(.7).and(i.metalness.lessThan(.3)),y=i.roughness.lessThan(.3).or(i.metalness.greaterThan(.7)),b=l.equal((0,o.int)(0));(0,o.If)(b.or(v).or(h.greaterThan(.1).and(y.not())),()=>{let h=p(c,l,u),g=e.position.add(e.u.mul(h.x.sub(.5))).add(e.v.mul(h.y.sub(.5))).sub(t),v=(0,o.dot)(g,g),y=(0,o.sqrt)(v),x=g.div(y),S=(0,o.max)((0,o.float)(0),(0,o.dot)(n,x)),C=(0,o.max)((0,o.float)(0),(0,o.dot)(x,e.normal).negate());(0,o.If)(S.greaterThan(0).and(C.greaterThan(0)),()=>{let t=d(_,x,y,u);(0,o.If)(t.greaterThan(0),()=>{let c=f(r,x,n,i,a),l=v.div((0,o.max)(e.area.mul(C),J)),u=s.pdf,d=e.area.div((0,o.float)(4).mul(q).mul(v)),p=e.color.mul(e.intensity).mul(d).mul(C),h=(0,o.select)(u.greaterThan(0).and(b),qt({pdf1:l,pdf2:u}),(0,o.float)(1));m.addAssign(p.mul(c).mul(S).mul(t).mul(h))})})}),(0,o.If)(b.or(y).and(s.pdf.greaterThan(0)),()=>{(0,o.If)((0,o.dot)(e.position.sub(_),s.direction).greaterThan(0),()=>{let t=Gr(e,_,s.direction);(0,o.If)(t.greaterThan(0),()=>{let r=d(_,s.direction,t,u);(0,o.If)(r.greaterThan(0),()=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(s.direction,e.normal).negate());(0,o.If)(i.greaterThan(0),()=>{let a=t.mul(t).div((0,o.max)(e.area.mul(i),J)),c=qt({pdf1:s.pdf,pdf2:a}),l=e.color.mul(e.intensity),u=(0,o.max)((0,o.float)(0),(0,o.dot)(n,s.direction));m.addAssign(l.mul(s.value).mul(u).mul(r).mul(c))})})})})})}),m}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=e.position.sub(t),m=(0,o.length)(p);return(0,o.If)(m.lessThanEqual(1e3),()=>{let a=p.div(m),s=(0,o.dot)(n,a);(0,o.If)(s.greaterThan(0),()=>{let c=(0,o.float)(1).div(m.mul(m)),p=e.color.mul(e.intensity).mul(c),h=Zr(t,n,i),g=u(t.add(h),a,m.sub(.001),l);(0,o.If)(g.greaterThan(0),()=>{let e=d(r,a,n,i);f.assign(e.mul(p).mul(s).mul(g))})})}),f}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=e.position.sub(t),m=(0,o.length)(p);return(0,o.If)(m.lessThanEqual(1e3),()=>{let a=p.div(m),s=(0,o.dot)(n,a);(0,o.If)(s.greaterThan(0),()=>{let c=(0,o.dot)(a.negate(),e.direction),p=(0,o.cos)(e.angle);(0,o.If)(c.greaterThanEqual(p),()=>{let h=(0,o.smoothstep)(p,p.add(.1),c),g=(0,o.float)(1).div(m.mul(m)),_=e.color.mul(e.intensity).mul(g).mul(h),v=Zr(t,n,i),y=u(t.add(v),a,m.sub(.001),l);(0,o.If)(y.greaterThan(0),()=>{let e=d(r,a,n,i);f.assign(e.mul(_).mul(s).mul(y))})})})}),f});var ri=2*q;(0,o.Fn)(()=>Fr({valid:(0,o.bool)(!1),direction:(0,o.vec3)(0,1,0),emission:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),lightType:(0,o.int)(2)}));var ii=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(2).toVar();return(0,o.If)(e.area.greaterThan(0),()=>{let d=e.position.add(e.u.mul(n.x.mul(2).sub(1))).add(e.v.mul(n.y.mul(2).sub(1))).toVar().sub(t).toVar(),f=(0,o.dot)(d,d).toVar();(0,o.If)(f.greaterThanEqual(1e-10),()=>{let t=(0,o.sqrt)(f).toVar(),n=d.div(t).toVar(),p=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),m=(0,o.dot)(n.negate(),p).toVar();u.assign((0,o.int)(1)),s.assign(e.color.mul(e.intensity)),c.assign(t),a.assign(n),l.assign(f.div((0,o.max)(e.area.mul((0,o.max)(m,.001)),1e-10)).mul(r)),i.assign(m.greaterThan(0))})}),Fr({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})});(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(2).toVar();return(0,o.If)(e.area.greaterThan(0),()=>{let d=(0,o.float)(.5).mul((0,o.sqrt)(n.x)).toVar(),f=n.y.mul(ri).toVar(),p=d.mul((0,o.cos)(f)).toVar(),m=d.mul((0,o.sin)(f)).toVar(),h=e.position.add(e.u.mul(p)).add(e.v.mul(m)).toVar().sub(t).toVar(),g=(0,o.dot)(h,h).toVar();(0,o.If)(g.greaterThanEqual(1e-10),()=>{let t=(0,o.sqrt)(g).toVar(),n=h.div(t).toVar(),d=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),f=(0,o.dot)(n.negate(),d).toVar();u.assign((0,o.int)(1)),s.assign(e.color.mul(e.intensity)),c.assign(t),a.assign(n),l.assign(g.div((0,o.max)(e.area.mul((0,o.max)(f,.001)),1e-10)).mul(r)),i.assign(f.greaterThan(0))})}),Fr({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})});var ai=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(3).toVar(),d=e.position.sub(t).toVar(),f=(0,o.length)(d).toVar();return(0,o.If)(f.greaterThanEqual(1e-10),()=>{let t=d.div(f).toVar(),n=(0,o.dot)(t.negate(),e.direction).toVar(),u=(0,o.cos)(e.angle).toVar();a.assign(t),c.assign(f),l.assign(r),i.assign(n.greaterThanEqual(u)),(0,o.If)(i,()=>{let t=Ur({coneCosine:u,penumbraCosine:(0,o.cos)(e.angle.mul((0,o.float)(1).sub(e.penumbra))).max(u.add(1e-5)).toVar(),angleCosine:n}),r=Hr({lightDistance:f,cutoffDistance:e.distance,decayExponent:e.decay});s.assign(e.color.mul(e.intensity).mul(r).mul(t))})}),Fr({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})}),oi=(0,o.Fn)(([e,t,n])=>{let r=(0,o.bool)(!1).toVar(),i=(0,o.vec3)(0,1,0).toVar(),a=(0,o.vec3)(0).toVar(),s=(0,o.float)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.int)(2).toVar(),u=e.position.sub(t).toVar(),d=(0,o.length)(u).toVar();return(0,o.If)(d.greaterThanEqual(1e-10),()=>{let t=u.div(d).toVar(),f=Hr({lightDistance:d,cutoffDistance:e.distance,decayExponent:e.decay});l.assign((0,o.int)(2)),i.assign(t),s.assign(d),a.assign(e.color.mul(e.intensity).mul(f)),c.assign(n),r.assign((0,o.bool)(!0))}),Fr({valid:r,direction:i,emission:a,distance:s,pdf:c,lightType:l})}),si=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m])=>{let h=(0,o.bool)(!1).toVar(),g=(0,o.vec3)(0,1,0).toVar(),_=(0,o.vec3)(0).toVar(),v=(0,o.float)(0).toVar(),y=(0,o.float)(0).toVar(),b=(0,o.int)(2).toVar(),x=c.add(u).add(f).add(m).toVar();return(0,o.If)(x.greaterThan((0,o.int)(0)),()=>{let S=(0,o.float)(0).toVar(),C=(0,o.int)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:c,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let a=jr.wrap(Lr(s,r));S.addAssign(Qr(a,e,t,n,i)),C.addAssign(1)})})}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:u,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Mr.wrap(Rr(l,r)),a=(0,o.select)(i.intensity.greaterThan(0),$r(i,e,t,n),(0,o.float)(0));S.addAssign(a),C.addAssign(1)})})}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:f,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Nr.wrap(zr(d,r));S.addAssign(ei(i,e,t,n)),C.addAssign(1)})})}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Pr.wrap(Br(p,r));S.addAssign(ti(i,e,t,n)),C.addAssign(1)})})}),(0,o.If)(S.lessThanEqual(0),()=>{let t=(0,o.int)(r.x.mul((0,o.float)(x)).toVar()).toVar(),n=(0,o.float)(1).div((0,o.max)((0,o.float)(x),1)).toVar();y.assign(n);let i=(0,o.bool)(!1).toVar(),S=(0,o.int)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(c))),()=>{let e=jr.wrap(Lr(s,t.sub(S)));(0,o.If)(e.intensity.greaterThan(0),()=>{g.assign((0,o.normalize)(e.direction)),_.assign(e.color.mul(e.intensity)),v.assign(1e6),b.assign((0,o.int)(0)),h.assign((0,o.bool)(!0)),i.assign((0,o.bool)(!0))})}),S.addAssign(c)}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(u))),()=>{let s=Mr.wrap(Rr(l,t.sub(S)));(0,o.If)(s.intensity.greaterThan(0),()=>{let t=(0,o.vec2)(r.y,F(a)).toVar(),c=Fr.wrap(ii(s,e,t,n));h.assign(c.valid),g.assign(c.direction),_.assign(c.emission),v.assign(c.distance),y.assign(c.pdf),b.assign(c.lightType),i.assign((0,o.bool)(!0))})}),S.addAssign(u)}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(f))),()=>{let r=Nr.wrap(zr(d,t.sub(S)));(0,o.If)(r.intensity.greaterThan(0),()=>{let t=Fr.wrap(oi(r,e,n));h.assign(t.valid),g.assign(t.direction),_.assign(t.emission),v.assign(t.distance),y.assign(t.pdf),b.assign(t.lightType),i.assign((0,o.bool)(!0))})}),S.addAssign(f)}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(m))),()=>{let s=Pr.wrap(Br(p,t.sub(S)));(0,o.If)(s.intensity.greaterThan(0),()=>{let t=(0,o.vec2)(r.y,F(a)).toVar(),c=Fr.wrap(ai(s,e,t,n));h.assign(c.valid),g.assign(c.direction),_.assign(c.emission),v.assign(c.distance),y.assign(c.pdf),b.assign(c.lightType),i.assign((0,o.bool)(!0))})})})}).Else(()=>{let x=r.x.mul(S).toVar(),w=(0,o.float)(0).toVar();C.assign(0);let T=(0,o.int)(-1).toVar(),E=(0,o.int)(-1).toVar(),D=(0,o.float)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:c,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let a=Qr(jr.wrap(Lr(s,r)),e,t,n,i).toVar(),c=w.toVar();w.addAssign(a),(0,o.If)(x.greaterThan(c).and(x.lessThanEqual(w)),()=>{T.assign(0),E.assign(r),D.assign(a)})}),C.addAssign(1)})}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:u,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=Mr.wrap(Rr(l,r)),a=(0,o.select)(i.intensity.greaterThan(0),$r(i,e,t,n),(0,o.float)(0)).toVar(),s=w.toVar();w.addAssign(a),(0,o.If)(x.greaterThan(s).and(x.lessThanEqual(w)),()=>{T.assign(1),E.assign(r),D.assign(a)})}),C.addAssign(1)})}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:f,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=ei(Nr.wrap(zr(d,r)),e,t,n).toVar(),a=w.toVar();w.addAssign(i),(0,o.If)(x.greaterThan(a).and(x.lessThanEqual(w)),()=>{T.assign(2),E.assign(r),D.assign(i)})}),C.addAssign(1)})}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=ti(Pr.wrap(Br(p,r)),e,t,n).toVar(),a=w.toVar();w.addAssign(i),(0,o.If)(x.greaterThan(a).and(x.lessThanEqual(w)),()=>{T.assign(3),E.assign(r),D.assign(i)})}),C.addAssign(1)})});let O=D.div((0,o.max)(S,1e-10)).toVar();(0,o.If)(T.equal((0,o.int)(0)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let e=jr.wrap(Lr(s,E)),t=(0,o.normalize)(e.direction).toVar(),n=(0,o.float)(1).toVar();(0,o.If)(e.angle.greaterThan(0),()=>{let i=(0,o.cos)(e.angle.mul(.5)).toVar(),s=(0,o.mix)(i,(0,o.float)(1),r.y).toVar(),c=(0,o.sqrt)((0,o.max)((0,o.float)(0),(0,o.float)(1).sub(s.mul(s)))).toVar(),l=(0,o.float)(ri).mul(F(a)).toVar(),u=(0,o.normalize)(e.direction).toVar(),d=(0,o.normalize)((0,o.cross)((0,o.select)((0,o.abs)(u.x).greaterThan(.9),(0,o.vec3)(0,1,0),(0,o.vec3)(1,0,0)),u)).toVar(),f=(0,o.cross)(u,d).toVar();t.assign((0,o.normalize)(u.mul(s).add(d.mul((0,o.cos)(l)).add(f.mul((0,o.sin)(l))).mul(c))));let p=(0,o.float)(ri).mul((0,o.max)((0,o.float)(1).sub(i),1e-10)).toVar();n.assign((0,o.float)(1).div(p))}),g.assign(t),_.assign(e.color.mul(e.intensity)),v.assign(1e6),y.assign(n.mul(O)),b.assign((0,o.int)(0)),h.assign((0,o.bool)(!0))}),(0,o.If)(T.equal((0,o.int)(1)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Mr.wrap(Rr(l,E)),n=(0,o.vec2)(r.y,F(a)).toVar(),i=Fr.wrap(ii(t,e,n,O));h.assign(i.valid),g.assign(i.direction),_.assign(i.emission),v.assign(i.distance),y.assign(i.pdf),b.assign(i.lightType)}),(0,o.If)(T.equal((0,o.int)(2)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Nr.wrap(zr(d,E)),n=Fr.wrap(oi(t,e,O));h.assign(n.valid),g.assign(n.direction),_.assign(n.emission),v.assign(n.distance),y.assign(n.pdf),b.assign(n.lightType)}),(0,o.If)(T.equal((0,o.int)(3)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Pr.wrap(Br(p,E)),n=(0,o.vec2)(r.y,F(a)).toVar(),i=Fr.wrap(ai(t,e,n,O));h.assign(i.valid),g.assign(i.direction),_.assign(i.emission),v.assign(i.distance),y.assign(i.pdf),b.assign(i.lightType)})})}),Fr({valid:h,direction:g,emission:_,distance:v,pdf:y,lightType:b})}),ci=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(n,e)).toVar(),a=(0,o.max)((0,o.float)(0),(0,o.dot)(n,t)).toVar(),s=(0,o.normalize)(e.add(t)).toVar(),c=(0,o.max)((0,o.float)(0),(0,o.dot)(n,s)).toVar();(0,o.max)((0,o.float)(0),(0,o.dot)(e,s)).toVar();let l=(0,o.float)(1).sub(r.metalness).mul((0,o.float)(1).sub(r.transmission)).toVar(),u=(0,o.float)(1).sub(l.mul((0,o.float)(1).sub(r.metalness))).toVar(),d=l.add(u).toVar(),f=(0,o.float)(0).toVar();return(0,o.If)(d.greaterThan(0),()=>{let e=(0,o.float)(1).div((0,o.max)(d,1e-10)).toVar();l.mulAssign(e),u.mulAssign(e),(0,o.If)(l.greaterThan(0).and(a.greaterThan(0)),()=>{f.addAssign(l.mul(a).mul(It))}),(0,o.If)(u.greaterThan(0).and(a.greaterThan(0)),()=>{let e=(0,o.max)(r.roughness,.02).toVar();f.addAssign(u.mul(ar(c,i,e)))})}),(0,o.max)(f,1e-8)});(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=(0,o.vec2)(F(c).toVar(),F(c).toVar()).toVar(),m=e.position.add(e.u.mul(p.x.mul(2).sub(1))).add(e.v.mul(p.y.mul(2).sub(1))).toVar().sub(a).toVar(),h=(0,o.dot)(m,m).toVar();return(0,o.If)(h.greaterThanEqual(1e-10),()=>{let n=(0,o.sqrt)(h).toVar(),s=m.div(n).toVar(),p=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),g=(0,o.dot)(s.negate(),p).toVar();(0,o.If)(g.greaterThan(0),()=>{let p=(0,o.dot)(r,s).toVar();(0,o.If)(p.greaterThan(0),()=>{(0,o.If)(Vr({direction:s,surfaceNormal:r}),()=>{let m=Xr(a,s,n.sub(.001),c,vn,l,u,d);(0,o.If)(m.greaterThan(0),()=>{let n=Dr(t,s,r,i),a=h.div((0,o.max)(e.area.mul(g),J)).toVar(),c=ci(t,s,r,i).toVar(),l=(0,o.select)(c.greaterThan(0),qt({pdf1:a,pdf2:c}),(0,o.float)(1)).toVar(),u=e.color.mul(e.intensity).toVar();f.assign(u.mul(n).mul(p).mul(m).mul(l).div((0,o.max)(a,Bt)))})})})})}),f});var li=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k])=>{let A=(0,o.vec3)(0).toVar(),j=e.add(t.mul(.001)).toVar();return(0,o.If)(n.emissiveIntensity.lessThanEqual(10),()=>{let c=(0,o.vec3)(1).toVar(),M=Pt.wrap(en(n.roughness,n.metalness,n.transmission,l,c)),N=M.useBRDFSampling.toVar(),ee=M.useLightSampling.toVar(),te=M.brdfWeight.toVar(),P=M.lightWeight.toVar(),ne=f.add(m).add(g).add(v).toVar(),re=(0,o.float)(.001).mul((0,o.float)(1).add((0,o.float)(l).mul(.5))).toVar(),ie=ne.greaterThan((0,o.int)(0)).toVar(),ae=(0,o.float)(0).toVar();(0,o.If)(ee.and(ie),()=>{ae.addAssign(P)}),(0,o.If)(N,()=>{ae.addAssign(te)}),(0,o.If)(ae.lessThanEqual(0),()=>{ae.assign(1),N.assign((0,o.bool)(!0)),te.assign(1)});let oe=F(u).toVar(),se=F(u).toVar(),ce=oe,le=(0,o.bool)(!1).toVar(),ue=(0,o.bool)(!1).toVar(),de=(0,o.select)(ie,P,(0,o.float)(0)).toVar(),fe=(0,o.float)(1).div((0,o.max)(ae,1e-10)).toVar(),pe=de.mul(fe).toVar();(0,o.If)(ce.lessThan(pe).and(ee).and(ie),()=>{le.assign((0,o.bool)(!0))}).ElseIf(N,()=>{ue.assign((0,o.bool)(!0))}).ElseIf(ie,()=>{le.assign((0,o.bool)(!0))}),(0,o.If)(le,()=>{let e=(0,o.vec2)(se,F(u)).toVar(),i=Fr.wrap(si(j,t,n,e,l,u,d,f,p,m,h,g,_,v));(0,o.If)(i.valid.and(i.pdf.greaterThan(0)),()=>{let e=(0,o.max)((0,o.float)(0),(0,o.dot)(t,i.direction)).toVar(),a=i.emission.x.add(i.emission.y).add(i.emission.z).toVar();(0,o.If)(e.greaterThan(0).and(a.mul(e).greaterThan(re)).and(Vr({direction:i.direction,surfaceNormal:t})),()=>{let a=(0,o.min)(i.distance.sub(.001),(0,o.float)(1e3)).toVar(),s=Xr(j,i.direction,a,u,vn,y,b,x);(0,o.If)(s.greaterThan(0),()=>{let a=Dr(r,i.direction,t,n),c=ci(r,i.direction,t,n).toVar(),l=(0,o.float)(1).toVar();(0,o.If)(c.greaterThan(0).and(N),()=>{let e=i.pdf.mul(P).toVar(),t=c.mul(te).toVar();(0,o.If)(i.lightType.equal((0,o.int)(1)),()=>{l.assign(qt({pdf1:e,pdf2:t}))})});let u=i.emission.mul(a).mul(e).mul(s).mul(l).div((0,o.max)(i.pdf,1e-10));A.addAssign(u.mul(ae).div((0,o.max)(P,1e-10)))})})})}),(0,o.If)(ue,()=>{(0,o.If)(a.greaterThan(0).and(N),()=>{let r=(0,o.max)((0,o.float)(0),(0,o.dot)(t,i)).toVar();(0,o.If)(r.greaterThan(0).and(Vr({direction:i,surfaceNormal:t})),()=>{(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{let c=(0,o.bool)(!1).toVar(),l=(0,o.float)(0).toVar(),d=(0,o.int)(-1).toVar();(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{let a=Mr.wrap(Rr(p,r));(0,o.If)(a.intensity.greaterThan(0),()=>{let s=$r(a,e,t,n).toVar();(0,o.If)(s.greaterThanEqual(re),()=>{(0,o.If)(Gr(a,j,i).toVar().greaterThan(0),()=>{(0,o.If)(s.greaterThan(l),()=>{l.assign(s),d.assign(r)}),c.assign((0,o.bool)(!0))})})})}),(0,o.If)(c.and(d.greaterThanEqual((0,o.int)(0))),()=>{let e=Mr.wrap(Rr(p,d)),t=Gr(e,j,i).toVar();(0,o.If)(t.greaterThan(0),()=>{let n=Xr(j,i,(0,o.min)(t.sub(.001),(0,o.float)(1e3)).toVar(),u,vn,y,b,x);(0,o.If)(n.greaterThan(0),()=>{let c=(0,o.max)((0,o.float)(0),(0,o.dot)(i,e.normal).negate()).toVar();(0,o.If)(c.greaterThan(0),()=>{let i=t.mul(t).toVar().div((0,o.max)(e.area.mul(c),J)).toVar();i.divAssign((0,o.max)((0,o.float)(ne),1));let l=qt({pdf1:a.mul(te).toVar(),pdf2:i.mul(P).toVar()}).toVar(),u=e.color.mul(e.intensity).toVar().mul(s).mul(r).mul(n).mul(l).div((0,o.max)(a,1e-10));A.addAssign(u.mul(ae).div((0,o.max)(te,1e-10)))})})})})})})})}),(0,o.If)(k,()=>{let e=(0,o.vec2)(F(u).toVar(),F(u).toVar()).toVar(),i=(0,o.vec3)(0).toVar(),a=wn(S,T,E,w,C,D,O,e,i).toVar(),s=a.xyz.toVar(),c=a.w.toVar();(0,o.If)(c.greaterThan(0),()=>{let e=(0,o.max)((0,o.float)(0),(0,o.dot)(t,s)).toVar();(0,o.If)(e.greaterThan(0).and(Vr({direction:s,surfaceNormal:t})),()=>{let a=Xr(j,s,(0,o.float)(1e3),u,vn,y,b,x);(0,o.If)(a.greaterThan(0),()=>{let l=Dr(r,s,t,n),u=ci(r,s,t,n).toVar(),d=(0,o.select)(u.greaterThan(0),qt({pdf1:c,pdf2:u}),(0,o.float)(1)).toVar(),f=i.mul(l).mul(e).mul(a).mul(d).div((0,o.max)(c,1e-10));A.addAssign(f)})})})})}),A}),ui=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=(0,o.select)(a,r,(0,o.float)(1).div(r)).toVar(),c=e.add(t.mul(s)).toVar(),l=(0,o.dot)(c,c).toVar(),u=(0,o.select)(l.greaterThan(J),c.div((0,o.sqrt)(l)),n).toVar();(0,o.If)((0,o.dot)(u,n).lessThan(0),()=>{u.assign(u.negate())});let d=(0,o.abs)((0,o.dot)(e,u)).toVar(),f=(0,o.abs)((0,o.dot)(t,u)).toVar(),p=(0,o.abs)((0,o.dot)(n,u)).toVar(),m=Qn(p,i).toVar(),h=d.add(f.mul(s)).toVar(),g=h.mul(h).toVar(),_=f.mul(s).mul(s).div((0,o.max)(g,J)).toVar();return m.mul(p).mul(_)}),di=(0,o.Fn)(([e,t,n,r])=>{let i=e.add(t).toVar(),a=(0,o.dot)(i,i).toVar();return ar((0,o.max)((0,o.dot)(n,(0,o.select)(a.greaterThan(J),i.div((0,o.sqrt)(a)),n).toVar()),0).toVar(),(0,o.max)((0,o.dot)(n,e),0).toVar(),r)}),fi=(0,o.Fn)(([e,t,n,r,i])=>{let a=e.specularImportance.toVar(),s=a.greaterThan(.001).toVar(),c=e.diffuseImportance.toVar(),l=c.greaterThan(.001).toVar(),u=e.transmissionImportance.toVar(),d=u.greaterThan(.001).toVar(),f=e.clearcoatImportance.toVar(),p=f.greaterThan(.001).toVar(),m=a.add(c).add(u).add(f).toVar();return(0,o.If)(m.lessThan(.001),()=>{a.assign(0),c.assign(1),u.assign(0),f.assign(0),m.assign(1),s.assign((0,o.bool)(!1)),l.assign((0,o.bool)(!0)),d.assign((0,o.bool)(!1)),p.assign((0,o.bool)(!1))}).Else(()=>{let e=(0,o.float)(1).div(m).toVar();a.mulAssign(e),c.mulAssign(e),u.mulAssign(e),f.mulAssign(e),m.assign(1)}),Nt({envWeight:(0,o.float)(0),specularWeight:a,diffuseWeight:c,transmissionWeight:u,clearcoatWeight:f,totalWeight:m,useEnv:(0,o.bool)(!1),useSpecular:s,useDiffuse:l,useTransmission:d,useClearcoat:p})}),pi=(0,o.Fn)(([e,t])=>{let n=(0,o.int)(2).toVar(),r=(0,o.float)(1).toVar(),i=(0,o.float)(0).toVar(),a=(0,o.bool)(!1).toVar();return(0,o.If)(e.useSpecular.and(a.not()),()=>{i.addAssign(e.specularWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(1),r.assign(e.specularWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useDiffuse.and(a.not()),()=>{i.addAssign(e.diffuseWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(2),r.assign(e.diffuseWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useTransmission.and(a.not()),()=>{i.addAssign(e.transmissionWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(3),r.assign(e.transmissionWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useClearcoat.and(a.not()),()=>{n.assign(4),r.assign(e.clearcoatWeight),a.assign((0,o.bool)(!0))}),(0,o.If)(a.not(),()=>{n.assign(2),r.assign((0,o.select)(e.useDiffuse,e.diffuseWeight,(0,o.float)(1)))}),(0,o.vec2)((0,o.float)(n),r)}),mi=(0,o.Fn)(([e])=>(0,o.max)(e,0).mul(It)),hi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y])=>{let b=(0,o.vec3)(0).toVar(),x=(0,o.vec3)(0).toVar(),S=(0,o.float)(0).toVar(),C=(0,o.float)(0).toVar(),w=(0,o.float)(0).toVar();return(0,o.If)(u.diffuseImportance.greaterThanEqual(0).and(u.specularImportance.greaterThanEqual(0)).and(u.transmissionImportance.greaterThanEqual(0)).and(u.clearcoatImportance.greaterThanEqual(0)).and(u.envmapImportance.greaterThanEqual(0)).toVar().not(),()=>{let e=(0,o.vec2)(F(l).toVar(),F(l).toVar()).toVar();b.assign(pr(t,e)),x.assign(n.color.xyz),S.assign(1),C.assign(1)}).Else(()=>{let s=Nt.wrap(fi(u,c,n,v,y).toVar()),d=F(l).toVar(),f=(0,o.vec2)(F(l).toVar(),F(l).toVar()).toVar(),p=pi(s,d).toVar(),m=(0,o.int)(p.x).toVar();p.y.toVar();let h=(0,o.vec3)(0).toVar(),g=(0,o.float)(0).toVar(),_=(0,o.vec3)(0).toVar();(0,o.If)(m.equal((0,o.int)(1)),()=>{h.assign(r),g.assign(i),_.assign(a)}).ElseIf(m.equal((0,o.int)(2)),()=>{h.assign(pr(t,f)),g.assign(mi((0,o.max)((0,o.dot)(t,h),0))),_.assign(Dr(e,h,t,n))}).ElseIf(m.equal((0,o.int)(3)),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),i=br.wrap(wr(e,t,n.ior,n.roughness,r,n.dispersion,f,l).toVar());h.assign(i.direction),g.assign(i.pdf),_.assign(Dr(e,h,t,n))}).Else(()=>{h.assign(r),g.assign(i),_.assign(a)});let T=(0,o.dot)(t,h).toVar(),E=(0,o.max)(T,0).toVar(),D=(0,o.abs)(T).toVar(),O=(0,o.float)(0).toVar();(0,o.If)(s.useSpecular,()=>{let r=ar((0,o.max)((0,o.dot)(t,(0,o.normalize)(e.add(h))),.001),(0,o.max)((0,o.dot)(t,e),.001),n.roughness);O.addAssign(s.specularWeight.mul(r))}),(0,o.If)(s.useDiffuse,()=>{let e=mi(E).toVar();O.addAssign(s.diffuseWeight.mul(e))}),(0,o.If)(s.useTransmission.and(n.transmission.greaterThan(0)),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),i=ui(e,h,t,n.ior,n.roughness,r).toVar();O.addAssign(s.transmissionWeight.mul(i))}),(0,o.If)(s.useClearcoat.and(n.clearcoat.greaterThan(0)),()=>{let r=di(e,h,t,n.clearcoatRoughness).toVar();O.addAssign(s.clearcoatWeight.mul(r))}),g.assign((0,o.max)(g,Bt)),O.assign((0,o.max)(O,Bt));let k=g.div(O).toVar(),A=(0,o.select)(m.equal((0,o.int)(3)),D,E),j=_.mul(A).mul(k).div(g).toVar();b.assign(h),x.assign(j),S.assign(k),C.assign(g),w.assign(O)}),Ir({direction:b,throughput:x,misWeight:S,pdf:C,combinedPdf:w})}),gi=K({position:`vec3`,normal:`vec3`,emission:`vec3`,direction:`vec3`,distance:`float`,pdf:`float`,area:`float`,cosThetaLight:`float`,valid:`bool`}),_i=K({contribution:`vec3`,hasEmissive:`bool`,emissionOnly:`vec3`,distance:`float`}),vi=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.sqrt)(r.x),a=(0,o.float)(1).sub(i),s=r.y.mul(i),c=(0,o.float)(1).sub(a).sub(s);return e.mul(a).add(t.mul(s)).add(n.mul(c))}),yi=(0,o.Fn)(([e,t,n])=>(0,o.length)((0,o.cross)(t.sub(e),n.sub(e))).mul(.5)),bi=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.normalize)(e.sub(r)),a=(0,o.normalize)(t.sub(r)),s=(0,o.normalize)(n.sub(r)),c=(0,o.abs)((0,o.dot)(i,(0,o.cross)(a,s))),l=(0,o.float)(1).add((0,o.dot)(a,s)).add((0,o.dot)(i,s)).add((0,o.dot)(i,a));return(0,o.max)((0,o.float)(2).mul((0,o.atan)(c,(0,o.max)(l,(0,o.float)(1e-10)))),(0,o.float)(0))}),xi=(0,o.Fn)(([e,t,n,r])=>{let i=t.sub(e),a=n.sub(e),s=n.sub(t),c=(0,o.max)((0,o.dot)(i,i),(0,o.max)((0,o.dot)(a,a),(0,o.dot)(s,s))),l=(0,o.cross)(i,a),u=(0,o.dot)(l,l),d=(0,o.bool)(!1).toVar();return(0,o.If)(u.greaterThan(1e-20),()=>{let t=(0,o.dot)(l,r.sub(e)),n=t.mul(t).div(u);d.assign(c.greaterThan(n))}),d}),Si=K({direction:`vec3`,position:`vec3`,solidAngle:`float`,valid:`bool`}),Ci=(0,o.Fn)(([e])=>{let t=(0,o.length)(e);return(0,o.select)(t.greaterThan(1e-10),e.div(t),(0,o.vec3)(0))}),wi=(0,o.Fn)(([e,t,n,r,i])=>{let a=Si({direction:(0,o.vec3)(0),position:(0,o.vec3)(0),solidAngle:(0,o.float)(0),valid:!1}).toVar(),s=(0,o.normalize)(e.sub(r)),c=(0,o.normalize)(t.sub(r)),l=(0,o.normalize)(n.sub(r)),u=bi(e,t,n,r);return a.solidAngle.assign(u),(0,o.If)(u.greaterThan(1e-7),()=>{let d=(0,o.clamp)((0,o.dot)(Ci((0,o.cross)(s,c)),Ci((0,o.cross)(s,l))),-1,1),f=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(d.mul(d)),0)),p=(0,o.acos)(d),m=i.x.mul(u).sub(p),h=(0,o.sin)(m),g=(0,o.cos)(m),_=(0,o.clamp)((0,o.dot)(s,c),-1,1),v=g.sub(d),y=h.add(f.mul(_)),b=y.mul(g).sub(v.mul(h)).mul(d).sub(y),x=y.mul(h).add(v.mul(g)).mul(f),S=(0,o.clamp)((0,o.select)((0,o.abs)(x).greaterThan(1e-10),b.div(x),(0,o.float)(1)),-1,1),C=(0,o.dot)(l,s),w=Ci(l.sub(s.mul(C))),T=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(S.mul(S)),0)),E=(0,o.normalize)(s.mul(S).add(w.mul(T))),D=(0,o.dot)(E,c),O=(0,o.float)(1).sub(i.y.mul((0,o.float)(1).sub(D))),k=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(O.mul(O)),0)),A=Ci(E.sub(c.mul(D))),j=(0,o.normalize)(c.mul(O).add(A.mul(k))),M=(0,o.normalize)((0,o.cross)(t.sub(e),n.sub(e))),N=(0,o.dot)(M,j);(0,o.If)((0,o.abs)(N).greaterThan(1e-10),()=>{let t=(0,o.dot)(M,e.sub(r)).div(N);(0,o.If)(t.greaterThan(0),()=>{a.direction.assign(j),a.position.assign(r.add(j.mul(t))),a.valid.assign(!0)})})}),a}),Ti=(0,o.Fn)(([e,t,n,r])=>{let i=n.sub(t),a=r.sub(t),s=e.sub(t),c=(0,o.dot)(i,i),l=(0,o.dot)(i,a),u=(0,o.dot)(a,a),d=(0,o.dot)(s,i),f=(0,o.dot)(s,a),p=(0,o.float)(1).div((0,o.max)(c.mul(u).sub(l.mul(l)),(0,o.float)(1e-10))),m=u.mul(d).sub(l.mul(f)).mul(p),h=c.mul(f).sub(l.mul(d)).mul(p);return(0,o.vec3)((0,o.float)(1).sub(m).sub(h),m,h)}),Ei=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.sqrt)(r.x),a=(0,o.float)(1).sub(i),s=r.y.mul(i),c=(0,o.float)(1).sub(a).sub(s);return(0,o.normalize)(e.mul(a).add(t.mul(s)).add(n.mul(c)))}),Di=(0,o.Fn)(([e])=>e.emissiveIntensity.greaterThan(0).and((0,o.length)(e.emissive).greaterThan(0)));(0,o.Fn)(([e,t])=>{let n=(0,o.float)(0).toVar();return(0,o.If)(Di(e),()=>{let r=e.emissive.x.add(e.emissive.y).add(e.emissive.z).div(3);n.assign(r.mul(e.emissiveIntensity).mul(t))}),n});var Oi=8,ki=2,Ai=K({v0:`vec3`,v1:`vec3`,v2:`vec3`,n0:`vec3`,n1:`vec3`,n2:`vec3`,materialIndex:`int`}),ji=(0,o.Fn)(([e,t])=>{let n=Z(t,e,(0,o.int)(0),(0,o.int)(Oi)),r=Z(t,e,(0,o.int)(1),(0,o.int)(Oi)),i=Z(t,e,(0,o.int)(2),(0,o.int)(Oi)),a=Z(t,e,(0,o.int)(3),(0,o.int)(Oi)),s=Z(t,e,(0,o.int)(4),(0,o.int)(Oi)),c=Z(t,e,(0,o.int)(5),(0,o.int)(Oi)),l=Z(t,e,(0,o.int)(7),(0,o.int)(Oi));return Ai({v0:n.xyz,v1:r.xyz,v2:i.xyz,n0:a.xyz,n1:s.xyz,n2:c.xyz,materialIndex:(0,o.int)(l.z)})}),Mi=(0,o.Fn)(([e,t,n,r,i,a,s])=>{let c=Ai.wrap(ji(e,i)),l=yi(c.v0,c.v1,c.v2),u=Z(a,c.materialIndex,(0,o.int)(Ht.EMISSIVE_ROUGHNESS),Y),d=Z(a,c.materialIndex,(0,o.int)(Ht.IOR_TRANSMISSION),Y),f=(0,o.max)(u.x.add(u.y).add(u.z).div(3).mul(d.a).mul(l),(0,o.float)(1e-10)).div((0,o.max)(s,(0,o.float)(1e-10))),p=(0,o.float)(0).toVar();return(0,o.If)(xi(c.v0,c.v1,c.v2,r),()=>{let e=bi(c.v0,c.v1,c.v2,r);p.assign(f.div((0,o.max)(e,(0,o.float)(1e-10))))}).Else(()=>{let e=(0,o.normalize)((0,o.cross)(c.v1.sub(c.v0),c.v2.sub(c.v0))),r=(0,o.max)((0,o.dot)(n.negate(),e),.001),i=t.mul(t),a=f.div(l);p.assign(a.mul(i).div(r))}),(0,o.max)(p,Bt)}),Ni=(0,o.Fn)(([e,t,n])=>{let r=(0,o.int)(0).toVar(),i=t.sub(1).toVar();return(0,o.Loop)(r.lessThan(i),()=>{let t=r.add(i).div(2).toVar(),a=e.element(t.mul(ki)).b;(0,o.If)(a.lessThan(n),()=>{r.assign(t.add(1))}).Else(()=>{i.assign(t)})}),r}),Pi=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=gi({position:(0,o.vec3)(0),normal:(0,o.vec3)(0),emission:(0,o.vec3)(0),direction:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),area:(0,o.float)(0),cosThetaLight:(0,o.float)(0),valid:!1}).toVar();return(0,o.If)(a.greaterThan((0,o.int)(0)),()=>{let n=Ni(i,a,F(r)).toVar().mul(ki),u=i.element(n),d=i.element(n.add(1)),f=(0,o.int)(u.r),p=(0,o.max)(u.g,(0,o.float)(1e-10)),m=d.xyz,h=d.w,g=Ai.wrap(ji(f,c)),_=(0,o.vec2)(F(r).toVar(),F(r).toVar()),v=(0,o.normalize)((0,o.cross)(g.v1.sub(g.v0),g.v2.sub(g.v0)));(0,o.If)(xi(g.v0,g.v1,g.v2,e),()=>{let n=Si.wrap(wi(g.v0,g.v1,g.v2,e,_));(0,o.If)(n.valid.and(n.solidAngle.greaterThan(1e-7)),()=>{let r=n.direction,i=n.position,a=(0,o.dot)(r,t),c=(0,o.dot)(r,v.negate());(0,o.If)(a.greaterThan(0).and(c.greaterThan(0)),()=>{let t=Ti(i,g.v0,g.v1,g.v2),a=(0,o.normalize)(g.n0.mul(t.x).add(g.n1.mul(t.y)).add(g.n2.mul(t.z))),u=(0,o.length)(i.sub(e)),d=p.div((0,o.max)(s,(0,o.float)(1e-10))).div(n.solidAngle);l.position.assign(i),l.normal.assign(a),l.emission.assign(m),l.direction.assign(r),l.distance.assign(u),l.pdf.assign((0,o.max)(d,Bt)),l.area.assign(h),l.cosThetaLight.assign(c),l.valid.assign(!0)})})}).Else(()=>{let n=vi(g.v0,g.v1,g.v2,_),r=Ei(g.n0,g.n1,g.n2,_),i=n.sub(e),a=(0,o.dot)(i,i),c=(0,o.sqrt)(a),u=i.div(c),d=(0,o.dot)(u,t),f=(0,o.dot)(u,r.negate());(0,o.If)(d.greaterThan(0).and(f.greaterThan(0)),()=>{let e=p.div((0,o.max)(s,(0,o.float)(1e-10)).mul(h)).mul(a).div(f);l.position.assign(n),l.normal.assign(r),l.emission.assign(m),l.direction.assign(u),l.distance.assign(c),l.pdf.assign((0,o.max)(e,Bt)),l.area.assign(h),l.cosThetaLight.assign(f),l.valid.assign(!0)})})}),l}),Fi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h])=>{let g=_i({contribution:(0,o.vec3)(0),hasEmissive:!1,emissionOnly:(0,o.vec3)(0),distance:(0,o.float)(0)}).toVar();return(0,o.If)(a.greaterThan((0,o.int)(1)).and(r.roughness.greaterThan(.9)).and(r.metalness.lessThan(.1)).not(),()=>{let a=gi.wrap(Pi(e,t,i,s,l,u,d,f));(0,o.If)(a.valid.and(a.pdf.greaterThan(0)),()=>{g.hasEmissive.assign(!0),g.emissionOnly.assign(a.emission),g.distance.assign(a.distance);let i=(0,o.max)((0,o.float)(0),(0,o.dot)(t,a.direction));(0,o.If)(i.greaterThan(0),()=>{let l=h(e,t,r),u=e.add(l),d=a.distance.sub(.001),f=p(u,a.direction,d,s);(0,o.If)(f.greaterThan(0),()=>{let e=m(n,a.direction,t,r),s=ci(n,a.direction,t,r),l=(0,o.select)(s.greaterThan(0),qt({pdf1:a.pdf,pdf2:s}),(0,o.float)(1));g.contribution.assign(a.emission.mul(e).mul(i).div(a.pdf).mul(f).mul(c).mul(l))})})})}),g}),Ii=(0,o.Fn)(([e,t,n,r,i,a,o,s,c,l,u,d,f,p,m])=>_i.wrap(Fi(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m)).contribution),Li=4,Ri=2,zi=32,Bi=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=gi({position:(0,o.vec3)(0),normal:(0,o.vec3)(0),emission:(0,o.vec3)(0),direction:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),area:(0,o.float)(0),cosThetaLight:(0,o.float)(0),valid:!1}).toVar(),c=(0,o.float)(1).toVar(),l=(0,o.int)(0).toVar(),u=(0,o.bool)(!1).toVar();return(0,o.Loop)(zi,()=>{let t=l.mul((0,o.int)(Li)),i=r.element(t.add((0,o.int)(1))),a=r.element(t.add((0,o.int)(2)));(0,o.If)(i.w.greaterThan(.5),()=>{u.assign((0,o.bool)(!0)),(0,o.Break)()});let s=(0,o.int)(a.x),d=(0,o.int)(a.y),f=s.mul((0,o.int)(Li)),p=r.element(f),m=r.element(f.add((0,o.int)(1))),h=d.mul((0,o.int)(Li)),g=r.element(h),_=r.element(h.add((0,o.int)(1))),v=(0,o.vec3)(p.x.add(m.x).mul(.5),p.y.add(m.y).mul(.5),p.z.add(m.z).mul(.5)),y=(0,o.vec3)(g.x.add(_.x).mul(.5),g.y.add(_.y).mul(.5),g.z.add(_.z).mul(.5)),b=v.sub(e),x=y.sub(e),S=(0,o.max)((0,o.dot)(b,b),(0,o.float)(.01)),C=(0,o.max)((0,o.dot)(x,x),(0,o.float)(.01)),w=(0,o.max)(p.w,(0,o.float)(0)),T=(0,o.max)(g.w,(0,o.float)(0)),E=w.div(S),D=T.div(C),O=E.add(D);(0,o.If)(O.lessThanEqual((0,o.float)(0)),()=>{l.assign(s)}).Else(()=>{let e=E.div(O);(0,o.If)(F(n).lessThan(e),()=>{c.mulAssign(e),l.assign(s)}).Else(()=>{c.mulAssign((0,o.float)(1).sub(e)),l.assign(d)})})}),(0,o.If)(u,()=>{let u=l.mul((0,o.int)(Li)),d=r.element(u),f=r.element(u.add((0,o.int)(2))),p=(0,o.int)(f.x),m=(0,o.int)(f.y),h=(0,o.max)(d.w,(0,o.float)(1e-10)),g=F(n).mul(h),_=(0,o.float)(0).toVar(),v=p.add(m.sub((0,o.int)(1))).toVar(),y=(0,o.float)(1e-10).toVar();(0,o.Loop)({start:(0,o.int)(0),end:m},({i:e})=>{let t=p.add(e),n=t.mul((0,o.int)(Ri)),r=(0,o.max)(i.element(n).g,(0,o.float)(0));_.addAssign(r),(0,o.If)(_.greaterThanEqual(g).and(r.greaterThan((0,o.float)(0))),()=>{v.assign(t),y.assign(r),(0,o.Break)()})}),c.mulAssign(y.div(h));let b=v.mul((0,o.int)(Ri)),x=i.element(b),S=i.element(b.add((0,o.int)(1))),C=(0,o.int)(x.r),w=S.xyz,T=S.w,E=Ai.wrap(ji(C,a)),D=(0,o.vec2)(F(n).toVar(),F(n).toVar()),O=(0,o.normalize)((0,o.cross)(E.v1.sub(E.v0),E.v2.sub(E.v0)));(0,o.If)(xi(E.v0,E.v1,E.v2,e),()=>{let n=Si.wrap(wi(E.v0,E.v1,E.v2,e,D));(0,o.If)(n.valid.and(n.solidAngle.greaterThan((0,o.float)(1e-7))),()=>{let r=n.direction,i=n.position,a=(0,o.dot)(r,t),l=(0,o.dot)(r,O.negate());(0,o.If)(a.greaterThan((0,o.float)(0)).and(l.greaterThan((0,o.float)(0))),()=>{let t=Ti(i,E.v0,E.v1,E.v2),a=(0,o.normalize)(E.n0.mul(t.x).add(E.n1.mul(t.y)).add(E.n2.mul(t.z))),u=(0,o.length)(i.sub(e)),d=c.div((0,o.max)(n.solidAngle,(0,o.float)(1e-10)));s.position.assign(i),s.normal.assign(a),s.emission.assign(w),s.direction.assign(r),s.distance.assign(u),s.pdf.assign((0,o.max)(d,Bt)),s.area.assign(T),s.cosThetaLight.assign(l),s.valid.assign(!0)})})}).Else(()=>{let n=vi(E.v0,E.v1,E.v2,D),r=Ei(E.n0,E.n1,E.n2,D),i=n.sub(e),a=(0,o.dot)(i,i),l=(0,o.sqrt)(a),u=i.div(l),d=(0,o.dot)(u,t),f=(0,o.dot)(u,r.negate());(0,o.If)(d.greaterThan((0,o.float)(0)).and(f.greaterThan((0,o.float)(0))),()=>{let e=c.div((0,o.max)(T,(0,o.float)(1e-10))).mul(a).div(f);s.position.assign(n),s.normal.assign(r),s.emission.assign(w),s.direction.assign(u),s.distance.assign(l),s.pdf.assign((0,o.max)(e,Bt)),s.area.assign(T),s.cosThetaLight.assign(f),s.valid.assign(!0)})})}),s}),Vi=0,Hi=1,Ui=2,Wi=3,Gi=K({radiance:`vec4`,objectNormal:`vec3`,objectColor:`vec3`,objectID:`float`,firstHitPoint:`vec3`,firstHitDistance:`float`}),Ki=(0,o.Fn)(([e,t,n,r,i])=>{let a=i.toVar();return(0,o.If)(n.not().or(r.notEqual(t)),()=>{a.assign($t(e.metalness,e.roughness,e.transmission,e.clearcoat,e.emissive))}),a}),qi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.vec3)(0).toVar(),h=(0,o.vec3)(0).toVar(),g=(0,o.float)(0).toVar(),_=At.wrap(Ki(n,r,s,c,l)).toVar(),v=d.toVar();(0,o.If)(u.not(),()=>{(0,o.If)(f,()=>{v.assign(cr(n,_,p))}).Else(()=>{let e=Mt({F0:Zn(n.ior),NoV:(0,o.float)(1),diffuseColor:(0,o.vec3)(0),specularColor:(0,o.vec3)(0),isMetallic:!1,isPurelyDiffuse:!1,hasSpecialFeatures:!1,alpha:(0,o.float)(0),k:(0,o.float)(0),alpha2:(0,o.float)(0),tsAlbedo:(0,o.vec4)(0),tsEmissive:(0,o.vec3)(0),tsMetalness:(0,o.float)(0),tsRoughness:(0,o.float)(0),tsNormal:(0,o.vec3)(0),tsHasTextures:!1,invRoughness:(0,o.float)(1).sub(n.roughness),metalFactor:(0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness)),iorFactor:(0,o.min)((0,o.float)(2).div(n.ior),1),maxSheenColor:(0,o.max)(n.sheenColor.x,(0,o.max)(n.sheenColor.y,n.sheenColor.z))}).toVar();v.assign(cr(n,_,e))})});let y=i.x.toVar(),b=(0,o.vec2)(i.y,F(a)).toVar(),x=(0,o.vec3)(0).toVar(),S=v.diffuse.toVar(),C=S.add(v.specular).toVar(),w=C.add(v.sheen).toVar(),T=w.add(v.clearcoat).toVar(),E=(0,o.bool)(!1).toVar();(0,o.If)(y.lessThan(S).and(E.not()),()=>{m.assign(fr({N:t,xi:b}));let r=(0,o.clamp)((0,o.dot)(t,m),0,1);g.assign(r.mul(It)),h.assign(Dr(e,m,t,n)),E.assign((0,o.bool)(!0))});let D=(0,o.clamp)((0,o.dot)(t,e),.001,1).toVar();return(0,o.If)(y.lessThan(C).and(E.not()),()=>{let r=Jt({N:t}),a=mr({V:r.transpose().mul(e).toVar(),roughness:n.roughness,Xi:i});x.assign(r.mul(a));let s=(0,o.clamp)((0,o.dot)(t,x),.001,1);m.assign((0,o.reflect)(e.negate(),x)),g.assign(ar(s,D,n.roughness)),h.assign(Dr(e,m,t,n)),E.assign((0,o.bool)(!0))}),(0,o.If)(y.lessThan(w).and(E.not()),()=>{x.assign(dr({N:t,roughness:n.sheenRoughness,Xi:i}));let r=(0,o.clamp)((0,o.dot)(t,x),.001,1),a=(0,o.clamp)((0,o.dot)(e,x),.001,1);m.assign((0,o.reflect)(e.negate(),x));let s=(0,o.dot)(t,m).toVar();(0,o.If)(s.lessThanEqual(0),()=>{m.assign(fr({N:t,xi:i})),s.assign((0,o.clamp)((0,o.dot)(t,m),0,1)),g.assign(s.mul(It)),h.assign(Dr(e,m,t,n))}).Else(()=>{g.assign($n(r,n.sheenRoughness).mul(r).div((0,o.float)(4).mul(a))),g.assign((0,o.max)(g,Bt)),h.assign(Dr(e,m,t,n))}),E.assign((0,o.bool)(!0))}),(0,o.If)(y.lessThan(T).and(E.not()),()=>{let r=(0,o.clamp)(n.clearcoatRoughness,zt,1);x.assign(dr({N:t,roughness:r,Xi:i}));let a=(0,o.clamp)((0,o.dot)(t,x),0,1);m.assign((0,o.reflect)(e.negate(),x)),g.assign(ar(a,D,r)),g.assign((0,o.max)(g,Bt)),h.assign(Dr(e,m,t,n)),E.assign((0,o.bool)(!0))}),(0,o.If)(E.not(),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),s=br.wrap(wr(e,t,n.ior,n.roughness,r,n.dispersion,i,a));m.assign(s.direction),g.assign((0,o.max)(s.pdf,Bt)),h.assign(Dr(e,m,t,n))}),g.assign((0,o.max)(g,Bt)),Tt({direction:m,value:h,pdf:g})}),Ji=(0,o.Fn)(([e,t,n,r,i,a,s,c,l])=>{let u=(0,o.max)(Gt({v:e}),0).toVar(),d=At.wrap(Ki(n,r,i,a,s)).toVar(),f=d.complexityScore.toVar();(0,o.If)(d.isMetallic.and(d.isSmooth),()=>{f.addAssign(.15)}),(0,o.If)(d.isTransmissive.and(d.hasClearcoat),()=>{f.addAssign(.12)}),(0,o.If)(d.isEmissive,()=>{f.addAssign(.1)}),f.assign((0,o.clamp)(f,0,1));let p=(0,o.float)(.5).toVar();(0,o.If)(c.and(l).and(u.greaterThan(.01)),()=>{let e=(0,o.clamp)(t.y,0,1);p.assign((0,o.mix)((0,o.float)(.3),(0,o.float)(.8),e.mul(e)))});let m=(0,o.smoothstep)((0,o.float)(.001),(0,o.float)(.1),u);return u.mul((0,o.mix)(f.mul(.7),p,.3)).mul(m)}),Yi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.float)(1).toVar();return(0,o.If)(e.greaterThanEqual((0,o.int)(3)),()=>{let h=(0,o.max)(Gt({v:t}),0).toVar();(0,o.If)(h.lessThan(8e-4).and(e.greaterThan((0,o.int)(4))),()=>{let e=(0,o.max)(h.mul(125),.01),t=F(a);m.assign((0,o.select)(t.lessThan(e),e,(0,o.float)(0)))}).Else(()=>{let g=At.wrap(Ki(n,r,s,c,l)).toVar(),_=g.complexityScore.toVar();(0,o.If)(g.isMetallic.and(g.isSmooth).and(e.lessThan((0,o.int)(7))),()=>{_.addAssign(.3)}),(0,o.If)(g.isTransmissive.and(e.lessThan((0,o.int)(6))),()=>{_.addAssign(.25)}),(0,o.If)(g.isEmissive.and(e.lessThan((0,o.int)(4))),()=>{_.addAssign(.15)}),_.assign((0,o.clamp)(_,0,1));let v=(0,o.int)(3).toVar();(0,o.If)(_.greaterThan(.6),()=>{v.assign(5)}).ElseIf(_.greaterThan(.4),()=>{v.assign(4)}),(0,o.If)(e.lessThan(v),()=>{m.assign(1)}).Else(()=>{let y=(0,o.float)(0).toVar();(0,o.If)(s.and(u),()=>{y.assign(d)}).Else(()=>{y.assign(Ji(t,i,n,r,s,c,l,f,p))});let b=(0,o.mix)((0,o.clamp)(_.mul(.4).add(h.mul(.6)).mul(1.2),.15,.95),(0,o.clamp)(h.mul(.4).add(_.mul(.1)),.03,.6),(0,o.clamp)((0,o.float)(e.sub(v)).div(10),0,1)).toVar();b.assign((0,o.mix)(b,(0,o.max)(b,y),.4)),(0,o.If)(_.greaterThan(.5),()=>{let e=_.sub(.5).mul(.6);b.assign((0,o.mix)(b,(0,o.float)(1),e))});let x=(0,o.float)(.12).add(_.mul(.08)),S=(0,o.exp)((0,o.float)(e.sub(v)).negate().mul(x));b.mulAssign(S);let C=(0,o.select)(g.isEmissive,(0,o.float)(.04),(0,o.float)(.02));b.assign((0,o.max)(b,C));let w=F(a);m.assign((0,o.select)(w.lessThan(b),b,(0,o.float)(0)))})})}),m}),Xi=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=(0,o.vec4)(0).toVar();return(0,o.If)(e.and(s.not()),()=>{l.assign((0,o.vec4)(0))}).Else(()=>{let s=Tn({tex:n,samp:(0,o.sampler)(n),direction:t,environmentMatrix:r,environmentIntensity:i,enableEnvironmentLight:a});(0,o.If)(e,()=>{l.assign(s.mul(c))}).Else(()=>{l.assign(s)})}),l}),Zi=(0,o.wgslFn)(`
|
|
506
|
+
`),Kr=(0,o.Fn)(([e,t,n])=>{let r=e.normal,i=(0,o.dot)(r,n),a=(0,o.float)(-1).toVar();return(0,o.If)(i.lessThan(-1e-4),()=>{let s=(0,o.float)(1).div(i),c=(0,o.dot)(e.position.sub(t),r).mul(s).toVar();(0,o.If)(c.greaterThan(.001),()=>{let r=t.add(n.mul(c)).sub(e.position),i=(0,o.length)(e.u),s=(0,o.length)(e.v),l=e.u.div(i),u=e.v.div(s),d=(0,o.dot)(r,l),f=(0,o.dot)(r,u);(0,o.If)((0,o.abs)(d).lessThanEqual(i).and((0,o.abs)(f).lessThanEqual(s)),()=>{a.assign(c)})})}),a}),qr=null,Jr=null;function Yr(e){qr=e}function Xr(e){Jr=e}(0,o.Fn)(([e,t,n])=>{let r=(0,o.float)(1).toVar();return(0,o.If)(e.material.transmission.greaterThan(0),()=>{let n=(0,o.dot)(t,e.normal).lessThan(0),i=wr(t,e.normal,e.material,n);r.assign((0,o.float)(1).sub(i))}).ElseIf(e.material.transparent,()=>{r.assign(e.material.opacity)}),r});var Zr=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=(0,o.float)(1).toVar(),u=e.toVar(),d=(0,o.float)(n).toVar();return(0,o.Loop)({start:(0,o.int)(0),end:(0,o.int)(8)},()=>{let e=St({origin:u,direction:t}),n=Tt.wrap(i(e,a,s,c,d));(0,o.If)(n.didHit.not(),()=>{(0,o.Break)()});let r=wt.wrap(an(n.materialIndex,c)),f=(0,o.bool)(!1).toVar();Jr&&(0,o.If)(Jr.equal((0,o.int)(1)),()=>{let e=(0,o.float)(1).toVar();qr&&(0,o.If)(r.albedoMapIndex.greaterThanEqual((0,o.int)(0)),()=>{let t=n.uv.x,i=n.uv.y,a=(0,o.float)(1).sub(t).sub(i),c=(0,o.int)(8),l=Z(s,n.triangleIndex,(0,o.int)(6),c),u=Z(s,n.triangleIndex,(0,o.int)(7),c),d=On({uv:l.xy.mul(a).add(l.zw.mul(t)).add(u.xy.mul(i)),transform:r.albedoTransform});e.assign((0,o.texture)(qr,d).depth((0,o.int)(r.albedoMapIndex)).a)}),(0,o.If)(r.alphaMode.equal((0,o.int)(1)),()=>{let t=r.color.a.mul(e),n=(0,o.select)(r.alphaTest.greaterThan(0),r.alphaTest,(0,o.float)(.5));(0,o.If)(t.lessThan(n),()=>{f.assign(!0)})}).ElseIf(r.alphaMode.equal((0,o.int)(2)),()=>{let t=(0,o.clamp)(r.color.a.mul(r.opacity).mul(e),0,1);l.mulAssign((0,o.float)(1).sub(t)),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),f.assign(!0)})}),(0,o.If)(f,()=>{let e=(0,o.max)((0,o.float)(1e-5),(0,o.length)(n.hitPoint).mul(1e-6));u.assign(n.hitPoint.add(t.mul(e))),d.subAssign(n.dst.add(e))}).ElseIf(r.transmission.greaterThan(0),()=>{let e=(0,o.dot)(t,n.normal).lessThan(0),i=(0,o.select)(e,n.normal,n.normal.negate());(0,o.If)(e.not().and(r.attenuationDistance.greaterThan(0)),()=>{let e=(0,o.length)(n.hitPoint.sub(u)),t=Cr(r.attenuationColor,r.attenuationDistance,e);l.mulAssign(t.x.add(t.y).add(t.z).div(3))});let a=qn((0,o.abs)((0,o.dot)(t,i)),Zn(r.ior,(0,o.float)(1))),s=(0,o.float)(1).sub(a).mul(r.transmission);l.mulAssign(s),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),u.assign(n.hitPoint.add(t.mul(.001))),d.subAssign(n.dst.add(.001))}).ElseIf(r.transparent,()=>{l.mulAssign((0,o.float)(1).sub(r.opacity)),(0,o.If)(l.lessThan(.005),()=>{l.assign(0),(0,o.Break)()}),u.assign(n.hitPoint.add(t.mul(.001))),d.subAssign(n.dst.add(.001))}).Else(()=>{l.assign(0),(0,o.Break)()})}),l}),Qr=(0,o.Fn)(([e,t,n])=>{let r=(0,o.max)((0,o.float)(1e-4),(0,o.length)(e).mul(1e-6)).toVar().toVar();return(0,o.If)(n.transmission.greaterThan(0),()=>{r.mulAssign(2)}),(0,o.If)(n.roughness.lessThan(.1),()=>{r.mulAssign(1.5)}),t.mul(r)}),$r=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.max)((0,o.float)(0),(0,o.dot)(n,e.direction)),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThan(0),()=>{let t=e.intensity.mul((0,o.dot)(e.color,Ht)),n=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{n.assign(1.5)}).ElseIf(r.roughness.greaterThan(.8),()=>{n.assign(.7)});let c=(0,o.float)(1).div((0,o.float)(1).add((0,o.float)(i).mul(.5)));s.assign(t.mul(a).mul(n).mul(c))}),s}),ei=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.length)(i),s=a.mul(a),c=i.div(a),l=(0,o.max)((0,o.dot)(n,c),0),u=(0,o.float)(0).toVar();return(0,o.If)(l.greaterThan(0),()=>{let t=(0,o.max)((0,o.dot)(c,e.normal).negate(),0);(0,o.If)(t.greaterThan(0),()=>{let n=e.area.div((0,o.max)(s,.1)),i=e.intensity.mul((0,o.dot)(e.color,Ht)).mul(e.area),a=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{a.mulAssign(1.5),(0,o.If)(r.roughness.lessThan(.3),()=>{a.mulAssign((0,o.float)(1).add((0,o.float)(1).sub(r.roughness).mul(.5)))})}),(0,o.If)(r.roughness.greaterThan(.6).and(r.metalness.lessThan(.3)),()=>{let t=(0,o.min)(e.area.mul(2),(0,o.float)(2));a.mulAssign(t)}),(0,o.If)(r.transmission.greaterThan(.5),()=>{a.mulAssign((0,o.float)(1).add(r.transmission.mul(.3)))}),u.assign(i.mul(n).mul(l).mul(t).mul(a))})}),u}),ti=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.dot)(i,i),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThanEqual(.001),()=>{let t=(0,o.sqrt)(a),c=i.div(t),l=(0,o.max)((0,o.float)(0),(0,o.dot)(n,c));(0,o.If)(l.greaterThan(0),()=>{let t=(0,o.float)(1).div((0,o.max)(a,.1)),n=e.intensity.mul((0,o.dot)(e.color,Ht)),i=(0,o.float)(1).toVar();(0,o.If)(r.metalness.greaterThan(.7),()=>{i.mulAssign(1.5),(0,o.If)(r.roughness.lessThan(.3),()=>{i.mulAssign((0,o.float)(1).add((0,o.float)(1).sub(r.roughness).mul(.4)))})}),(0,o.If)(r.roughness.greaterThan(.6),()=>{i.mulAssign(.9)}),(0,o.If)(r.transmission.greaterThan(.5),()=>{i.mulAssign((0,o.float)(1).add(r.transmission.mul(.2)))}),s.assign(n.mul(t).mul(l).mul(i))})}),s}),ni=(0,o.Fn)(([e,t,n,r])=>{let i=e.position.sub(t),a=(0,o.dot)(i,i),s=(0,o.float)(0).toVar();return(0,o.If)(a.greaterThanEqual(.001),()=>{let t=i.div((0,o.sqrt)(a)),c=(0,o.max)((0,o.float)(0),(0,o.dot)(n,t));(0,o.If)(c.greaterThan(0),()=>{let n=(0,o.dot)(t.negate(),e.direction),i=(0,o.cos)(e.angle);(0,o.If)(n.greaterThanEqual(i),()=>{let t=(0,o.float)(1).div((0,o.max)(a,.01)),l=(0,o.smoothstep)(i,i.add(.1),n),u=e.intensity.mul((0,o.dot)(e.color,Ht)),d=(0,o.select)(r.metalness.greaterThan(.7),(0,o.float)(1.5),(0,o.select)(r.roughness.greaterThan(.8),(0,o.float)(.8),(0,o.float)(1)));s.assign(u.mul(t).mul(l).mul(c).mul(d))})})}),s}),ri=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(t,e.direction)),a=(0,o.bool)(!1).toVar();return(0,o.If)(e.intensity.lessThanEqual(.001).or(i.lessThanEqual(.001)),()=>{a.assign(!0)}),(0,o.If)(a.not().and(r.greaterThan((0,o.int)(0))),()=>{(0,o.If)(e.intensity.lessThan(.01),()=>{a.assign(!0)}),(0,o.If)(a.not().and(n.metalness.greaterThan(.9)).and(i.lessThan(.1)),()=>{a.assign(!0)}),(0,o.If)(a.not().and(n.metalness.lessThan(.1)).and(n.roughness.greaterThan(.9)).and(e.intensity.lessThan(.1)),()=>{a.assign(!0)})}),a});(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar();return(0,o.If)(ri(e,n,i,c).not(),()=>{let p=Qr(t,n,i),m=t.add(p),h=(0,o.vec3)(0).toVar(),g=(0,o.float)(1e6).toVar();(0,o.If)(e.angle.greaterThan(.001),()=>{let t=(0,o.vec2)(F(l).toVar(),F(l).toVar()),n=e.angle.mul(.5);h.assign(Gr({direction:e.direction,halfAngle:n,xi:t}));let r=(0,o.cos)(n);g.assign((0,o.float)(1).div(Rt.mul((0,o.float)(1).sub(r))))}).Else(()=>{h.assign(e.direction)});let _=(0,o.max)((0,o.float)(0),(0,o.dot)(n,h));(0,o.If)(_.greaterThan(0),()=>{let t=u(m,h,(0,o.float)(1e6),l);(0,o.If)(t.greaterThan(0),()=>{let l=d(r,h,n,i,a),u=e.color.mul(e.intensity).mul(l).mul(_).mul(t);(0,o.If)(c.equal((0,o.int)(0)).and(s.pdf.greaterThan(0)),()=>{(0,o.If)((0,o.max)((0,o.float)(0),(0,o.dot)((0,o.normalize)(s.direction),h)).greaterThan(.996),()=>{let e=Jt({pdf1:g,pdf2:s.pdf});f.assign(u.mul(e))}).Else(()=>{f.assign(u)})}).Else(()=>{f.assign(u)})})})}),f}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.vec3)(0).toVar(),h=ei(e,t,n,i);return(0,o.If)(h.greaterThanEqual(.001),()=>{let g=Qr(t,n,i),_=t.add(g),v=i.roughness.greaterThan(.7).and(i.metalness.lessThan(.3)),y=i.roughness.lessThan(.3).or(i.metalness.greaterThan(.7)),b=l.equal((0,o.int)(0));(0,o.If)(b.or(v).or(h.greaterThan(.1).and(y.not())),()=>{let h=p(c,l,u),g=e.position.add(e.u.mul(h.x.sub(.5))).add(e.v.mul(h.y.sub(.5))).sub(t),v=(0,o.dot)(g,g),y=(0,o.sqrt)(v),x=g.div(y),S=(0,o.max)((0,o.float)(0),(0,o.dot)(n,x)),C=(0,o.max)((0,o.float)(0),(0,o.dot)(x,e.normal).negate());(0,o.If)(S.greaterThan(0).and(C.greaterThan(0)),()=>{let t=d(_,x,y,u);(0,o.If)(t.greaterThan(0),()=>{let c=f(r,x,n,i,a),l=v.div((0,o.max)(e.area.mul(C),J)),u=s.pdf,d=e.area.div((0,o.float)(4).mul(q).mul(v)),p=e.color.mul(e.intensity).mul(d).mul(C),h=(0,o.select)(u.greaterThan(0).and(b),Jt({pdf1:l,pdf2:u}),(0,o.float)(1));m.addAssign(p.mul(c).mul(S).mul(t).mul(h))})})}),(0,o.If)(b.or(y).and(s.pdf.greaterThan(0)),()=>{(0,o.If)((0,o.dot)(e.position.sub(_),s.direction).greaterThan(0),()=>{let t=Kr(e,_,s.direction);(0,o.If)(t.greaterThan(0),()=>{let r=d(_,s.direction,t,u);(0,o.If)(r.greaterThan(0),()=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(s.direction,e.normal).negate());(0,o.If)(i.greaterThan(0),()=>{let a=t.mul(t).div((0,o.max)(e.area.mul(i),J)),c=Jt({pdf1:s.pdf,pdf2:a}),l=e.color.mul(e.intensity),u=(0,o.max)((0,o.float)(0),(0,o.dot)(n,s.direction));m.addAssign(l.mul(s.value).mul(u).mul(r).mul(c))})})})})})}),m}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=e.position.sub(t),m=(0,o.length)(p);return(0,o.If)(m.lessThanEqual(1e3),()=>{let a=p.div(m),s=(0,o.dot)(n,a);(0,o.If)(s.greaterThan(0),()=>{let c=(0,o.float)(1).div(m.mul(m)),p=e.color.mul(e.intensity).mul(c),h=Qr(t,n,i),g=u(t.add(h),a,m.sub(.001),l);(0,o.If)(g.greaterThan(0),()=>{let e=d(r,a,n,i);f.assign(e.mul(p).mul(s).mul(g))})})}),f}),(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=e.position.sub(t),m=(0,o.length)(p);return(0,o.If)(m.lessThanEqual(1e3),()=>{let a=p.div(m),s=(0,o.dot)(n,a);(0,o.If)(s.greaterThan(0),()=>{let c=(0,o.dot)(a.negate(),e.direction),p=(0,o.cos)(e.angle);(0,o.If)(c.greaterThanEqual(p),()=>{let h=(0,o.smoothstep)(p,p.add(.1),c),g=(0,o.float)(1).div(m.mul(m)),_=e.color.mul(e.intensity).mul(g).mul(h),v=Qr(t,n,i),y=u(t.add(v),a,m.sub(.001),l);(0,o.If)(y.greaterThan(0),()=>{let e=d(r,a,n,i);f.assign(e.mul(_).mul(s).mul(y))})})})}),f});var ii=2*q;(0,o.Fn)(()=>Ir({valid:(0,o.bool)(!1),direction:(0,o.vec3)(0,1,0),emission:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),lightType:(0,o.int)(2)}));var ai=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(2).toVar();return(0,o.If)(e.area.greaterThan(0),()=>{let d=e.position.add(e.u.mul(n.x.mul(2).sub(1))).add(e.v.mul(n.y.mul(2).sub(1))).toVar().sub(t).toVar(),f=(0,o.dot)(d,d).toVar();(0,o.If)(f.greaterThanEqual(1e-10),()=>{let t=(0,o.sqrt)(f).toVar(),n=d.div(t).toVar(),p=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),m=(0,o.dot)(n.negate(),p).toVar();u.assign((0,o.int)(1)),s.assign(e.color.mul(e.intensity)),c.assign(t),a.assign(n),l.assign(f.div((0,o.max)(e.area.mul((0,o.max)(m,.001)),1e-10)).mul(r)),i.assign(m.greaterThan(0))})}),Ir({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})});(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(2).toVar();return(0,o.If)(e.area.greaterThan(0),()=>{let d=(0,o.float)(.5).mul((0,o.sqrt)(n.x)).toVar(),f=n.y.mul(ii).toVar(),p=d.mul((0,o.cos)(f)).toVar(),m=d.mul((0,o.sin)(f)).toVar(),h=e.position.add(e.u.mul(p)).add(e.v.mul(m)).toVar().sub(t).toVar(),g=(0,o.dot)(h,h).toVar();(0,o.If)(g.greaterThanEqual(1e-10),()=>{let t=(0,o.sqrt)(g).toVar(),n=h.div(t).toVar(),d=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),f=(0,o.dot)(n.negate(),d).toVar();u.assign((0,o.int)(1)),s.assign(e.color.mul(e.intensity)),c.assign(t),a.assign(n),l.assign(g.div((0,o.max)(e.area.mul((0,o.max)(f,.001)),1e-10)).mul(r)),i.assign(f.greaterThan(0))})}),Ir({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})});var oi=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.bool)(!1).toVar(),a=(0,o.vec3)(0,1,0).toVar(),s=(0,o.vec3)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.float)(0).toVar(),u=(0,o.int)(3).toVar(),d=e.position.sub(t).toVar(),f=(0,o.length)(d).toVar();return(0,o.If)(f.greaterThanEqual(1e-10),()=>{let t=d.div(f).toVar(),n=(0,o.dot)(t.negate(),e.direction).toVar(),u=(0,o.cos)(e.angle).toVar();a.assign(t),c.assign(f),l.assign(r),i.assign(n.greaterThanEqual(u)),(0,o.If)(i,()=>{let t=Wr({coneCosine:u,penumbraCosine:(0,o.cos)(e.angle.mul((0,o.float)(1).sub(e.penumbra))).max(u.add(1e-5)).toVar(),angleCosine:n}),r=Ur({lightDistance:f,cutoffDistance:e.distance,decayExponent:e.decay});s.assign(e.color.mul(e.intensity).mul(r).mul(t))})}),Ir({valid:i,direction:a,emission:s,distance:c,pdf:l,lightType:u})}),si=(0,o.Fn)(([e,t,n])=>{let r=(0,o.bool)(!1).toVar(),i=(0,o.vec3)(0,1,0).toVar(),a=(0,o.vec3)(0).toVar(),s=(0,o.float)(0).toVar(),c=(0,o.float)(0).toVar(),l=(0,o.int)(2).toVar(),u=e.position.sub(t).toVar(),d=(0,o.length)(u).toVar();return(0,o.If)(d.greaterThanEqual(1e-10),()=>{let t=u.div(d).toVar(),f=Ur({lightDistance:d,cutoffDistance:e.distance,decayExponent:e.decay});l.assign((0,o.int)(2)),i.assign(t),s.assign(d),a.assign(e.color.mul(e.intensity).mul(f)),c.assign(n),r.assign((0,o.bool)(!0))}),Ir({valid:r,direction:i,emission:a,distance:s,pdf:c,lightType:l})}),ci=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m])=>{let h=(0,o.bool)(!1).toVar(),g=(0,o.vec3)(0,1,0).toVar(),_=(0,o.vec3)(0).toVar(),v=(0,o.float)(0).toVar(),y=(0,o.float)(0).toVar(),b=(0,o.int)(2).toVar(),x=c.add(u).add(f).add(m).toVar();return(0,o.If)(x.greaterThan((0,o.int)(0)),()=>{let S=(0,o.float)(0).toVar(),C=(0,o.int)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:c,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let a=Mr.wrap(Rr(s,r));S.addAssign($r(a,e,t,n,i)),C.addAssign(1)})})}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:u,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Nr.wrap(zr(l,r)),a=(0,o.select)(i.intensity.greaterThan(0),ei(i,e,t,n),(0,o.float)(0));S.addAssign(a),C.addAssign(1)})})}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:f,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Pr.wrap(Br(d,r));S.addAssign(ti(i,e,t,n)),C.addAssign(1)})})}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)),()=>{let i=Fr.wrap(Vr(p,r));S.addAssign(ni(i,e,t,n)),C.addAssign(1)})})}),(0,o.If)(S.lessThanEqual(0),()=>{let t=(0,o.int)(r.x.mul((0,o.float)(x)).toVar()).toVar(),n=(0,o.float)(1).div((0,o.max)((0,o.float)(x),1)).toVar();y.assign(n);let i=(0,o.bool)(!1).toVar(),S=(0,o.int)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(c))),()=>{let e=Mr.wrap(Rr(s,t.sub(S)));(0,o.If)(e.intensity.greaterThan(0),()=>{g.assign((0,o.normalize)(e.direction)),_.assign(e.color.mul(e.intensity)),v.assign(1e6),b.assign((0,o.int)(0)),h.assign((0,o.bool)(!0)),i.assign((0,o.bool)(!0))})}),S.addAssign(c)}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(u))),()=>{let s=Nr.wrap(zr(l,t.sub(S)));(0,o.If)(s.intensity.greaterThan(0),()=>{let t=(0,o.vec2)(r.y,F(a)).toVar(),c=Ir.wrap(ai(s,e,t,n));h.assign(c.valid),g.assign(c.direction),_.assign(c.emission),v.assign(c.distance),y.assign(c.pdf),b.assign(c.lightType),i.assign((0,o.bool)(!0))})}),S.addAssign(u)}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(f))),()=>{let r=Pr.wrap(Br(d,t.sub(S)));(0,o.If)(r.intensity.greaterThan(0),()=>{let t=Ir.wrap(si(r,e,n));h.assign(t.valid),g.assign(t.direction),_.assign(t.emission),v.assign(t.distance),y.assign(t.pdf),b.assign(t.lightType),i.assign((0,o.bool)(!0))})}),S.addAssign(f)}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.If)(i.not().and(t.greaterThanEqual(S)).and(t.lessThan(S.add(m))),()=>{let s=Fr.wrap(Vr(p,t.sub(S)));(0,o.If)(s.intensity.greaterThan(0),()=>{let t=(0,o.vec2)(r.y,F(a)).toVar(),c=Ir.wrap(oi(s,e,t,n));h.assign(c.valid),g.assign(c.direction),_.assign(c.emission),v.assign(c.distance),y.assign(c.pdf),b.assign(c.lightType),i.assign((0,o.bool)(!0))})})})}).Else(()=>{let x=r.x.mul(S).toVar(),w=(0,o.float)(0).toVar();C.assign(0);let T=(0,o.int)(-1).toVar(),E=(0,o.int)(-1).toVar(),D=(0,o.float)(0).toVar();(0,o.If)(c.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:c,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let a=$r(Mr.wrap(Rr(s,r)),e,t,n,i).toVar(),c=w.toVar();w.addAssign(a),(0,o.If)(x.greaterThan(c).and(x.lessThanEqual(w)),()=>{T.assign(0),E.assign(r),D.assign(a)})}),C.addAssign(1)})}),(0,o.If)(u.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:u,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=Nr.wrap(zr(l,r)),a=(0,o.select)(i.intensity.greaterThan(0),ei(i,e,t,n),(0,o.float)(0)).toVar(),s=w.toVar();w.addAssign(a),(0,o.If)(x.greaterThan(s).and(x.lessThanEqual(w)),()=>{T.assign(1),E.assign(r),D.assign(a)})}),C.addAssign(1)})}),(0,o.If)(f.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:f,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=ti(Pr.wrap(Br(d,r)),e,t,n).toVar(),a=w.toVar();w.addAssign(i),(0,o.If)(x.greaterThan(a).and(x.lessThanEqual(w)),()=>{T.assign(2),E.assign(r),D.assign(i)})}),C.addAssign(1)})}),(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{(0,o.If)(C.lessThan((0,o.int)(16)).and(T.lessThan((0,o.int)(0))),()=>{let i=ni(Fr.wrap(Vr(p,r)),e,t,n).toVar(),a=w.toVar();w.addAssign(i),(0,o.If)(x.greaterThan(a).and(x.lessThanEqual(w)),()=>{T.assign(3),E.assign(r),D.assign(i)})}),C.addAssign(1)})});let O=D.div((0,o.max)(S,1e-10)).toVar();(0,o.If)(T.equal((0,o.int)(0)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let e=Mr.wrap(Rr(s,E)),t=(0,o.normalize)(e.direction).toVar(),n=(0,o.float)(1).toVar();(0,o.If)(e.angle.greaterThan(0),()=>{let i=(0,o.cos)(e.angle.mul(.5)).toVar(),s=(0,o.mix)(i,(0,o.float)(1),r.y).toVar(),c=(0,o.sqrt)((0,o.max)((0,o.float)(0),(0,o.float)(1).sub(s.mul(s)))).toVar(),l=(0,o.float)(ii).mul(F(a)).toVar(),u=(0,o.normalize)(e.direction).toVar(),d=(0,o.normalize)((0,o.cross)((0,o.select)((0,o.abs)(u.x).greaterThan(.9),(0,o.vec3)(0,1,0),(0,o.vec3)(1,0,0)),u)).toVar(),f=(0,o.cross)(u,d).toVar();t.assign((0,o.normalize)(u.mul(s).add(d.mul((0,o.cos)(l)).add(f.mul((0,o.sin)(l))).mul(c))));let p=(0,o.float)(ii).mul((0,o.max)((0,o.float)(1).sub(i),1e-10)).toVar();n.assign((0,o.float)(1).div(p))}),g.assign(t),_.assign(e.color.mul(e.intensity)),v.assign(1e6),y.assign(n.mul(O)),b.assign((0,o.int)(0)),h.assign((0,o.bool)(!0))}),(0,o.If)(T.equal((0,o.int)(1)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Nr.wrap(zr(l,E)),n=(0,o.vec2)(r.y,F(a)).toVar(),i=Ir.wrap(ai(t,e,n,O));h.assign(i.valid),g.assign(i.direction),_.assign(i.emission),v.assign(i.distance),y.assign(i.pdf),b.assign(i.lightType)}),(0,o.If)(T.equal((0,o.int)(2)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Pr.wrap(Br(d,E)),n=Ir.wrap(si(t,e,O));h.assign(n.valid),g.assign(n.direction),_.assign(n.emission),v.assign(n.distance),y.assign(n.pdf),b.assign(n.lightType)}),(0,o.If)(T.equal((0,o.int)(3)).and(E.greaterThanEqual((0,o.int)(0))),()=>{let t=Fr.wrap(Vr(p,E)),n=(0,o.vec2)(r.y,F(a)).toVar(),i=Ir.wrap(oi(t,e,n,O));h.assign(i.valid),g.assign(i.direction),_.assign(i.emission),v.assign(i.distance),y.assign(i.pdf),b.assign(i.lightType)})})}),Ir({valid:h,direction:g,emission:_,distance:v,pdf:y,lightType:b})}),li=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.max)((0,o.float)(0),(0,o.dot)(n,e)).toVar(),a=(0,o.max)((0,o.float)(0),(0,o.dot)(n,t)).toVar(),s=(0,o.normalize)(e.add(t)).toVar(),c=(0,o.max)((0,o.float)(0),(0,o.dot)(n,s)).toVar();(0,o.max)((0,o.float)(0),(0,o.dot)(e,s)).toVar();let l=(0,o.float)(1).sub(r.metalness).mul((0,o.float)(1).sub(r.transmission)).toVar(),u=(0,o.float)(1).sub(l.mul((0,o.float)(1).sub(r.metalness))).toVar(),d=l.add(u).toVar(),f=(0,o.float)(0).toVar();return(0,o.If)(d.greaterThan(0),()=>{let e=(0,o.float)(1).div((0,o.max)(d,1e-10)).toVar();l.mulAssign(e),u.mulAssign(e),(0,o.If)(l.greaterThan(0).and(a.greaterThan(0)),()=>{f.addAssign(l.mul(a).mul(Lt))}),(0,o.If)(u.greaterThan(0).and(a.greaterThan(0)),()=>{let e=(0,o.max)(r.roughness,.02).toVar();f.addAssign(u.mul(or(c,i,e)))})}),(0,o.max)(f,1e-8)});(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d])=>{let f=(0,o.vec3)(0).toVar(),p=(0,o.vec2)(F(c).toVar(),F(c).toVar()).toVar(),m=e.position.add(e.u.mul(p.x.mul(2).sub(1))).add(e.v.mul(p.y.mul(2).sub(1))).toVar().sub(a).toVar(),h=(0,o.dot)(m,m).toVar();return(0,o.If)(h.greaterThanEqual(1e-10),()=>{let n=(0,o.sqrt)(h).toVar(),s=m.div(n).toVar(),p=(0,o.normalize)((0,o.cross)(e.u,e.v)).toVar(),g=(0,o.dot)(s.negate(),p).toVar();(0,o.If)(g.greaterThan(0),()=>{let p=(0,o.dot)(r,s).toVar();(0,o.If)(p.greaterThan(0),()=>{(0,o.If)(Hr({direction:s,surfaceNormal:r}),()=>{let m=Zr(a,s,n.sub(.001),c,yn,l,u,d);(0,o.If)(m.greaterThan(0),()=>{let n=Or(t,s,r,i),a=h.div((0,o.max)(e.area.mul(g),J)).toVar(),c=li(t,s,r,i).toVar(),l=(0,o.select)(c.greaterThan(0),Jt({pdf1:a,pdf2:c}),(0,o.float)(1)).toVar(),u=e.color.mul(e.intensity).toVar();f.assign(u.mul(n).mul(p).mul(m).mul(l).div((0,o.max)(a,Vt)))})})})})}),f});var ui=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k])=>{let A=(0,o.vec3)(0).toVar(),j=e.add(t.mul(.001)).toVar();return(0,o.If)(n.emissiveIntensity.lessThanEqual(10),()=>{let c=(0,o.vec3)(1).toVar(),M=Ft.wrap(tn(n.roughness,n.metalness,n.transmission,l,c)),N=M.useBRDFSampling.toVar(),ee=M.useLightSampling.toVar(),te=M.brdfWeight.toVar(),P=M.lightWeight.toVar(),ne=f.add(m).add(g).add(v).toVar(),re=(0,o.float)(.001).mul((0,o.float)(1).add((0,o.float)(l).mul(.5))).toVar(),ie=ne.greaterThan((0,o.int)(0)).toVar(),ae=(0,o.float)(0).toVar();(0,o.If)(ee.and(ie),()=>{ae.addAssign(P)}),(0,o.If)(N,()=>{ae.addAssign(te)}),(0,o.If)(ae.lessThanEqual(0),()=>{ae.assign(1),N.assign((0,o.bool)(!0)),te.assign(1)});let oe=F(u).toVar(),se=F(u).toVar(),ce=oe,le=(0,o.bool)(!1).toVar(),ue=(0,o.bool)(!1).toVar(),de=(0,o.select)(ie,P,(0,o.float)(0)).toVar(),fe=(0,o.float)(1).div((0,o.max)(ae,1e-10)).toVar(),pe=de.mul(fe).toVar();(0,o.If)(ce.lessThan(pe).and(ee).and(ie),()=>{le.assign((0,o.bool)(!0))}).ElseIf(N,()=>{ue.assign((0,o.bool)(!0))}).ElseIf(ie,()=>{le.assign((0,o.bool)(!0))}),(0,o.If)(le,()=>{let e=(0,o.vec2)(se,F(u)).toVar(),i=Ir.wrap(ci(j,t,n,e,l,u,d,f,p,m,h,g,_,v));(0,o.If)(i.valid.and(i.pdf.greaterThan(0)),()=>{let e=(0,o.max)((0,o.float)(0),(0,o.dot)(t,i.direction)).toVar(),a=i.emission.x.add(i.emission.y).add(i.emission.z).toVar();(0,o.If)(e.greaterThan(0).and(a.mul(e).greaterThan(re)).and(Hr({direction:i.direction,surfaceNormal:t})),()=>{let a=(0,o.min)(i.distance.sub(.001),(0,o.float)(1e3)).toVar(),s=Zr(j,i.direction,a,u,yn,y,b,x);(0,o.If)(s.greaterThan(0),()=>{let a=Or(r,i.direction,t,n),c=li(r,i.direction,t,n).toVar(),l=(0,o.float)(1).toVar();(0,o.If)(c.greaterThan(0).and(N),()=>{let e=i.pdf.mul(P).toVar(),t=c.mul(te).toVar();(0,o.If)(i.lightType.equal((0,o.int)(1)),()=>{l.assign(Jt({pdf1:e,pdf2:t}))})});let u=i.emission.mul(a).mul(e).mul(s).mul(l).div((0,o.max)(i.pdf,1e-10));A.addAssign(u.mul(ae).div((0,o.max)(P,1e-10)))})})})}),(0,o.If)(ue,()=>{(0,o.If)(a.greaterThan(0).and(N),()=>{let r=(0,o.max)((0,o.float)(0),(0,o.dot)(t,i)).toVar();(0,o.If)(r.greaterThan(0).and(Hr({direction:i,surfaceNormal:t})),()=>{(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{let c=(0,o.bool)(!1).toVar(),l=(0,o.float)(0).toVar(),d=(0,o.int)(-1).toVar();(0,o.Loop)({start:(0,o.int)(0),end:m,type:`int`,condition:`<`},({i:r})=>{let a=Nr.wrap(zr(p,r));(0,o.If)(a.intensity.greaterThan(0),()=>{let s=ei(a,e,t,n).toVar();(0,o.If)(s.greaterThanEqual(re),()=>{(0,o.If)(Kr(a,j,i).toVar().greaterThan(0),()=>{(0,o.If)(s.greaterThan(l),()=>{l.assign(s),d.assign(r)}),c.assign((0,o.bool)(!0))})})})}),(0,o.If)(c.and(d.greaterThanEqual((0,o.int)(0))),()=>{let e=Nr.wrap(zr(p,d)),t=Kr(e,j,i).toVar();(0,o.If)(t.greaterThan(0),()=>{let n=Zr(j,i,(0,o.min)(t.sub(.001),(0,o.float)(1e3)).toVar(),u,yn,y,b,x);(0,o.If)(n.greaterThan(0),()=>{let c=(0,o.max)((0,o.float)(0),(0,o.dot)(i,e.normal).negate()).toVar();(0,o.If)(c.greaterThan(0),()=>{let i=t.mul(t).toVar().div((0,o.max)(e.area.mul(c),J)).toVar();i.divAssign((0,o.max)((0,o.float)(ne),1));let l=Jt({pdf1:a.mul(te).toVar(),pdf2:i.mul(P).toVar()}).toVar(),u=e.color.mul(e.intensity).toVar().mul(s).mul(r).mul(n).mul(l).div((0,o.max)(a,1e-10));A.addAssign(u.mul(ae).div((0,o.max)(te,1e-10)))})})})})})})})}),(0,o.If)(k,()=>{let e=(0,o.vec2)(F(u).toVar(),F(u).toVar()).toVar(),i=(0,o.vec3)(0).toVar(),a=Tn(S,T,E,w,C,D,O,e,i).toVar(),s=a.xyz.toVar(),c=a.w.toVar();(0,o.If)(c.greaterThan(0),()=>{let e=(0,o.max)((0,o.float)(0),(0,o.dot)(t,s)).toVar();(0,o.If)(e.greaterThan(0).and(Hr({direction:s,surfaceNormal:t})),()=>{let a=Zr(j,s,(0,o.float)(1e3),u,yn,y,b,x);(0,o.If)(a.greaterThan(0),()=>{let l=Or(r,s,t,n),u=li(r,s,t,n).toVar(),d=(0,o.select)(u.greaterThan(0),Jt({pdf1:c,pdf2:u}),(0,o.float)(1)).toVar(),f=i.mul(l).mul(e).mul(a).mul(d).div((0,o.max)(c,1e-10));A.addAssign(f)})})})})}),A}),di=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=(0,o.select)(a,r,(0,o.float)(1).div(r)).toVar(),c=e.add(t.mul(s)).toVar(),l=(0,o.dot)(c,c).toVar(),u=(0,o.select)(l.greaterThan(J),c.div((0,o.sqrt)(l)),n).toVar();(0,o.If)((0,o.dot)(u,n).lessThan(0),()=>{u.assign(u.negate())});let d=(0,o.abs)((0,o.dot)(e,u)).toVar(),f=(0,o.abs)((0,o.dot)(t,u)).toVar(),p=(0,o.abs)((0,o.dot)(n,u)).toVar(),m=$n(p,i).toVar(),h=d.add(f.mul(s)).toVar(),g=h.mul(h).toVar(),_=f.mul(s).mul(s).div((0,o.max)(g,J)).toVar();return m.mul(p).mul(_)}),fi=(0,o.Fn)(([e,t,n,r])=>{let i=e.add(t).toVar(),a=(0,o.dot)(i,i).toVar();return or((0,o.max)((0,o.dot)(n,(0,o.select)(a.greaterThan(J),i.div((0,o.sqrt)(a)),n).toVar()),0).toVar(),(0,o.max)((0,o.dot)(n,e),0).toVar(),r)}),pi=(0,o.Fn)(([e,t,n,r,i])=>{let a=e.specularImportance.toVar(),s=a.greaterThan(.001).toVar(),c=e.diffuseImportance.toVar(),l=c.greaterThan(.001).toVar(),u=e.transmissionImportance.toVar(),d=u.greaterThan(.001).toVar(),f=e.clearcoatImportance.toVar(),p=f.greaterThan(.001).toVar(),m=a.add(c).add(u).add(f).toVar();return(0,o.If)(m.lessThan(.001),()=>{a.assign(0),c.assign(1),u.assign(0),f.assign(0),m.assign(1),s.assign((0,o.bool)(!1)),l.assign((0,o.bool)(!0)),d.assign((0,o.bool)(!1)),p.assign((0,o.bool)(!1))}).Else(()=>{let e=(0,o.float)(1).div(m).toVar();a.mulAssign(e),c.mulAssign(e),u.mulAssign(e),f.mulAssign(e),m.assign(1)}),Pt({envWeight:(0,o.float)(0),specularWeight:a,diffuseWeight:c,transmissionWeight:u,clearcoatWeight:f,totalWeight:m,useEnv:(0,o.bool)(!1),useSpecular:s,useDiffuse:l,useTransmission:d,useClearcoat:p})}),mi=(0,o.Fn)(([e,t])=>{let n=(0,o.int)(2).toVar(),r=(0,o.float)(1).toVar(),i=(0,o.float)(0).toVar(),a=(0,o.bool)(!1).toVar();return(0,o.If)(e.useSpecular.and(a.not()),()=>{i.addAssign(e.specularWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(1),r.assign(e.specularWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useDiffuse.and(a.not()),()=>{i.addAssign(e.diffuseWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(2),r.assign(e.diffuseWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useTransmission.and(a.not()),()=>{i.addAssign(e.transmissionWeight),(0,o.If)(t.lessThan(i),()=>{n.assign(3),r.assign(e.transmissionWeight),a.assign((0,o.bool)(!0))})}),(0,o.If)(e.useClearcoat.and(a.not()),()=>{n.assign(4),r.assign(e.clearcoatWeight),a.assign((0,o.bool)(!0))}),(0,o.If)(a.not(),()=>{n.assign(2),r.assign((0,o.select)(e.useDiffuse,e.diffuseWeight,(0,o.float)(1)))}),(0,o.vec2)((0,o.float)(n),r)}),hi=(0,o.Fn)(([e])=>(0,o.max)(e,0).mul(Lt)),gi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y])=>{let b=(0,o.vec3)(0).toVar(),x=(0,o.vec3)(0).toVar(),S=(0,o.float)(0).toVar(),C=(0,o.float)(0).toVar(),w=(0,o.float)(0).toVar();return(0,o.If)(u.diffuseImportance.greaterThanEqual(0).and(u.specularImportance.greaterThanEqual(0)).and(u.transmissionImportance.greaterThanEqual(0)).and(u.clearcoatImportance.greaterThanEqual(0)).and(u.envmapImportance.greaterThanEqual(0)).toVar().not(),()=>{let e=(0,o.vec2)(F(l).toVar(),F(l).toVar()).toVar();b.assign(mr(t,e)),x.assign(n.color.xyz),S.assign(1),C.assign(1)}).Else(()=>{let s=Pt.wrap(pi(u,c,n,v,y).toVar()),d=F(l).toVar(),f=(0,o.vec2)(F(l).toVar(),F(l).toVar()).toVar(),p=mi(s,d).toVar(),m=(0,o.int)(p.x).toVar();p.y.toVar();let h=(0,o.vec3)(0).toVar(),g=(0,o.float)(0).toVar(),_=(0,o.vec3)(0).toVar();(0,o.If)(m.equal((0,o.int)(1)),()=>{h.assign(r),g.assign(i),_.assign(a)}).ElseIf(m.equal((0,o.int)(2)),()=>{h.assign(mr(t,f)),g.assign(hi((0,o.max)((0,o.dot)(t,h),0))),_.assign(Or(e,h,t,n))}).ElseIf(m.equal((0,o.int)(3)),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),i=xr.wrap(Tr(e,t,n.ior,n.roughness,r,n.dispersion,f,l).toVar());h.assign(i.direction),g.assign(i.pdf),_.assign(Or(e,h,t,n))}).Else(()=>{h.assign(r),g.assign(i),_.assign(a)});let T=(0,o.dot)(t,h).toVar(),E=(0,o.max)(T,0).toVar(),D=(0,o.abs)(T).toVar(),O=(0,o.float)(0).toVar();(0,o.If)(s.useSpecular,()=>{let r=or((0,o.max)((0,o.dot)(t,(0,o.normalize)(e.add(h))),.001),(0,o.max)((0,o.dot)(t,e),.001),n.roughness);O.addAssign(s.specularWeight.mul(r))}),(0,o.If)(s.useDiffuse,()=>{let e=hi(E).toVar();O.addAssign(s.diffuseWeight.mul(e))}),(0,o.If)(s.useTransmission.and(n.transmission.greaterThan(0)),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),i=di(e,h,t,n.ior,n.roughness,r).toVar();O.addAssign(s.transmissionWeight.mul(i))}),(0,o.If)(s.useClearcoat.and(n.clearcoat.greaterThan(0)),()=>{let r=fi(e,h,t,n.clearcoatRoughness).toVar();O.addAssign(s.clearcoatWeight.mul(r))}),g.assign((0,o.max)(g,Vt)),O.assign((0,o.max)(O,Vt));let k=g.div(O).toVar(),A=(0,o.select)(m.equal((0,o.int)(3)),D,E),j=_.mul(A).mul(k).div(g).toVar();b.assign(h),x.assign(j),S.assign(k),C.assign(g),w.assign(O)}),Lr({direction:b,throughput:x,misWeight:S,pdf:C,combinedPdf:w})}),_i=K({position:`vec3`,normal:`vec3`,emission:`vec3`,direction:`vec3`,distance:`float`,pdf:`float`,area:`float`,cosThetaLight:`float`,valid:`bool`}),vi=K({contribution:`vec3`,hasEmissive:`bool`,emissionOnly:`vec3`,distance:`float`}),yi=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.sqrt)(r.x),a=(0,o.float)(1).sub(i),s=r.y.mul(i),c=(0,o.float)(1).sub(a).sub(s);return e.mul(a).add(t.mul(s)).add(n.mul(c))}),bi=(0,o.Fn)(([e,t,n])=>(0,o.length)((0,o.cross)(t.sub(e),n.sub(e))).mul(.5)),xi=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.normalize)(e.sub(r)),a=(0,o.normalize)(t.sub(r)),s=(0,o.normalize)(n.sub(r)),c=(0,o.abs)((0,o.dot)(i,(0,o.cross)(a,s))),l=(0,o.float)(1).add((0,o.dot)(a,s)).add((0,o.dot)(i,s)).add((0,o.dot)(i,a));return(0,o.max)((0,o.float)(2).mul((0,o.atan)(c,(0,o.max)(l,(0,o.float)(1e-10)))),(0,o.float)(0))}),Si=(0,o.Fn)(([e,t,n,r])=>{let i=t.sub(e),a=n.sub(e),s=n.sub(t),c=(0,o.max)((0,o.dot)(i,i),(0,o.max)((0,o.dot)(a,a),(0,o.dot)(s,s))),l=(0,o.cross)(i,a),u=(0,o.dot)(l,l),d=(0,o.bool)(!1).toVar();return(0,o.If)(u.greaterThan(1e-20),()=>{let t=(0,o.dot)(l,r.sub(e)),n=t.mul(t).div(u);d.assign(c.greaterThan(n))}),d}),Ci=K({direction:`vec3`,position:`vec3`,solidAngle:`float`,valid:`bool`}),wi=(0,o.Fn)(([e])=>{let t=(0,o.length)(e);return(0,o.select)(t.greaterThan(1e-10),e.div(t),(0,o.vec3)(0))}),Ti=(0,o.Fn)(([e,t,n,r,i])=>{let a=Ci({direction:(0,o.vec3)(0),position:(0,o.vec3)(0),solidAngle:(0,o.float)(0),valid:!1}).toVar(),s=(0,o.normalize)(e.sub(r)),c=(0,o.normalize)(t.sub(r)),l=(0,o.normalize)(n.sub(r)),u=xi(e,t,n,r);return a.solidAngle.assign(u),(0,o.If)(u.greaterThan(1e-7),()=>{let d=(0,o.clamp)((0,o.dot)(wi((0,o.cross)(s,c)),wi((0,o.cross)(s,l))),-1,1),f=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(d.mul(d)),0)),p=(0,o.acos)(d),m=i.x.mul(u).sub(p),h=(0,o.sin)(m),g=(0,o.cos)(m),_=(0,o.clamp)((0,o.dot)(s,c),-1,1),v=g.sub(d),y=h.add(f.mul(_)),b=y.mul(g).sub(v.mul(h)).mul(d).sub(y),x=y.mul(h).add(v.mul(g)).mul(f),S=(0,o.clamp)((0,o.select)((0,o.abs)(x).greaterThan(1e-10),b.div(x),(0,o.float)(1)),-1,1),C=(0,o.dot)(l,s),w=wi(l.sub(s.mul(C))),T=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(S.mul(S)),0)),E=(0,o.normalize)(s.mul(S).add(w.mul(T))),D=(0,o.dot)(E,c),O=(0,o.float)(1).sub(i.y.mul((0,o.float)(1).sub(D))),k=(0,o.sqrt)((0,o.max)((0,o.float)(1).sub(O.mul(O)),0)),A=wi(E.sub(c.mul(D))),j=(0,o.normalize)(c.mul(O).add(A.mul(k))),M=(0,o.normalize)((0,o.cross)(t.sub(e),n.sub(e))),N=(0,o.dot)(M,j);(0,o.If)((0,o.abs)(N).greaterThan(1e-10),()=>{let t=(0,o.dot)(M,e.sub(r)).div(N);(0,o.If)(t.greaterThan(0),()=>{a.direction.assign(j),a.position.assign(r.add(j.mul(t))),a.valid.assign(!0)})})}),a}),Ei=(0,o.Fn)(([e,t,n,r])=>{let i=n.sub(t),a=r.sub(t),s=e.sub(t),c=(0,o.dot)(i,i),l=(0,o.dot)(i,a),u=(0,o.dot)(a,a),d=(0,o.dot)(s,i),f=(0,o.dot)(s,a),p=(0,o.float)(1).div((0,o.max)(c.mul(u).sub(l.mul(l)),(0,o.float)(1e-10))),m=u.mul(d).sub(l.mul(f)).mul(p),h=c.mul(f).sub(l.mul(d)).mul(p);return(0,o.vec3)((0,o.float)(1).sub(m).sub(h),m,h)}),Di=(0,o.Fn)(([e,t,n,r])=>{let i=(0,o.sqrt)(r.x),a=(0,o.float)(1).sub(i),s=r.y.mul(i),c=(0,o.float)(1).sub(a).sub(s);return(0,o.normalize)(e.mul(a).add(t.mul(s)).add(n.mul(c)))}),Oi=(0,o.Fn)(([e])=>e.emissiveIntensity.greaterThan(0).and((0,o.length)(e.emissive).greaterThan(0)));(0,o.Fn)(([e,t])=>{let n=(0,o.float)(0).toVar();return(0,o.If)(Oi(e),()=>{let r=e.emissive.x.add(e.emissive.y).add(e.emissive.z).div(3);n.assign(r.mul(e.emissiveIntensity).mul(t))}),n});var ki=8,Ai=2,ji=K({v0:`vec3`,v1:`vec3`,v2:`vec3`,n0:`vec3`,n1:`vec3`,n2:`vec3`,materialIndex:`int`}),Mi=(0,o.Fn)(([e,t])=>{let n=Z(t,e,(0,o.int)(0),(0,o.int)(ki)),r=Z(t,e,(0,o.int)(1),(0,o.int)(ki)),i=Z(t,e,(0,o.int)(2),(0,o.int)(ki)),a=Z(t,e,(0,o.int)(3),(0,o.int)(ki)),s=Z(t,e,(0,o.int)(4),(0,o.int)(ki)),c=Z(t,e,(0,o.int)(5),(0,o.int)(ki)),l=Z(t,e,(0,o.int)(7),(0,o.int)(ki));return ji({v0:n.xyz,v1:r.xyz,v2:i.xyz,n0:a.xyz,n1:s.xyz,n2:c.xyz,materialIndex:(0,o.int)(l.z)})}),Ni=(0,o.Fn)(([e,t,n,r,i,a,s])=>{let c=ji.wrap(Mi(e,i)),l=bi(c.v0,c.v1,c.v2),u=Z(a,c.materialIndex,(0,o.int)(Ut.EMISSIVE_ROUGHNESS),Y),d=Z(a,c.materialIndex,(0,o.int)(Ut.IOR_TRANSMISSION),Y),f=(0,o.max)(u.x.add(u.y).add(u.z).div(3).mul(d.a).mul(l),(0,o.float)(1e-10)).div((0,o.max)(s,(0,o.float)(1e-10))),p=(0,o.float)(0).toVar();return(0,o.If)(Si(c.v0,c.v1,c.v2,r),()=>{let e=xi(c.v0,c.v1,c.v2,r);p.assign(f.div((0,o.max)(e,(0,o.float)(1e-10))))}).Else(()=>{let e=(0,o.normalize)((0,o.cross)(c.v1.sub(c.v0),c.v2.sub(c.v0))),r=(0,o.max)((0,o.dot)(n.negate(),e),.001),i=t.mul(t),a=f.div(l);p.assign(a.mul(i).div(r))}),(0,o.max)(p,Vt)}),Pi=(0,o.Fn)(([e,t,n])=>{let r=(0,o.int)(0).toVar(),i=t.sub(1).toVar();return(0,o.Loop)(r.lessThan(i),()=>{let t=r.add(i).div(2).toVar(),a=e.element(t.mul(Ai)).b;(0,o.If)(a.lessThan(n),()=>{r.assign(t.add(1))}).Else(()=>{i.assign(t)})}),r}),Fi=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=_i({position:(0,o.vec3)(0),normal:(0,o.vec3)(0),emission:(0,o.vec3)(0),direction:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),area:(0,o.float)(0),cosThetaLight:(0,o.float)(0),valid:!1}).toVar();return(0,o.If)(a.greaterThan((0,o.int)(0)),()=>{let n=Pi(i,a,F(r)).toVar().mul(Ai),u=i.element(n),d=i.element(n.add(1)),f=(0,o.int)(u.r),p=(0,o.max)(u.g,(0,o.float)(1e-10)),m=d.xyz,h=d.w,g=ji.wrap(Mi(f,c)),_=(0,o.vec2)(F(r).toVar(),F(r).toVar()),v=(0,o.normalize)((0,o.cross)(g.v1.sub(g.v0),g.v2.sub(g.v0)));(0,o.If)(Si(g.v0,g.v1,g.v2,e),()=>{let n=Ci.wrap(Ti(g.v0,g.v1,g.v2,e,_));(0,o.If)(n.valid.and(n.solidAngle.greaterThan(1e-7)),()=>{let r=n.direction,i=n.position,a=(0,o.dot)(r,t),c=(0,o.dot)(r,v.negate());(0,o.If)(a.greaterThan(0).and(c.greaterThan(0)),()=>{let t=Ei(i,g.v0,g.v1,g.v2),a=(0,o.normalize)(g.n0.mul(t.x).add(g.n1.mul(t.y)).add(g.n2.mul(t.z))),u=(0,o.length)(i.sub(e)),d=p.div((0,o.max)(s,(0,o.float)(1e-10))).div(n.solidAngle);l.position.assign(i),l.normal.assign(a),l.emission.assign(m),l.direction.assign(r),l.distance.assign(u),l.pdf.assign((0,o.max)(d,Vt)),l.area.assign(h),l.cosThetaLight.assign(c),l.valid.assign(!0)})})}).Else(()=>{let n=yi(g.v0,g.v1,g.v2,_),r=Di(g.n0,g.n1,g.n2,_),i=n.sub(e),a=(0,o.dot)(i,i),c=(0,o.sqrt)(a),u=i.div(c),d=(0,o.dot)(u,t),f=(0,o.dot)(u,r.negate());(0,o.If)(d.greaterThan(0).and(f.greaterThan(0)),()=>{let e=p.div((0,o.max)(s,(0,o.float)(1e-10)).mul(h)).mul(a).div(f);l.position.assign(n),l.normal.assign(r),l.emission.assign(m),l.direction.assign(u),l.distance.assign(c),l.pdf.assign((0,o.max)(e,Vt)),l.area.assign(h),l.cosThetaLight.assign(f),l.valid.assign(!0)})})}),l}),Ii=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h])=>{let g=vi({contribution:(0,o.vec3)(0),hasEmissive:!1,emissionOnly:(0,o.vec3)(0),distance:(0,o.float)(0)}).toVar();return(0,o.If)(a.greaterThan((0,o.int)(1)).and(r.roughness.greaterThan(.9)).and(r.metalness.lessThan(.1)).not(),()=>{let a=_i.wrap(Fi(e,t,i,s,l,u,d,f));(0,o.If)(a.valid.and(a.pdf.greaterThan(0)),()=>{g.hasEmissive.assign(!0),g.emissionOnly.assign(a.emission),g.distance.assign(a.distance);let i=(0,o.max)((0,o.float)(0),(0,o.dot)(t,a.direction));(0,o.If)(i.greaterThan(0),()=>{let l=h(e,t,r),u=e.add(l),d=a.distance.sub(.001),f=p(u,a.direction,d,s);(0,o.If)(f.greaterThan(0),()=>{let e=m(n,a.direction,t,r),s=li(n,a.direction,t,r),l=(0,o.select)(s.greaterThan(0),Jt({pdf1:a.pdf,pdf2:s}),(0,o.float)(1));g.contribution.assign(a.emission.mul(e).mul(i).div(a.pdf).mul(f).mul(c).mul(l))})})})}),g}),Li=(0,o.Fn)(([e,t,n,r,i,a,o,s,c,l,u,d,f,p,m])=>vi.wrap(Ii(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m)).contribution),Ri=4,zi=2,Bi=32,Vi=(0,o.Fn)(([e,t,n,r,i,a])=>{let s=_i({position:(0,o.vec3)(0),normal:(0,o.vec3)(0),emission:(0,o.vec3)(0),direction:(0,o.vec3)(0),distance:(0,o.float)(0),pdf:(0,o.float)(0),area:(0,o.float)(0),cosThetaLight:(0,o.float)(0),valid:!1}).toVar(),c=(0,o.float)(1).toVar(),l=(0,o.int)(0).toVar(),u=(0,o.bool)(!1).toVar();return(0,o.Loop)(Bi,()=>{let t=l.mul((0,o.int)(Ri)),i=r.element(t.add((0,o.int)(1))),a=r.element(t.add((0,o.int)(2)));(0,o.If)(i.w.greaterThan(.5),()=>{u.assign((0,o.bool)(!0)),(0,o.Break)()});let s=(0,o.int)(a.x),d=(0,o.int)(a.y),f=s.mul((0,o.int)(Ri)),p=r.element(f),m=r.element(f.add((0,o.int)(1))),h=d.mul((0,o.int)(Ri)),g=r.element(h),_=r.element(h.add((0,o.int)(1))),v=(0,o.vec3)(p.x.add(m.x).mul(.5),p.y.add(m.y).mul(.5),p.z.add(m.z).mul(.5)),y=(0,o.vec3)(g.x.add(_.x).mul(.5),g.y.add(_.y).mul(.5),g.z.add(_.z).mul(.5)),b=v.sub(e),x=y.sub(e),S=(0,o.max)((0,o.dot)(b,b),(0,o.float)(.01)),C=(0,o.max)((0,o.dot)(x,x),(0,o.float)(.01)),w=(0,o.max)(p.w,(0,o.float)(0)),T=(0,o.max)(g.w,(0,o.float)(0)),E=w.div(S),D=T.div(C),O=E.add(D);(0,o.If)(O.lessThanEqual((0,o.float)(0)),()=>{l.assign(s)}).Else(()=>{let e=E.div(O);(0,o.If)(F(n).lessThan(e),()=>{c.mulAssign(e),l.assign(s)}).Else(()=>{c.mulAssign((0,o.float)(1).sub(e)),l.assign(d)})})}),(0,o.If)(u,()=>{let u=l.mul((0,o.int)(Ri)),d=r.element(u),f=r.element(u.add((0,o.int)(2))),p=(0,o.int)(f.x),m=(0,o.int)(f.y),h=(0,o.max)(d.w,(0,o.float)(1e-10)),g=F(n).mul(h),_=(0,o.float)(0).toVar(),v=p.add(m.sub((0,o.int)(1))).toVar(),y=(0,o.float)(1e-10).toVar();(0,o.Loop)({start:(0,o.int)(0),end:m},({i:e})=>{let t=p.add(e),n=t.mul((0,o.int)(zi)),r=(0,o.max)(i.element(n).g,(0,o.float)(0));_.addAssign(r),(0,o.If)(_.greaterThanEqual(g).and(r.greaterThan((0,o.float)(0))),()=>{v.assign(t),y.assign(r),(0,o.Break)()})}),c.mulAssign(y.div(h));let b=v.mul((0,o.int)(zi)),x=i.element(b),S=i.element(b.add((0,o.int)(1))),C=(0,o.int)(x.r),w=S.xyz,T=S.w,E=ji.wrap(Mi(C,a)),D=(0,o.vec2)(F(n).toVar(),F(n).toVar()),O=(0,o.normalize)((0,o.cross)(E.v1.sub(E.v0),E.v2.sub(E.v0)));(0,o.If)(Si(E.v0,E.v1,E.v2,e),()=>{let n=Ci.wrap(Ti(E.v0,E.v1,E.v2,e,D));(0,o.If)(n.valid.and(n.solidAngle.greaterThan((0,o.float)(1e-7))),()=>{let r=n.direction,i=n.position,a=(0,o.dot)(r,t),l=(0,o.dot)(r,O.negate());(0,o.If)(a.greaterThan((0,o.float)(0)).and(l.greaterThan((0,o.float)(0))),()=>{let t=Ei(i,E.v0,E.v1,E.v2),a=(0,o.normalize)(E.n0.mul(t.x).add(E.n1.mul(t.y)).add(E.n2.mul(t.z))),u=(0,o.length)(i.sub(e)),d=c.div((0,o.max)(n.solidAngle,(0,o.float)(1e-10)));s.position.assign(i),s.normal.assign(a),s.emission.assign(w),s.direction.assign(r),s.distance.assign(u),s.pdf.assign((0,o.max)(d,Vt)),s.area.assign(T),s.cosThetaLight.assign(l),s.valid.assign(!0)})})}).Else(()=>{let n=yi(E.v0,E.v1,E.v2,D),r=Di(E.n0,E.n1,E.n2,D),i=n.sub(e),a=(0,o.dot)(i,i),l=(0,o.sqrt)(a),u=i.div(l),d=(0,o.dot)(u,t),f=(0,o.dot)(u,r.negate());(0,o.If)(d.greaterThan((0,o.float)(0)).and(f.greaterThan((0,o.float)(0))),()=>{let e=c.div((0,o.max)(T,(0,o.float)(1e-10))).mul(a).div(f);s.position.assign(n),s.normal.assign(r),s.emission.assign(w),s.direction.assign(u),s.distance.assign(l),s.pdf.assign((0,o.max)(e,Vt)),s.area.assign(T),s.cosThetaLight.assign(f),s.valid.assign(!0)})})}),s}),Hi=0,Ui=1,Wi=2,Gi=3,Ki=K({radiance:`vec4`,objectNormal:`vec3`,objectColor:`vec3`,objectID:`float`,firstHitPoint:`vec3`,firstHitDistance:`float`}),qi=(0,o.Fn)(([e,t,n,r,i])=>{let a=i.toVar();return(0,o.If)(n.not().or(r.notEqual(t)),()=>{a.assign(en(e.metalness,e.roughness,e.transmission,e.clearcoat,e.emissive))}),a}),Ji=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.vec3)(0).toVar(),h=(0,o.vec3)(0).toVar(),g=(0,o.float)(0).toVar(),_=jt.wrap(qi(n,r,s,c,l)).toVar(),v=d.toVar();(0,o.If)(u.not(),()=>{(0,o.If)(f,()=>{v.assign(lr(n,_,p))}).Else(()=>{let e=Nt({F0:Qn(n.ior),NoV:(0,o.float)(1),diffuseColor:(0,o.vec3)(0),specularColor:(0,o.vec3)(0),isMetallic:!1,isPurelyDiffuse:!1,hasSpecialFeatures:!1,alpha:(0,o.float)(0),k:(0,o.float)(0),alpha2:(0,o.float)(0),tsAlbedo:(0,o.vec4)(0),tsEmissive:(0,o.vec3)(0),tsMetalness:(0,o.float)(0),tsRoughness:(0,o.float)(0),tsNormal:(0,o.vec3)(0),tsHasTextures:!1,invRoughness:(0,o.float)(1).sub(n.roughness),metalFactor:(0,o.float)(.5).add((0,o.float)(.5).mul(n.metalness)),iorFactor:(0,o.min)((0,o.float)(2).div(n.ior),1),maxSheenColor:(0,o.max)(n.sheenColor.x,(0,o.max)(n.sheenColor.y,n.sheenColor.z))}).toVar();v.assign(lr(n,_,e))})});let y=i.x.toVar(),b=(0,o.vec2)(i.y,F(a)).toVar(),x=(0,o.vec3)(0).toVar(),S=v.diffuse.toVar(),C=S.add(v.specular).toVar(),w=C.add(v.sheen).toVar(),T=w.add(v.clearcoat).toVar(),E=(0,o.bool)(!1).toVar();(0,o.If)(y.lessThan(S).and(E.not()),()=>{m.assign(pr({N:t,xi:b}));let r=(0,o.clamp)((0,o.dot)(t,m),0,1);g.assign(r.mul(Lt)),h.assign(Or(e,m,t,n)),E.assign((0,o.bool)(!0))});let D=(0,o.clamp)((0,o.dot)(t,e),.001,1).toVar();return(0,o.If)(y.lessThan(C).and(E.not()),()=>{let r=Yt({N:t}),a=hr({V:r.transpose().mul(e).toVar(),roughness:n.roughness,Xi:i});x.assign(r.mul(a));let s=(0,o.clamp)((0,o.dot)(t,x),.001,1);m.assign((0,o.reflect)(e.negate(),x)),g.assign(or(s,D,n.roughness)),h.assign(Or(e,m,t,n)),E.assign((0,o.bool)(!0))}),(0,o.If)(y.lessThan(w).and(E.not()),()=>{x.assign(fr({N:t,roughness:n.sheenRoughness,Xi:i}));let r=(0,o.clamp)((0,o.dot)(t,x),.001,1),a=(0,o.clamp)((0,o.dot)(e,x),.001,1);m.assign((0,o.reflect)(e.negate(),x));let s=(0,o.dot)(t,m).toVar();(0,o.If)(s.lessThanEqual(0),()=>{m.assign(pr({N:t,xi:i})),s.assign((0,o.clamp)((0,o.dot)(t,m),0,1)),g.assign(s.mul(Lt)),h.assign(Or(e,m,t,n))}).Else(()=>{g.assign(er(r,n.sheenRoughness).mul(r).div((0,o.float)(4).mul(a))),g.assign((0,o.max)(g,Vt)),h.assign(Or(e,m,t,n))}),E.assign((0,o.bool)(!0))}),(0,o.If)(y.lessThan(T).and(E.not()),()=>{let r=(0,o.clamp)(n.clearcoatRoughness,Bt,1);x.assign(fr({N:t,roughness:r,Xi:i}));let a=(0,o.clamp)((0,o.dot)(t,x),0,1);m.assign((0,o.reflect)(e.negate(),x)),g.assign(or(a,D,r)),g.assign((0,o.max)(g,Vt)),h.assign(Or(e,m,t,n)),E.assign((0,o.bool)(!0))}),(0,o.If)(E.not(),()=>{let r=(0,o.dot)(e,t).greaterThan(0).toVar(),s=xr.wrap(Tr(e,t,n.ior,n.roughness,r,n.dispersion,i,a));m.assign(s.direction),g.assign((0,o.max)(s.pdf,Vt)),h.assign(Or(e,m,t,n))}),g.assign((0,o.max)(g,Vt)),Et({direction:m,value:h,pdf:g})}),Yi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l])=>{let u=(0,o.max)(Kt({v:e}),0).toVar(),d=jt.wrap(qi(n,r,i,a,s)).toVar(),f=d.complexityScore.toVar();(0,o.If)(d.isMetallic.and(d.isSmooth),()=>{f.addAssign(.15)}),(0,o.If)(d.isTransmissive.and(d.hasClearcoat),()=>{f.addAssign(.12)}),(0,o.If)(d.isEmissive,()=>{f.addAssign(.1)}),f.assign((0,o.clamp)(f,0,1));let p=(0,o.float)(.5).toVar();(0,o.If)(c.and(l).and(u.greaterThan(.01)),()=>{let e=(0,o.clamp)(t.y,0,1);p.assign((0,o.mix)((0,o.float)(.3),(0,o.float)(.8),e.mul(e)))});let m=(0,o.smoothstep)((0,o.float)(.001),(0,o.float)(.1),u);return u.mul((0,o.mix)(f.mul(.7),p,.3)).mul(m)}),Xi=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p])=>{let m=(0,o.float)(1).toVar();return(0,o.If)(e.greaterThanEqual((0,o.int)(3)),()=>{let h=(0,o.max)(Kt({v:t}),0).toVar();(0,o.If)(h.lessThan(8e-4).and(e.greaterThan((0,o.int)(4))),()=>{let e=(0,o.max)(h.mul(125),.01),t=F(a);m.assign((0,o.select)(t.lessThan(e),e,(0,o.float)(0)))}).Else(()=>{let g=jt.wrap(qi(n,r,s,c,l)).toVar(),_=g.complexityScore.toVar();(0,o.If)(g.isMetallic.and(g.isSmooth).and(e.lessThan((0,o.int)(7))),()=>{_.addAssign(.3)}),(0,o.If)(g.isTransmissive.and(e.lessThan((0,o.int)(6))),()=>{_.addAssign(.25)}),(0,o.If)(g.isEmissive.and(e.lessThan((0,o.int)(4))),()=>{_.addAssign(.15)}),_.assign((0,o.clamp)(_,0,1));let v=(0,o.int)(3).toVar();(0,o.If)(_.greaterThan(.6),()=>{v.assign(5)}).ElseIf(_.greaterThan(.4),()=>{v.assign(4)}),(0,o.If)(e.lessThan(v),()=>{m.assign(1)}).Else(()=>{let y=(0,o.float)(0).toVar();(0,o.If)(s.and(u),()=>{y.assign(d)}).Else(()=>{y.assign(Yi(t,i,n,r,s,c,l,f,p))});let b=(0,o.mix)((0,o.clamp)(_.mul(.4).add(h.mul(.6)).mul(1.2),.15,.95),(0,o.clamp)(h.mul(.4).add(_.mul(.1)),.03,.6),(0,o.clamp)((0,o.float)(e.sub(v)).div(10),0,1)).toVar();b.assign((0,o.mix)(b,(0,o.max)(b,y),.4)),(0,o.If)(_.greaterThan(.5),()=>{let e=_.sub(.5).mul(.6);b.assign((0,o.mix)(b,(0,o.float)(1),e))});let x=(0,o.float)(.12).add(_.mul(.08)),S=(0,o.exp)((0,o.float)(e.sub(v)).negate().mul(x));b.mulAssign(S);let C=(0,o.select)(g.isEmissive,(0,o.float)(.04),(0,o.float)(.02));b.assign((0,o.max)(b,C));let w=F(a);m.assign((0,o.select)(w.lessThan(b),b,(0,o.float)(0)))})})}),m}),Zi=(0,o.Fn)(([e,t,n,r,i,a,s,c])=>{let l=(0,o.vec4)(0).toVar();return(0,o.If)(e.and(s.not()),()=>{l.assign((0,o.vec4)(0))}).Else(()=>{let s=En({tex:n,samp:(0,o.sampler)(n),direction:t,environmentMatrix:r,environmentIntensity:i,enableEnvironmentLight:a});(0,o.If)(e,()=>{l.assign(s.mul(c))}).Else(()=>{l.assign(s)})}),l}),Qi=(0,o.wgslFn)(`
|
|
507
507
|
fn regularizePathContribution( contribution: vec3f, pathLength: f32, fireflyThreshold: f32, frame: i32 ) -> vec3f {
|
|
508
508
|
let threshold = calculateFireflyThreshold( fireflyThreshold, i32( pathLength ), frame );
|
|
509
509
|
return applySoftSuppressionRGB( contribution, threshold, 0.5f );
|
|
510
510
|
}
|
|
511
|
-
`,[
|
|
511
|
+
`,[Zt,$t]),$i=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee,te,P,ne,re,F,ie,ae,oe,se,ce,le,ue,de,fe,me])=>{let he=(0,o.vec3)(0).toVar(),I=(0,o.vec3)(1).toVar(),L=(0,o.float)(1).toVar(),ge=(0,o.bool)(!1).toVar(),_e=(0,o.float)(0).toVar(),R=(0,o.vec3)(0).toVar(),ve=(0,o.vec3)(0).toVar(),ye=(0,o.float)(-1e3).toVar(),be=e.origin.toVar(),z=(0,o.float)(1e10).toVar(),xe=(0,o.int)(0).toVar(),Se=(0,o.float)(1).toVar(),Ce=(0,o.float)(1).toVar(),we=(0,o.float)(1).toVar(),Te=M.toVar(),B=N.toVar(),Ee=(0,o.int)(Hi).toVar(),De=(0,o.bool)(!0).toVar(),Oe=(0,o.bool)(!1).toVar(),ke=(0,o.bool)(!1).toVar(),Ae=(0,o.bool)(!1).toVar();(0,o.bool)(!1).toVar();let V=(0,o.float)(0).toVar(),je=(0,o.int)(-1).toVar(),Me=jt({isMetallic:!1,isRough:!1,isSmooth:!1,isTransmissive:!1,hasClearcoat:!1,isEmissive:!1,complexityScore:(0,o.float)(0)}).toVar(),Ne=Dt({specular:(0,o.float)(.5),diffuse:(0,o.float)(.5),sheen:(0,o.float)(0),clearcoat:(0,o.float)(0),transmission:(0,o.float)(0),iridescence:(0,o.float)(0)}).toVar(),Pe=Nt({F0:(0,o.vec3)(.04),NoV:(0,o.float)(1),diffuseColor:(0,o.vec3)(0),specularColor:(0,o.vec3)(0),isMetallic:!1,isPurelyDiffuse:!1,hasSpecialFeatures:!1,alpha:(0,o.float)(0),k:(0,o.float)(0),alpha2:(0,o.float)(0),tsAlbedo:(0,o.vec4)(0),tsEmissive:(0,o.vec3)(0),tsMetalness:(0,o.float)(0),tsRoughness:(0,o.float)(0),tsNormal:(0,o.vec3)(0),tsHasTextures:!1,invRoughness:(0,o.float)(1),metalFactor:(0,o.float)(.5),iorFactor:(0,o.float)(1),maxSheenColor:(0,o.float)(0)}).toVar(),Fe=(0,o.int)(0).toVar(),Ie=e.origin.toVar(),H=e.direction.toVar();return(0,o.Loop)({start:(0,o.int)(0),end:M.add(N).add(1),type:`int`,condition:`<`},({i:e})=>{Te.assign(M.sub(Fe)),De.assign(e.equal((0,o.int)(0))),(0,o.If)(Fe.greaterThan(M),()=>{(0,o.Break)()});let r=(0,o.select)(e.greaterThan((0,o.int)(0)),re,(0,o.float)(1)),N=St({origin:Ie,direction:H}),U=Tt.wrap(vn(N,i,a,s)).toVar();(0,o.If)(U.didHit.not(),()=>{let t=Zi(De,H,C,T,w,A,te,ee),n=(0,o.float)(1).toVar();(0,o.If)(_e.greaterThan(0).and(A).and(j),()=>{let e=wn(C,H,T,O,k).w.toVar();(0,o.If)(e.greaterThan(0),()=>{n.assign(Jt({pdf1:_e,pdf2:e}))})}),he.addAssign(Qi({contribution:t.xyz.mul(I).mul(r).mul(n),pathLength:(0,o.float)(e),fireflyThreshold:ne,frame:(0,o.int)(me)})),(0,o.If)(P.and(ge.not()),()=>{L.assign(0)}).ElseIf(P.not(),()=>{L.mulAssign(t.a)}),(0,o.Break)()});let W=Ct.wrap(rn(U.materialIndex,s)).toVar(),Le=U.uv.toVar(),Re=U.normal.toVar();(0,o.If)(W.displacementMapIndex.greaterThanEqual((0,o.int)(0)).and(W.displacementScale.greaterThan(0)),()=>{let t=Wn.wrap(Gn(N,U,a,m,W,e)).toVar();Le.assign(t.uv),Re.assign(t.normal),U.hitPoint.assign(t.hitPoint)});let ze=At.wrap(Ln(c,l,u,d,f,p,W,Le,U.normal)).toVar();W.color.assign(ze.albedo),W.metalness.assign((0,o.clamp)(ze.metalness,0,1)),W.roughness.assign((0,o.clamp)(ze.roughness,zt,1));let G=ze.normal.toVar();(0,o.If)(W.displacementMapIndex.greaterThanEqual((0,o.int)(0)).and(W.displacementScale.greaterThan(0)),()=>{G.assign((0,o.normalize)(Re.add(ze.normal.sub(U.normal))))});let Be=(0,o.float)(1).toVar(),Ve=(0,o.float)(1).toVar();(0,o.If)(xe.equal((0,o.int)(1)),()=>{Be.assign(Se)}).ElseIf(xe.equal((0,o.int)(2)),()=>{Be.assign(Ce),Ve.assign(Se)}).ElseIf(xe.equal((0,o.int)(3)),()=>{Be.assign(we),Ve.assign(Ce)});let He=yr.wrap(Dr(N,U.hitPoint,G,W,t,B,Be,Ve)).toVar();(0,o.If)(He.continueRay,()=>{let e=(0,o.bool)(!1).toVar();(0,o.If)(He.isTransmissive.and(B.greaterThan((0,o.int)(0))),()=>{B.subAssign(1),Ee.assign((0,o.int)(Wi)),e.assign((0,o.bool)(!0)),(0,o.If)(He.didReflect.not(),()=>{(0,o.If)(He.entering,()=>{(0,o.If)(xe.lessThan((0,o.int)(3)),()=>{xe.addAssign(1),(0,o.If)(xe.equal((0,o.int)(1)),()=>{Se.assign(W.ior)}).ElseIf(xe.equal((0,o.int)(2)),()=>{Ce.assign(W.ior)}).ElseIf(xe.equal((0,o.int)(3)),()=>{we.assign(W.ior)})})}).Else(()=>{(0,o.If)(xe.greaterThan((0,o.int)(0)),()=>{xe.subAssign(1)})})})}).ElseIf(He.isAlphaSkip,()=>{e.assign((0,o.bool)(!0))}),I.mulAssign(He.throughput),(0,o.If)(P.not(),()=>{L.mulAssign(He.alpha)});let t=(0,o.select)(He.entering,G,G.negate()),n=(0,o.select)(He.didReflect,t,H);Ie.assign(U.hitPoint.add(n.mul(.001))),H.assign(He.direction),De.assign((0,o.bool)(!1)),Oe.assign((0,o.bool)(!1)),Ae.assign((0,o.bool)(!1)),(0,o.If)(e.not(),()=>{Fe.addAssign(1)}),(0,o.Continue)()}),(0,o.If)(P.not(),()=>{L.mulAssign(He.alpha)}),ge.assign((0,o.bool)(!0));let Ue=pe(de,n,e,t,(0,o.int)(-1),fe,me).toVar(),We=H.negate().toVar();W.sheenRoughness.assign((0,o.clamp)(W.sheenRoughness,zt,1)),(0,o.If)(Ae.not(),()=>{Pe.assign(dr(G,We,W,ze,Me)),Ae.assign((0,o.bool)(!0))});let Ge=(0,o.vec3)(0).toVar(),Ke=(0,o.vec3)(0).toVar(),qe=(0,o.float)(0).toVar();(0,o.If)(W.clearcoat.greaterThan(0),()=>{let e=Ar.wrap(jr(N,U,W,Ue,t));Ge.assign(e.L),Ke.assign(e.brdf),qe.assign(e.pdf)}).Else(()=>{let e=Et.wrap(Ji(We,G,W,U.materialIndex,Ue,t,ke,je,Me,Oe,Ne,Ae,Pe));Ge.assign(e.direction),Ke.assign(e.value),qe.assign(e.pdf),(0,o.If)(je.notEqual(U.materialIndex).or(ke.not()),()=>{Me.assign(en(W.metalness,W.roughness,W.transmission,W.clearcoat,W.emissive))}),ke.assign((0,o.bool)(!0)),je.assign(U.materialIndex),Oe.assign((0,o.bool)(!0))}),(0,o.If)((0,o.length)(ze.emissive).greaterThan(0),()=>{let t=(0,o.float)(1).toVar();(0,o.If)(ie.equal((0,o.int)(1)).and(oe.greaterThan((0,o.int)(0))).and(_e.greaterThan(0)),()=>{let e=Ni(U.triangleIndex,U.dst,H,Ie,a,s,se);t.assign(Jt({pdf1:_e,pdf2:e}))}),he.addAssign(Qi({contribution:ze.emissive.mul(I).mul(r).mul(t),pathLength:(0,o.float)(e),fireflyThreshold:ne,frame:(0,o.int)(me)}))});let Je=ui(U.hitPoint,G,W,We,Ge,qe,Ke,n,e,t,h,g,_,v,y,b,x,S,i,a,s,C,w,T,E,D,O,k,A);he.addAssign(Qi({contribution:Je.mul(I).mul(r),pathLength:(0,o.float)(e),fireflyThreshold:ne,frame:(0,o.int)(me)})),(0,o.If)(ie.equal((0,o.int)(1)).and(oe.greaterThan((0,o.int)(0))),()=>{let n=(0,o.Fn)(([e,t,n,r])=>Zr(e,t,n,r,yn,i,a,s));(0,o.If)(ue.greaterThan((0,o.int)(0)),()=>{let i=_i.wrap(Vi(U.hitPoint,G,t,le,ae,a));(0,o.If)(e.greaterThan((0,o.int)(1)).and(W.roughness.greaterThan(.9)).and(W.metalness.lessThan(.1)).not().and(i.valid).and(i.pdf.greaterThan(0)),()=>{let a=(0,o.max)((0,o.float)(0),(0,o.dot)(G,i.direction));(0,o.If)(a.greaterThan(0),()=>{let s=Qr(U.hitPoint,G,W),c=U.hitPoint.add(s),l=i.distance.sub(.001),u=n(c,i.direction,l,t);(0,o.If)(u.greaterThan(0),()=>{let t=Or(We,i.direction,G,W),n=li(We,i.direction,G,W),s=(0,o.select)(n.greaterThan(0),Jt({pdf1:i.pdf,pdf2:n}),(0,o.float)(1)),c=i.emission.mul(t).mul(a).div(i.pdf).mul(u).mul(ce).mul(s);he.addAssign(Qi({contribution:c.mul(I).mul(r),pathLength:(0,o.float)(e),fireflyThreshold:ne,frame:(0,o.int)(me)}))})})})}).Else(()=>{let i=Li(U.hitPoint,G,We,W,F,e,t,ce,ae,oe,se,a,n,Or,Qr);he.addAssign(Qi({contribution:i.mul(I).mul(r),pathLength:(0,o.float)(e),fireflyThreshold:ne,frame:(0,o.int)(me)}))})}),(0,o.If)(Oe.not().or(e.equal((0,o.int)(0))),()=>{Me.assign(jt.wrap(qi(W,U.materialIndex,ke,je,Me))),ke.assign((0,o.bool)(!0)),je.assign(U.materialIndex)});let Ye=Ot.wrap(ur(W,e,Me,w,j,A)),Xe=Lr.wrap(gi(We,G,W,Ge,qe,Ke,n,e,t,Ye,C,w,T,E,D,O,k,A,j));I.mulAssign(Xe.throughput),Ie.assign(U.hitPoint.add(G.mul(.001))),H.assign(Xe.direction),_e.assign(Xe.combinedPdf),De.assign((0,o.bool)(!1)),(0,o.If)(W.metalness.greaterThan(.7).and(W.roughness.lessThan(.3)),()=>{Ee.assign((0,o.int)(Ui))}).ElseIf(W.transmission.greaterThan(.5),()=>{Ee.assign((0,o.int)(Wi))}).Else(()=>{Ee.assign((0,o.int)(Gi))}),(0,o.If)(e.equal((0,o.int)(0)).and(U.didHit),()=>{R.assign(G),ve.assign(W.color.xyz),ye.assign((0,o.float)(U.materialIndex)),be.assign(U.hitPoint),z.assign(U.dst)});let Ze=Xi(e,I,W,U.materialIndex,H,t,ke,je,Me,Oe,V,A,j);(0,o.If)(Ze.lessThanEqual(0),()=>{(0,o.Break)()}),I.divAssign(Ze),Fe.addAssign(1),Oe.assign((0,o.bool)(!1)),Ae.assign((0,o.bool)(!1))}),Ki({radiance:(0,o.vec4)(he,L),objectNormal:R,objectColor:ve,objectID:ye,firstHitPoint:be,firstHitDistance:z})}),ea=(0,o.wgslFn)(`
|
|
512
512
|
fn visualizeDepth( depth: f32 ) -> vec3f {
|
|
513
513
|
return vec3f( 1.0f - depth );
|
|
514
514
|
}
|
|
515
|
-
`),
|
|
515
|
+
`),ta=(0,o.wgslFn)(`
|
|
516
516
|
fn visualizeNormal( normal: vec3f ) -> vec3f {
|
|
517
517
|
return normal * 0.5f + 0.5f;
|
|
518
518
|
}
|
|
519
|
-
`),
|
|
519
|
+
`),na=(0,o.wgslFn)(`
|
|
520
520
|
fn computeNDCDepthLocal( worldPos: vec3f, cameraProjectionMatrix: mat4x4f, cameraViewMatrix: mat4x4f ) -> f32 {
|
|
521
521
|
let clipPos = cameraProjectionMatrix * cameraViewMatrix * vec4f( worldPos, 1.0f );
|
|
522
522
|
let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
|
|
523
523
|
return clamp( ndcDepth, 0.0f, 1.0f );
|
|
524
524
|
}
|
|
525
|
-
`),
|
|
525
|
+
`),ra=(0,o.Fn)(([e,t,n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S])=>{let C=(0,o.vec4)(1,0,1,1).toVar(),w=St({origin:e,direction:t}),T=Tt.wrap(vn(w,n,r,i).toVar());return(0,o.If)(u.equal((0,o.int)(7)),()=>{let e=(0,o.float)(T.triTests).div(d);C.assign((0,o.select)(e.lessThan(1),(0,o.vec4)((0,o.vec3)(e),1),(0,o.vec4)(1,0,0,1)))}),(0,o.If)(u.equal((0,o.int)(8)),()=>{let e=(0,o.float)(T.boxTests).div(d);C.assign((0,o.select)(e.lessThan(1),(0,o.vec4)((0,o.vec3)(e),1),(0,o.vec4)(1,0,0,1)))}),(0,o.If)(u.equal((0,o.int)(10)),()=>{(0,o.If)(l,()=>{let e=En({tex:a,samp:(0,o.sampler)(a),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),n=(0,o.dot)(e.xyz,Ht).toVar(),r=n.toVar(),i=(0,o.max)(d.mul(.1),.001),u=n.div(i).toVar(),m=(0,o.log)(n.add(1e-6)).add(10).div(10).toVar(),h=(0,o.select)(d.greaterThan(1),u,m).toVar(),g=(0,o.vec3)(0).toVar();(0,o.If)(h.lessThan(.2),()=>{g.assign((0,o.mix)((0,o.vec3)(0,0,0),(0,o.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,o.mix)((0,o.vec3)(0,0,.5),(0,o.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,o.mix)((0,o.vec3)(0,0,1),(0,o.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,o.mix)((0,o.vec3)(0,1,0),(0,o.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,o.mix)((0,o.vec3)(1,1,0),(0,o.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,o.mix)((0,o.vec3)(1,0,0),(0,o.vec3)(1,1,1),(0,o.min)(h.sub(1),1)))});let _=f.div(p);(0,o.If)(_.x.lessThan(.1).and(_.y.lessThan(.1)),()=>{let e=r.mul(1);g.assign((0,o.vec3)(e))}).ElseIf(_.x.greaterThan(.9).and(_.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),C.assign((0,o.vec4)(g,1))}).Else(()=>{C.assign((0,o.vec4)(1,0,1,1))})}),(0,o.If)(u.equal((0,o.int)(4)),()=>{(0,o.If)(T.didHit.not(),()=>{C.assign((0,o.vec4)(0,0,0,1))}).Else(()=>{let t=Ct.wrap(rn(T.materialIndex,i)).toVar(),n=At.wrap(Ln(m,h,g,_,v,y,t,T.uv,T.normal)).toVar().emissive.toVar(),r=(0,o.length)(n).toVar();(0,o.If)(r.greaterThan(0),()=>{let t=n.div((0,o.max)(r.mul(.1),.001)).toVar(),i=(0,o.length)(e.sub(T.hitPoint)),a=(0,o.clamp)((0,o.float)(1).sub(i.div(10)),0,1),s=(0,o.mix)(t,t.mul((0,o.vec3)(1,.8,.6)),a.mul(.3));C.assign((0,o.vec4)(s,1))}).Else(()=>{C.assign((0,o.vec4)(0,0,.1,1))})})}),(0,o.If)(u.equal((0,o.int)(1)),()=>{(0,o.If)(T.didHit.not(),()=>{C.assign((0,o.vec4)(.5,.5,1,1))}).Else(()=>{let e=Ct.wrap(rn(T.materialIndex,i)).toVar(),t=(0,o.normalize)(At.wrap(Ln(m,h,g,_,v,y,e,T.uv,T.normal)).toVar().normal);C.assign((0,o.vec4)(ta({normal:t}),1))})}),(0,o.If)(u.equal((0,o.int)(2)),()=>{(0,o.If)(T.didHit.not(),()=>{C.assign((0,o.vec4)((0,o.vec3)(1),1))}).Else(()=>{let e=na({worldPos:T.hitPoint,cameraProjectionMatrix:b,cameraViewMatrix:x});C.assign((0,o.vec4)(ea({depth:e}),1))})}),(0,o.If)(u.equal((0,o.int)(3)),()=>{(0,o.If)(T.didHit.not(),()=>{C.assign((0,o.vec4)(0,0,0,1))}).Else(()=>{let e=Ct.wrap(rn(T.materialIndex,i)).toVar(),t=At.wrap(Ln(m,h,g,_,v,y,e,T.uv,T.normal)).toVar().albedo.rgb;C.assign((0,o.vec4)(t,1))})}),(0,o.If)(u.equal((0,o.int)(5)),()=>{(0,o.If)(T.didHit.not(),()=>{C.assign((0,o.vec4)(0,0,0,1))}).Else(()=>{let e=Ct.wrap(rn(T.materialIndex,i)).toVar(),t=At.wrap(Ln(m,h,g,_,v,y,e,T.uv,T.normal)).toVar(),u=t.albedo.rgb.toVar(),d=(0,o.normalize)(t.normal).toVar(),p=P({state:ne({seed:(0,o.uint)(f.x).mul((0,o.uint)(1973)).add((0,o.uint)(f.y).mul((0,o.uint)(9277))).add(S.mul((0,o.uint)(26699)))})}).toVar(),b=mr({N:d,xi:(0,o.vec2)(F(p).toVar(),F(p).toVar()).toVar()}).toVar(),x=St({origin:T.hitPoint.add(d.mul(.001)).toVar(),direction:b}),w=Tt.wrap(vn(x,n,r,i).toVar()),E=(0,o.vec3)(0).toVar();(0,o.If)(w.didHit.not(),()=>{(0,o.If)(l,()=>{E.assign(En({tex:a,samp:(0,o.sampler)(a),direction:b,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=Ct.wrap(rn(w.materialIndex,i)).toVar(),t=At.wrap(Ln(m,h,g,_,v,y,e,w.uv,w.normal)).toVar();E.assign(t.emissive),(0,o.If)(l,()=>{let e=(0,o.normalize)(t.normal).toVar(),n=En({tex:a,samp:(0,o.sampler)(a),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;E.addAssign(t.albedo.rgb.mul(n))})});let D=u.mul(E);C.assign((0,o.vec4)(D,1))})}),(0,o.If)(u.equal((0,o.int)(6)),()=>{(0,o.If)(T.didHit,()=>{let e=T.normal.toVar(),n=(0,o.normalize)(t.sub(e.mul((0,o.dot)(t,e).mul(2)))).toVar(),r=En({tex:a,samp:(0,o.sampler)(a),direction:n,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,i=r.div(r.add(1));C.assign((0,o.vec4)(i,1))}).Else(()=>{let e=En({tex:a,samp:(0,o.sampler)(a),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,n=e.div(e.add(1));C.assign((0,o.vec4)(n,1))})}),C});(0,o.Fn)(([e,t])=>{let n=F(t),r=(0,o.vec3)(.25/255,-.25/255,.25/255).toVar();return r.assign((0,o.mix)(r.mul(2),r.mul(-2),n)),e.add(r)});var ia=(0,o.wgslFn)(`
|
|
526
526
|
fn computeNDCDepth( worldPos: vec3f, cameraProjectionMatrix: mat4x4f, cameraViewMatrix: mat4x4f ) -> f32 {
|
|
527
527
|
let clipPos = cameraProjectionMatrix * cameraViewMatrix * vec4f( worldPos, 1.0f );
|
|
528
528
|
let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
|
|
529
529
|
return clamp( ndcDepth, 0.0f, 1.0f );
|
|
530
530
|
}
|
|
531
|
-
`),ia=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.texture)(n,e.div(t),0),s=(0,o.int)(0).toVar();return(0,o.If)(a.b.greaterThan(.5),()=>{s.assign(0)}).Else(()=>{let e=(0,o.int)((0,o.floor)(a.r.mul((0,o.float)(i)).add(.5)));s.assign((0,o.clamp)(e,r,i))}),s}),aa=e=>{let{pixelCoord:t,writeColorTex:n,writeNDTex:r,writeAlbedoTex:i,resolution:a,frame:s,samplesPerPixel:c,visMode:l,cameraWorldMatrix:u,cameraProjectionMatrixInverse:d,cameraViewMatrix:f,cameraProjectionMatrix:p,bvhBuffer:m,triangleBuffer:h,materialBuffer:g,albedoMaps:_,normalMaps:v,bumpMaps:y,metalnessMaps:b,roughnessMaps:x,emissiveMaps:S,displacementMaps:C,directionalLightsBuffer:w,numDirectionalLights:T,areaLightsBuffer:E,numAreaLights:D,pointLightsBuffer:O,numPointLights:k,spotLightsBuffer:A,numSpotLights:j,envTexture:M,environmentIntensity:N,envMatrix:ee,envMarginalWeights:te,envConditionalWeights:ne,envTotalSum:re,envResolution:F,enableEnvironmentLight:ie,useEnvMapIS:ae,maxBounceCount:oe,transmissiveBounces:se,showBackground:ce,transparentBackground:le,backgroundIntensity:ue,fireflyThreshold:de,globalIlluminationIntensity:fe,totalTriangleCount:pe,enableEmissiveTriangleSampling:I,emissiveTriangleBuffer:L,emissiveTriangleCount:ge,emissiveTotalPower:_e,emissiveBoost:R,lightBVHBuffer:ve,lightBVHNodeCount:ye,debugVisScale:be,enableAccumulation:z,hasPreviousAccumulated:xe,prevAccumTexture:Se,prevNormalDepthTexture:Ce,prevAlbedoTexture:we,accumulationAlpha:Te,cameraIsMoving:B,useAdaptiveSampling:Ee,adaptiveSamplingTexture:De,adaptiveSamplingMin:Oe,adaptiveSamplingMax:ke,enableDOF:Ae,focalLength:V,aperture:je,focusDistance:Me,sceneScale:Ne,apertureScale:Pe,anamorphicRatio:Fe}=e,Ie=(0,o.uvec2)((0,o.uint)((0,o.int)(t.x)),(0,o.uint)((0,o.int)(t.y))),H=t.div(a),U=t.div(a).mul(2).sub(1).toVar();U.y.assign(U.y.negate());let W=(0,o.vec4)(0).toVar(),Le=(0,o.int)(0).toVar(),Re=he({pixelCoord:t,rayIndex:(0,o.int)(0),frame:s}).toVar(),ze=(0,o.int)(t.y).mul((0,o.int)(a.x)).add((0,o.int)(t.x)).toVar(),G=(0,o.vec3)(0,0,1).toVar(),Be=(0,o.float)(1).toVar(),Ve=(0,o.float)(0).toVar(),He=(0,o.int)(c).toVar();(0,o.If)(s.greaterThan((0,o.uint)(2)).and(Ee),()=>{let e=ia(t,a,De,Oe,ke);He.assign(e),(0,o.If)(He.equal((0,o.int)(0)),()=>{(0,o.If)(z.and(xe),()=>{let e=(0,o.texture)(Se,H,0);W.assign(e),Ve.assign(e.w);let t=(0,o.texture)(Ce,H,0);G.assign(t.xyz.mul(2).sub(1)),Be.assign(t.w)}).Else(()=>{He.assign(1)})})});let Ue=(0,o.vec3)(0).toVar(),We=(0,o.vec3)(0).toVar(),Ge=(0,o.float)(-1e3).toVar(),Ke=(0,o.vec2)(2).div(a).toVar();(0,o.Loop)({start:(0,o.int)(0),end:He,type:`int`,condition:`<`},({i:e})=>{let n=P({state:Re.add((0,o.uint)(e))}).toVar(),r=me(t,e,He,n,a,s).toVar();(0,o.If)(l.equal((0,o.int)(9)),()=>{W.assign((0,o.vec4)(r,1,1)),Le.assign(1),(0,o.Break)()});let i=r.sub(.5).mul(Ke),c=U.add(i),he=xt.wrap(yn(c,n,u,d,Ae,V,je,Me,Ne,Pe,Fe)),z=(0,o.vec4)(0).toVar();(0,o.If)(l.greaterThan((0,o.int)(0)),()=>{z.assign(na(he.origin,he.direction,m,h,g,M,ee,N,ie,l,be,t,a,_,v,y,b,x,S,p,f,s))}).Else(()=>{let r=Gi.wrap(Qi(he,n,e,ze,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee,te,ne,re,F,ie,ae,oe,se,ue,ce,le,de,fe,pe,I,L,ge,_e,R,ve,ye,t,a,s));z.assign(r.radiance),(0,o.If)(e.equal((0,o.int)(0)),()=>{Ue.assign(r.objectNormal),We.assign(r.objectColor),Ge.assign(r.objectID),(0,o.If)(r.firstHitDistance.lessThan(1e9),()=>{G.assign((0,o.normalize)(r.objectNormal)),Be.assign(ra({worldPos:r.firstHitPoint,cameraProjectionMatrix:p,cameraViewMatrix:f}))})})}),W.addAssign(z),Ve.addAssign(z.w),Le.addAssign(1)}),(0,o.If)(Le.greaterThan((0,o.int)(0)),()=>{W.divAssign((0,o.float)(Le)),Ve.divAssign((0,o.float)(Le))});let qe=W.xyz.toVar(),Je=(0,o.vec4)(G.mul(.5).add(.5),Be).toVar(),Ye=(0,o.vec3)(We).toVar(),Xe=(0,o.select)(le,Ve,(0,o.float)(1)).toVar();(0,o.If)(z.and(B.not()).and(s.greaterThan((0,o.uint)(0))).and(xe),()=>{let e=(0,o.texture)(Se,H,0).toVar();qe.assign((0,o.mix)(e.xyz,W.xyz,Te)),Je.assign((0,o.mix)((0,o.texture)(Ce,H,0),Je,Te)),Ye.assign((0,o.mix)((0,o.texture)(we,H,0).xyz,Ye,Te)),(0,o.If)(le,()=>{Xe.assign((0,o.mix)(e.w,Ve,Te))})}),(0,o.textureStore)(n,Ie,(0,o.vec4)(qe.xyz,Xe)).toWriteOnly(),(0,o.textureStore)(r,Ie,Je).toWriteOnly(),(0,o.textureStore)(i,Ie,(0,o.vec4)(Ye,1)).toWriteOnly()},oa=class{constructor(e=`Build`){this.label=e,this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(){let e=performance.now()-this.totalStart,t=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean);return console.log(`[${this.label}] ${Math.round(e)}ms`+(t.length?` | ${t.join(` · `)}`:``)),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(e)}}},sa=8,ca=class{constructor(){this.computeNode=null,this.prevColorTexNode=null,this.prevNormalDepthTexNode=null,this.prevAlbedoTexNode=null,this.adaptiveSamplingTexNode=null,this.tileOffsetX=(0,o.uniform)(0,`int`),this.tileOffsetY=(0,o.uniform)(0,`int`),this.renderWidth=(0,o.uniform)(1920,`int`),this.renderHeight=(0,o.uniform)(1080,`int`),this._dispatchX=0,this._dispatchY=0,this._sceneTextureNodes=null}setupCompute(e){let{stage:t,storageTextures:n}=e,r=new oa(`setupCompute`);r.start(`Create texture nodes`);let i=this._createTextureNodes(t,n);r.end(`Create texture nodes`),r.start(`Build compute node (TSL)`);let a=n.renderWidth,o=n.renderHeight;this._dispatchX=Math.ceil(a/sa),this._dispatchY=Math.ceil(o/sa),this.renderWidth.value=a,this.renderHeight.value=o;let s=n.getWriteTextures();this.computeNode=this._buildComputeNode(t,i,s.color,s.normalDepth,s.albedo),r.end(`Build compute node (TSL)`),r.print()}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment,r=e.materialData;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),r.albedoMaps&&t.albedoMapsTex&&(t.albedoMapsTex.value=r.albedoMaps),r.normalMaps&&t.normalMapsTex&&(t.normalMapsTex.value=r.normalMaps),r.bumpMaps&&t.bumpMapsTex&&(t.bumpMapsTex.value=r.bumpMaps),r.metalnessMaps&&t.metalnessMapsTex&&(t.metalnessMapsTex.value=r.metalnessMaps),r.roughnessMaps&&t.roughnessMapsTex&&(t.roughnessMapsTex.value=r.roughnessMaps),r.emissiveMaps&&t.emissiveMapsTex&&(t.emissiveMapsTex.value=r.emissiveMaps),r.displacementMaps&&t.displacementMapsTex&&(t.displacementMapsTex.value=r.displacementMaps),console.log(`ShaderBuilder: Scene textures updated in-place`)}getSceneTextureNodes(){return this._sceneTextureNodes}setSize(e,t){this._dispatchX=Math.ceil(e/sa),this._dispatchY=Math.ceil(t/sa),this.computeNode&&this.computeNode.setCount([this._dispatchX,this._dispatchY,1]),this.renderWidth.value=e,this.renderHeight.value=t,this.tileOffsetX.value=0,this.tileOffsetY.value=0}setTileDispatch(e,t,n,r){this.tileOffsetX.value=e,this.tileOffsetY.value=t;let i=Math.ceil(n/sa),a=Math.ceil(r/sa);this.computeNode&&this.computeNode.setCount([i,a,1])}setFullScreenDispatch(){this.tileOffsetX.value=0,this.tileOffsetY.value=0,this.computeNode&&this.computeNode.setCount([this._dispatchX,this._dispatchY,1])}forceCompile(){}_createTextureNodes(e,r){let i=e.triangleStorageNode,a=e.bvhStorageNode,s=e.materialData.materialStorageNode,c=e.emissiveTriangleStorageNode,l=e.lightBVHStorageNode;fn(e.meshVisibilityStorageNode),Yr(e.uniforms.get(`enableAlphaShadows`));let u=(0,o.texture)(e.environment.environmentTexture),d=new t.TextureNode;this.adaptiveSamplingTexNode=d;let f=e.environment.envMarginalStorageNode,p=e.environment.envConditionalStorageNode,m=r.getReadTextures();this.prevColorTexNode=(0,o.texture)(m.color),this.prevNormalDepthTexNode=(0,o.texture)(m.normalDepth),this.prevAlbedoTexNode=(0,o.texture)(m.albedo);let h=()=>{let e=new n.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=n.LinearFilter,e.magFilter=n.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,o.texture)(e)},g=e.materialData,_=g.albedoMaps?(0,o.texture)(g.albedoMaps):h(),v=g.normalMaps?(0,o.texture)(g.normalMaps):h(),y=g.bumpMaps?(0,o.texture)(g.bumpMaps):h(),b=g.metalnessMaps?(0,o.texture)(g.metalnessMaps):h(),x=g.roughnessMaps?(0,o.texture)(g.roughnessMaps):h(),S=g.emissiveMaps?(0,o.texture)(g.emissiveMaps):h(),C=g.displacementMaps?(0,o.texture)(g.displacementMaps):h();Jr(_);let w={triStorage:i,bvhStorage:a,matStorage:s,emissiveTriStorage:c,lightBVHStorage:l,envTex:u,adaptiveSamplingTex:d,marginalCDFStorage:f,conditionalCDFStorage:p,albedoMapsTex:_,normalMapsTex:v,bumpMapsTex:y,metalnessMapsTex:b,roughnessMapsTex:x,emissiveMapsTex:S,displacementMapsTex:C};return this._sceneTextureNodes=w,w}_buildComputeNode(e,t,n,r,i){let{triStorage:a,bvhStorage:s,matStorage:c,emissiveTriStorage:l,lightBVHStorage:u,envTex:d,adaptiveSamplingTex:f,marginalCDFStorage:p,conditionalCDFStorage:m,albedoMapsTex:h,normalMapsTex:g,bumpMapsTex:_,metalnessMapsTex:v,roughnessMapsTex:y,emissiveMapsTex:b,displacementMapsTex:x}=t,S=this.tileOffsetX,C=this.tileOffsetY,w=this.renderWidth,T=this.renderHeight,E=this.prevColorTexNode,D=this.prevNormalDepthTexNode,O=this.prevAlbedoTexNode;return(0,o.Fn)(()=>{let t=S.add((0,o.int)(o.workgroupId.x).mul(sa)).add((0,o.int)(o.localId.x)),k=C.add((0,o.int)(o.workgroupId.y).mul(sa)).add((0,o.int)(o.localId.y));(0,o.If)(t.lessThan(w).and(k.lessThan(T)),()=>{aa({pixelCoord:(0,o.vec2)((0,o.float)(t).add(.5),(0,o.float)(k).add(.5)),writeColorTex:n,writeNDTex:r,writeAlbedoTex:i,prevAccumTexture:E,prevNormalDepthTexture:D,prevAlbedoTexture:O,resolution:e.resolution,frame:e.frame,samplesPerPixel:e.samplesPerPixel,visMode:e.visMode,cameraWorldMatrix:e.cameraWorldMatrix,cameraProjectionMatrixInverse:e.cameraProjectionMatrixInverse,cameraViewMatrix:e.cameraViewMatrix,cameraProjectionMatrix:e.cameraProjectionMatrix,bvhBuffer:s,triangleBuffer:a,materialBuffer:c,albedoMaps:h,normalMaps:g,bumpMaps:_,metalnessMaps:v,roughnessMaps:y,emissiveMaps:b,displacementMaps:x,directionalLightsBuffer:e.directionalLightsBufferNode,numDirectionalLights:e.numDirectionalLights,areaLightsBuffer:e.areaLightsBufferNode,numAreaLights:e.numAreaLights,pointLightsBuffer:e.pointLightsBufferNode,numPointLights:e.numPointLights,spotLightsBuffer:e.spotLightsBufferNode,numSpotLights:e.numSpotLights,envTexture:d,environmentIntensity:e.environmentIntensity,envMatrix:e.environmentMatrix,envMarginalWeights:p,envConditionalWeights:m,envTotalSum:e.envTotalSum,envResolution:e.envResolution,enableEnvironmentLight:e.enableEnvironment,useEnvMapIS:e.useEnvMapIS,maxBounceCount:e.maxBounces,transmissiveBounces:e.transmissiveBounces,showBackground:e.showBackground,transparentBackground:e.transparentBackground,backgroundIntensity:e.backgroundIntensity,fireflyThreshold:e.fireflyThreshold,globalIlluminationIntensity:e.globalIlluminationIntensity,totalTriangleCount:e.totalTriangleCount,enableEmissiveTriangleSampling:e.enableEmissiveTriangleSampling,emissiveTriangleBuffer:l,emissiveTriangleCount:e.emissiveTriangleCount,emissiveTotalPower:e.emissiveTotalPower,emissiveBoost:e.emissiveBoost,lightBVHBuffer:u,lightBVHNodeCount:e.lightBVHNodeCount,debugVisScale:e.debugVisScale,enableAccumulation:e.enableAccumulation,hasPreviousAccumulated:e.hasPreviousAccumulated,accumulationAlpha:e.accumulationAlpha,cameraIsMoving:e.cameraIsMoving,useAdaptiveSampling:e.useAdaptiveSampling,adaptiveSamplingTexture:f,adaptiveSamplingMin:e.adaptiveSamplingMin,adaptiveSamplingMax:e.adaptiveSamplingMax,enableDOF:e.enableDOF,focalLength:e.focalLength,aperture:e.aperture,focusDistance:e.focusDistance,sceneScale:e.sceneScale,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio})})})().compute([this._dispatchX,this._dispatchY,1],[sa,sa,1])}dispose(){this.computeNode?.dispose(),this.computeNode=null,this.prevColorTexNode=null,this.prevNormalDepthTexNode=null,this.prevAlbedoTexNode=null,this.adaptiveSamplingTexNode=null,this._sceneTextureNodes=null}},la=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new ua;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new ua;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}setMaxTreelets(){}getStatistics(){return{...this.stats}}},ua=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},da=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}},fa={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},pa=fa.FLOATS_PER_TRIANGLE,ma=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},ha=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!0,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.maxTreeletDepth=3,this.maxTreeletsPerScene=20,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement))}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=this.triangles,n=fa.POSITION_A_OFFSET,r=fa.POSITION_B_OFFSET,i=fa.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*pa,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(pa*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&typeof Worker<`u`?new Promise((r,i)=>{try{let a=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BqQTDljT.js`).href:new URL(`assets/BVHWorker-BqQTDljT.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;console.log(`[BVHBuilder] SharedArrayBuffer: ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*pa*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])}catch(i){console.warn(`Worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(pa*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold,t=e?3:this.treeletSize,r=e?10:this.maxTreeletsPerScene,i=new la(this.traversalCost,this.intersectionCost);i.setTreeletSize(t),i.setMinImprovement(this.treeletMinImprovement),i.setMaxTreelets(r);let a=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{i.optimizeBVH(c,t)}catch(t){console.error(`TreeletOptimizer: Error in pass ${e+1}:`,t);break}let r=i.getStatistics(),o=performance.now()-a;if(r.treeletsImproved===0&&e>0||o>15e3)break}let o=performance.now()-a;this.splitStats.treeletOptimizationTime=o;let s=i.getStatistics();this.splitStats.treeletsProcessed=s.treeletsProcessed,this.splitStats.treeletsImproved=s.treeletsImproved,this.splitStats.averageSAHImprovement=s.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new da(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){console.error(`ReinsertionOptimizer: Error:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new Float32Array(a*pa);for(let e=0;e<a;e++){let t=this.indices[e]*pa,n=e*pa;f.set(d.subarray(t,t+pa),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return console.log(`[BVH] ${a.toLocaleString()} tris → ${this.totalNodes} nodes in ${Math.round(m)}ms | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new ma;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new ma;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Q={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},ga=Q.FLOATS_PER_TRIANGLE,_a=16,va=-1,ya=-2,ba=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length;for(let i=0;i<r;i++){let r=n[i],a=i*ga,o=r*9,s=t[o],c=t[o+1],l=t[o+2],u=t[o+3],d=t[o+4],f=t[o+5],p=t[o+6],m=t[o+7],h=t[o+8];e[a+Q.POSITION_A_OFFSET]=s,e[a+Q.POSITION_A_OFFSET+1]=c,e[a+Q.POSITION_A_OFFSET+2]=l,e[a+Q.POSITION_B_OFFSET]=u,e[a+Q.POSITION_B_OFFSET+1]=d,e[a+Q.POSITION_B_OFFSET+2]=f,e[a+Q.POSITION_C_OFFSET]=p,e[a+Q.POSITION_C_OFFSET+1]=m,e[a+Q.POSITION_C_OFFSET+2]=h;let g=u-s,_=d-c,v=f-l,y=p-s,b=m-c,x=h-l,S=_*x-v*b,C=v*y-g*x,w=g*b-_*y;e[a+Q.NORMAL_A_OFFSET]=S,e[a+Q.NORMAL_A_OFFSET+1]=C,e[a+Q.NORMAL_A_OFFSET+2]=w,e[a+Q.NORMAL_B_OFFSET]=S,e[a+Q.NORMAL_B_OFFSET+1]=C,e[a+Q.NORMAL_B_OFFSET+2]=w,e[a+Q.NORMAL_C_OFFSET]=S,e[a+Q.NORMAL_C_OFFSET+1]=C,e[a+Q.NORMAL_C_OFFSET+2]=w}}refitRange(e,t,n,r){r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let i=this._bounds,a=n+r;for(let r=a-1;r>=n;r--){let a=r*_a,o=(r-n)*6;if(e[a+3]===va){let n=e[a],r=e[a+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<r;e++){let r=(n+e)*ga,i=t[r+Q.POSITION_A_OFFSET],a=t[r+Q.POSITION_A_OFFSET+1],o=t[r+Q.POSITION_A_OFFSET+2],p=t[r+Q.POSITION_B_OFFSET],m=t[r+Q.POSITION_B_OFFSET+1],h=t[r+Q.POSITION_B_OFFSET+2],g=t[r+Q.POSITION_C_OFFSET],_=t[r+Q.POSITION_C_OFFSET+1],v=t[r+Q.POSITION_C_OFFSET+2];s=Math.min(s,i,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,i,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}i[o]=s,i[o+1]=c,i[o+2]=l,i[o+3]=u,i[o+4]=d,i[o+5]=f}else{let t=e[a+3],r=e[a+7],s=(t-n)*6,c=(r-n)*6,l=i[s],u=i[s+1],d=i[s+2],f=i[s+3],p=i[s+4],m=i[s+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];e[a]=l,e[a+1]=u,e[a+2]=d,e[a+4]=f,e[a+5]=p,e[a+6]=m,e[a+8]=h,e[a+9]=g,e[a+10]=_,e[a+12]=v,e[a+13]=y,e[a+14]=b,i[o]=Math.min(l,h),i[o+1]=Math.min(u,g),i[o+2]=Math.min(d,_),i[o+3]=Math.max(f,v),i[o+4]=Math.max(p,y),i[o+5]=Math.max(m,b)}}}refit(e,t,n){n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let r=this._bounds;for(let i=n-1;i>=0;i--){let n=i*_a,a=i*6,o=e[n+3];if(o===va){let i=e[n],o=e[n+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<o;e++){let n=(i+e)*ga,r=t[n+Q.POSITION_A_OFFSET],a=t[n+Q.POSITION_A_OFFSET+1],o=t[n+Q.POSITION_A_OFFSET+2],p=t[n+Q.POSITION_B_OFFSET],m=t[n+Q.POSITION_B_OFFSET+1],h=t[n+Q.POSITION_B_OFFSET+2],g=t[n+Q.POSITION_C_OFFSET],_=t[n+Q.POSITION_C_OFFSET+1],v=t[n+Q.POSITION_C_OFFSET+2];s=Math.min(s,r,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,r,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}r[a]=s,r[a+1]=c,r[a+2]=l,r[a+3]=u,r[a+4]=d,r[a+5]=f}else if(o===ya){let t=e[n]*6;r[a]=r[t],r[a+1]=r[t+1],r[a+2]=r[t+2],r[a+3]=r[t+3],r[a+4]=r[t+4],r[a+5]=r[t+5]}else{let t=e[n+3],i=e[n+7],o=t*6,s=i*6,c=r[o],l=r[o+1],u=r[o+2],d=r[o+3],f=r[o+4],p=r[o+5],m=r[s],h=r[s+1],g=r[s+2],_=r[s+3],v=r[s+4],y=r[s+5];e[n]=c,e[n+1]=l,e[n+2]=u,e[n+4]=d,e[n+5]=f,e[n+6]=p,e[n+8]=m,e[n+9]=h,e[n+10]=g,e[n+12]=_,e[n+13]=v,e[n+14]=y,r[a]=Math.min(c,m),r[a+1]=Math.min(l,h),r[a+2]=Math.min(u,g),r[a+3]=Math.max(d,_),r[a+4]=Math.max(f,v),r[a+5]=Math.max(p,y)}}}},xa=32,Sa=5e4,Ca=8;function wa(e,t,n,r){let i=e.byteLength/(xa*4),a=Math.min(navigator.hardwareConcurrency||4,Ca),o=Math.ceil(Math.log2(a*2.5+1));return console.log(`[ParallelBVH] Parallel build: ${i.toLocaleString()} triangles, ${a} workers, parallelDepth=${o}`),new Promise((s,c)=>{try{let c=new SharedArrayBuffer(e.byteLength);new Float32Array(c).set(e);let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*xa*4),h=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BqQTDljT.js`).href:new URL(`assets/BVHWorker-BqQTDljT.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),g=null,_=[h],v={id:null},y=!1,b=()=>{v.id&&=(clearTimeout(v.id),null);for(let e of _)try{e.terminate()}catch{}},x=e=>{if(y)return;y=!0,console.warn(`[ParallelBVH] Parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Float32Array(i).set(new Float32Array(c)),s(Ea(new Float32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,Ta(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r);return}if(t.type===`assembleResult`){y=!0,b();let e=new Float32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})}catch(e){console.warn(`[ParallelBVH] Parallel build setup failed:`,e),c(e)}})}function Ta(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){console.log(`[ParallelBVH] No frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},[_.buffer]);return}console.log(`[ParallelBVH] Phase 2: distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHSubtreeWorker-BoG4D6dP.js`).href:new URL(`assets/BVHSubtreeWorker-BoG4D6dP.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Ea(e,t,n,r){return new Promise((i,a)=>{try{let o=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BqQTDljT.js`).href:new URL(`assets/BVHWorker-BqQTDljT.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),s=e.byteLength/(xa*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*xa*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])}catch(e){console.warn(`[ParallelBVH] Single worker fallback failed:`,e),a(e)}})}function Da(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Sa}var Oa=16,ka=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.entryIndex=-1}},Aa=class{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){if(e.length===0)return{root:null,nodeCount:0};let t=[];for(let n=0;n<e.length;n++)t.push(n);let n=this._buildRecursive(e,t);return{root:n,nodeCount:this._countNodes(n)}}_buildRecursive(e,t){let n=new ka;if(t.length===1){let r=e[t[0]].worldAABB;return n.minX=r.minX,n.minY=r.minY,n.minZ=r.minZ,n.maxX=r.maxX,n.maxY=r.maxY,n.maxZ=r.maxZ,n.entryIndex=t[0],n}let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let n of t){let t=e[n].worldAABB;t.minX<r&&(r=t.minX),t.minY<i&&(i=t.minY),t.minZ<a&&(a=t.minZ),t.maxX>o&&(o=t.maxX),t.maxY>s&&(s=t.maxY),t.maxZ>c&&(c=t.maxZ)}if(n.minX=r,n.minY=i,n.minZ=a,n.maxX=o,n.maxY=s,n.maxZ=c,t.length===2)return n.leftChild=this._buildRecursive(e,[t[0]]),n.rightChild=this._buildRecursive(e,[t[1]]),n;let l=this._surfaceArea(r,i,a,o,s,c),u=1/0,d=0,f=0;if(l>0&&isFinite(l))for(let n=0;n<3;n++){let r=t.slice().sort((t,r)=>{let i=e[t].worldAABB,a=e[r].worldAABB;return this._centroid(i,n)-this._centroid(a,n)});for(let t=1;t<r.length;t++){let i=this._computeGroupAABB(e,r,0,t),a=this._computeGroupAABB(e,r,t,r.length),o=this._surfaceArea(i.minX,i.minY,i.minZ,i.maxX,i.maxY,i.maxZ),s=this._surfaceArea(a.minX,a.minY,a.minZ,a.maxX,a.maxY,a.maxZ),c=1+(o*t+s*(r.length-t))/l;c<u&&(u=c,d=n,f=t)}}if(f<=0||f>=t.length){d=0;let e=o-r,n=s-i,l=c-a;n>e&&n>l?d=1:l>e&&(d=2),f=t.length>>1}let p=t.slice().sort((t,n)=>this._centroid(e[t].worldAABB,d)-this._centroid(e[n].worldAABB,d)),m=p.slice(0,f),h=p.slice(f);return n.leftChild=this._buildRecursive(e,m),n.rightChild=this._buildRecursive(e,h),n}flatten(e,t){if(!e)return new Float32Array;let n=[],r=[e];for(;r.length>0;){let e=r.pop();e._flatIndex=n.length,n.push(e),e.rightChild&&r.push(e.rightChild),e.leftChild&&r.push(e.leftChild)}let i=n.length*Oa;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer;a.fill(0,0,i);for(let e=0;e<n.length;e++){let r=n[e],i=e*Oa;if(r.leftChild){let e=r.leftChild,t=r.rightChild;a[i]=e.minX,a[i+1]=e.minY,a[i+2]=e.minZ,a[i+3]=e._flatIndex,a[i+4]=e.maxX,a[i+5]=e.maxY,a[i+6]=e.maxZ,a[i+7]=t._flatIndex,a[i+8]=t.minX,a[i+9]=t.minY,a[i+10]=t.minZ,a[i+12]=t.maxX,a[i+13]=t.maxY,a[i+14]=t.maxZ}else a[i]=t[r.entryIndex].blasOffset,a[i+1]=r.entryIndex,a[i+3]=W.BLAS_POINTER_LEAF}return a.subarray(0,i)}_centroid(e,t){return t===0?(e.minX+e.maxX)*.5:t===1?(e.minY+e.maxY)*.5:(e.minZ+e.maxZ)*.5}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}_computeGroupAABB(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=e[t[u]].worldAABB;n.minX<i&&(i=n.minX),n.minY<a&&(a=n.minY),n.minZ<o&&(o=n.minZ),n.maxX>s&&(s=n.maxX),n.maxY>c&&(c=n.maxY),n.maxZ>l&&(l=n.maxZ)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l}}_countNodes(e){if(!e)return 0;let t=0,n=[e];for(;n.length>0;){let e=n.pop();t++,e.leftChild&&n.push(e.leftChild),e.rightChild&&n.push(e.rightChild)}return t}},ja=class{constructor(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}allocate(e){this.entries=Array(e).fill(null)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a}){this.entries[e]={meshIndex:e,blasOffset:0,blasNodeCount:t,triOffset:n,triCount:r,worldAABB:null,originalToBvhMap:i,bvhData:a}}computeAABBs(e){for(let t of this.entries)t&&(t.worldAABB=this._readRootAABB(t.bvhData,t,e))}recomputeAABB(e,t,n){let r=this.entries[e],i=t.subarray(r.blasOffset*16,r.blasOffset*16+16);r.worldAABB=this._readRootAABB(i,r,n)}_readRootAABB(e,t,n){if(e[3]===-1)return this._computeAABBFromTriangles(t,n);let r=e[0],i=e[1],a=e[2],o=e[4],s=e[5],c=e[6],l=e[8],u=e[9],d=e[10],f=e[12],p=e[13],m=e[14];return{minX:Math.min(r,l),minY:Math.min(i,u),minZ:Math.min(a,d),maxX:Math.max(o,f),maxY:Math.max(s,p),maxZ:Math.max(c,m)}}_computeAABBFromTriangles(e,t){let n=H.FLOATS_PER_TRIANGLE,r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let l=0;l<e.triCount;l++){let u=(e.triOffset+l)*n;for(let e=0;e<=8;e+=4){let n=t[u+e],l=t[u+e+1],d=t[u+e+2];n<r&&(r=n),l<i&&(i=l),d<a&&(a=d),n>o&&(o=n),l>s&&(s=l),d>c&&(c=d)}}return{minX:r,minY:i,minZ:a,maxX:o,maxY:s,maxZ:c}}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e of this.entries)e&&(e.blasOffset=t,t+=e.blasNodeCount);this.totalBLASNodes=t-e}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}get count(){return this.entries.length}clear(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}},Ma=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Le.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Na=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Be.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Be.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Le.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},Pa=class{constructor(e=Le.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``;t+=`${e}x${r}_${i.slice(-8)}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e),this.cache.get(e)}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Fa=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Le.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this.canvasPool=new Ma,this.bufferPool=new Na({maxMemory:e.maxBufferMemory||Be.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Pa,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:navigator.hardwareConcurrency||4}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}async createTexturesToDataTexture(e){if(!e||e.length===0)return null;let t=this.textureCache.generateHash(e),n=this.textureCache.get(t);if(n)return n;let{normalized:r,bitmapsToClose:i}=await this._normalizeTexturesForProcessing(e),a=this.selectProcessingStrategy(r),o;try{switch(a.method){case`worker-direct`:o=await this.processWithWorkerDirect(r);break;case`worker-chunked`:o=await this.processWithWorkerChunked(r,a.chunkSize);break;case`main-batch`:o=await this.processOnMainThreadBatch(r,a.batchSize);break;case`main-streaming`:o=await this.processOnMainThreadStreaming(r);break;default:o=await this.processOnMainThreadSync(r)}return o&&this.textureCache.set(t,o),o}catch(e){return console.warn(`Texture processing failed, trying fallback:`,e),await this.processOnMainThreadSync(r)}finally{for(let e of i)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Be.MAX_TEXTURE_MEMORY?{method:`worker-chunked`,chunkSize:Math.max(1,Math.floor(e.length/4))}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;try{let t=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/TexturesWorker-DBqGmVdR.js`).href:new URL(`assets/TexturesWorker-DBqGmVdR.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:Le.MAX_TEXTURE_SIZE,method:`direct-transfer`},i)});return t.terminate(),this.createDataArrayTextureFromResult(r)}finally{this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[];for(let n of e)if(n?.image)try{if(typeof createImageBitmap<`u`&&n.image instanceof HTMLImageElement){let e=await createImageBitmap(n.image);t.push({bitmap:e,width:n.image.width,height:n.image.height,isDirect:!0})}else{let e=this.canvasPool.getCanvasWithContext(n.image.width,n.image.height);e.context.drawImage(n.image,0,0);let r=e.context.getImageData(0,0,n.image.width,n.image.height);t.push({data:r.data.buffer,width:n.image.width,height:n.image.height,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(e)}}catch(e){console.warn(`Failed to prepare texture for worker:`,e)}return t}async processWithWorkerChunked(e,t){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.processWithWorkerDirect(i);n.push(a)}return this.combineTextureResults(n)}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`});s.push(a.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e];o.context.clearRect(0,0,n,r),o.context.drawImage(i.image,0,0,n,r);let s=o.context.getImageData(0,0,n,r),c=n*r*4*e;a.set(s.data,c),e%Be.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e];o.context.clearRect(0,0,n,r),o.context.drawImage(i.image,0,0,n,r);let s=o.context.getImageData(0,0,n,r),c=n*r*4*e;a.set(s.data,c)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=U.FLOATS_PER_MATERIAL,n=e.length,r=n*t,i=new Float32Array(r);for(let r=0;r<n;r++){let n=e[r],a=r*t,o=n.mapMatrix??Re,s=n.normalMapMatrices??Re,c=n.roughnessMapMatrices??Re,l=n.metalnessMapMatrices??Re,u=n.emissiveMapMatrices??Re,d=n.bumpMapMatrices??Re,f=n.displacementMapMatrices??Re,p=[n.ior,n.transmission,n.thickness,n.emissiveIntensity,n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b,n.attenuationDistance,n.opacity,n.side,n.transparent,n.alphaTest,n.alphaMode,n.depthWrite,n.normalScale?.x??1,n.normalScale?.y??1,n.color.r,n.color.g,n.color.b,n.metalness,n.emissive.r,n.emissive.g,n.emissive.b,n.roughness,n.map,n.normalMap,n.roughnessMap,n.metalnessMap,n.emissiveMap,n.bumpMap,n.clearcoat,n.clearcoatRoughness,n.dispersion,n.visible,n.sheen,n.sheenRoughness,n.sheenColor.r,n.sheenColor.g,n.sheenColor.b,1,n.specularIntensity,n.specularColor.r,n.specularColor.g,n.specularColor.b,n.iridescence,n.iridescenceIOR,n.iridescenceThicknessRange[0],n.iridescenceThicknessRange[1],n.bumpScale,n.displacementScale,n.displacementMap,0,o[0],o[1],o[2],o[3],o[4],o[5],o[6],1,s[0],s[1],s[2],s[3],s[4],s[5],s[6],1,c[0],c[1],c[2],c[3],c[4],c[5],c[6],1,l[0],l[1],l[2],l[3],l[4],l[5],l[6],1,u[0],u[1],u[2],u[3],u[4],u[5],u[6],1,d[0],d[1],d[2],d[3],d[4],d[5],d[6],1,f[0],f[1],f[2],f[3],f[4],f[5],f[6],1];i.set(p,a)}return i}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Le.VEC4_PER_BVH_NODE*Le.FLOATS_PER_VEC4,i=t.length*r,a=new Float32Array(i);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,o=t[e],s=t[r];a[n]=o.boundsMin.x,a[n+1]=o.boundsMin.y,a[n+2]=o.boundsMin.z,a[n+3]=e,a[n+4]=o.boundsMax.x,a[n+5]=o.boundsMax.y,a[n+6]=o.boundsMax.z,a[n+7]=r,a[n+8]=s.boundsMin.x,a[n+9]=s.boundsMin.y,a[n+10]=s.boundsMin.z,a[n+12]=s.boundsMax.x,a[n+13]=s.boundsMax.y,a[n+14]=s.boundsMax.z}else a[n]=i.triangleOffset,a[n+1]=i.triangleCount,a[n+3]=-1}return a}async createMaterialTextures(e){let{materials:t,maps:r,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new Pa;let e=[];r&&r.length>0&&e.push(this.createTexturesToDataTexture(r).then(e=>({type:`albedo`,texture:e})).catch(e=>(console.warn(`Failed to create albedo textures:`,e),{type:`albedo`,texture:null}))),i&&i.length>0&&e.push(this.createTexturesToDataTexture(i).then(e=>({type:`normal`,texture:e})).catch(e=>(console.warn(`Failed to create normal textures:`,e),{type:`normal`,texture:null}))),a&&a.length>0&&e.push(this.createTexturesToDataTexture(a).then(e=>({type:`bump`,texture:e})).catch(e=>(console.warn(`Failed to create bump textures:`,e),{type:`bump`,texture:null}))),o&&o.length>0&&e.push(this.createTexturesToDataTexture(o).then(e=>({type:`roughness`,texture:e})).catch(e=>(console.warn(`Failed to create roughness textures:`,e),{type:`roughness`,texture:null}))),s&&s.length>0&&e.push(this.createTexturesToDataTexture(s).then(e=>({type:`metalness`,texture:e})).catch(e=>(console.warn(`Failed to create metalness textures:`,e),{type:`metalness`,texture:null}))),c&&c.length>0&&e.push(this.createTexturesToDataTexture(c).then(e=>({type:`emissive`,texture:e})).catch(e=>(console.warn(`Failed to create emissive textures:`,e),{type:`emissive`,texture:null}))),l&&l.length>0&&e.push(this.createTexturesToDataTexture(l).then(e=>({type:`displacement`,texture:e})).catch(e=>(console.warn(`Failed to create displacement textures:`,e),{type:`displacement`,texture:null})));let d=await Promise.allSettled(e),f={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:r}=e.value;if(r)switch(t){case`albedo`:r.colorSpace=n.SRGBColorSpace,f.albedoTexture=r;break;case`normal`:f.normalTexture=r;break;case`bump`:f.bumpTexture=r;break;case`roughness`:f.roughnessTexture=r;break;case`metalness`:f.metalnessTexture=r;break;case`emissive`:r.colorSpace=n.SRGBColorSpace,f.emissiveTexture=r;break;case`displacement`:f.displacementTexture=r;break}}});let p=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${p.toFixed(2)}ms)`),f}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);for(t=2**Math.ceil(Math.log2(t)),n=2**Math.ceil(Math.log2(n));t>=Le.MAX_TEXTURE_SIZE/2||n>=Le.MAX_TEXTURE_SIZE/2;)t=Math.max(1,Math.floor(t/2)),n=Math.max(1,Math.floor(n/2));return{maxWidth:t,maxHeight:n}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,r,i){let a=new n.DataArrayTexture(e,t,r,i);a.minFilter=n.LinearFilter,a.magFilter=n.LinearFilter,a.format=n.RGBAFormat,a.type=n.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],r=[],i=[];for(let r of e)if(r?.image){if(r.isCompressedTexture&&r.format===n.RGBAFormat&&r.mipmaps?.[0]?.data){let e=r.mipmaps[0],n=t.length;t.push(null),i.push({index:n,promise:Ia(e.data,e.width,e.height)});continue}if(r.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(r.image.data&&!(r.image instanceof HTMLImageElement)&&!(r.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&r.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,promise:Ia(r.image.data,r.image.width,r.image.height)});continue}t.push(r)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let n=0;n<i.length;n++){let{index:a}=i[n],o=e[n];if(o.status===`fulfilled`){let e=o.value;r.push(e),t[a]={image:e}}else console.warn(`[TextureCreator] Failed to create ImageBitmap:`,o.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let n=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(n,1,1));r.push(i),t[e]={image:i}}return{normalized:t,bitmapsToClose:r}}createFallbackTexture(){let e=new n.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=n.LinearFilter,e.magFilter=n.LinearFilter,e.format=n.RGBAFormat,e.type=n.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}combineTextureResults(e){return e[0]}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function Ia(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var La=128,Ra=class{constructor(){this._vectorPool={vec3:Array(9).fill().map(()=>new n.Vector3),vec2:[,,,,,,].fill().map(()=>new n.Vector2)},this._matrixPool={mat3:new n.Matrix3,mat4:new n.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){return this.resetArrays(),this._triangleCapacity=1024,this.triangleData=new Float32Array(this._triangleCapacity*H.FLOATS_PER_TRIANGLE),this.currentTriangleIndex=0,this.traverseObject(e),this.logStats(),this.getExtractedData()}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this._triangleCapacity;for(;t<e;)t*=2;let n=new Float32Array(t*H.FLOATS_PER_TRIANGLE);n.set(this.triangleData),this.triangleData=n,this._triangleCapacity=t}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=this.currentTriangleIndex;this.extractGeometry(e,t,n),this.meshTriangleRanges.push({start:r,count:this.currentTriangleIndex-r})}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,console.warn(`Depth write is disabled in material, enabling it for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t),n.clearcoat>0&&(this.sceneFeatures.hasClearcoat=!0),n.transmission>0&&(this.sceneFeatures.hasTransmission=!0),n.dispersion>0&&(this.sceneFeatures.hasDispersion=!0),n.iridescence>0&&(this.sceneFeatures.hasIridescence=!0),n.sheen>0&&(this.sceneFeatures.hasSheen=!0),(n.transparent||n.opacity<1||n.alphaTest>0)&&(this.sceneFeatures.hasTransparency=!0),[n.clearcoat>0,n.transmission>0,n.iridescence>0,n.sheen>0].filter(Boolean).length>=2&&(this.sceneFeatures.hasMultiLobeMaterials=!0)}return t}getMaterialAlphaMode(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:t===`MASK`?1:0}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===n.RGBAFormat&&e.transparent?2:0}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){return{emissive:new n.Color(0,0,0),emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:.1,attenuationColor:new n.Color(16777215),attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:new n.Color(0),specularIntensity:1,specularColor:new n.Color(16777215),clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:{x:1,y:1},bumpScale:1,displacementScale:1,alphaTest:0}}mapLegacyMaterialToPhysical(e,t){let r={};switch(t){case`basic`:r.emissive=e.color.clone(),r.emissiveIntensity=1,r.color=new n.Color(0),r.roughness=1,r.metalness=0;break;case`lambert`:r.roughness=1,r.metalness=0,r.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;r.roughness=Math.sqrt(2/(t+2)),r.metalness=0}if(e.specular){let t=e.specular.r*.299+e.specular.g*.587+e.specular.b*.114;r.specularIntensity=Math.min(t*2,1),r.specularColor=e.specular.clone()}break;case`toon`:r.roughness=.9,r.metalness=0;break;case`standard`:case`physical`:break}return r}createMaterialObject(e){let t=this.getPhysicalDefaults(),r=this.getMaterialType(e),i=this.mapLegacyMaterialToPhysical(e,r),a=(e.metalness??i.metalness??0)>.1,o=t.ior;a?o=2.5:e.transmission>0&&(o=1.5);let s=e.color||new n.Color(16777215);return r===`basic`&&!e.map&&(s=new n.Color(0)),{uuid:e.uuid,color:s,emissive:i.emissive??e.emissive??t.emissive,emissiveIntensity:i.emissiveIntensity??e.emissiveIntensity??t.emissiveIntensity,roughness:Math.max(.05,i.roughness??e.roughness??t.roughness),metalness:i.metalness??e.metalness??t.metalness,ior:e.ior??o,opacity:e.opacity??t.opacity,transmission:e.transmission??t.transmission,thickness:e.thickness??t.thickness,attenuationColor:e.attenuationColor??t.attenuationColor,attenuationDistance:e.attenuationDistance??t.attenuationDistance,dispersion:e.dispersion??t.dispersion,sheen:e.sheen??t.sheen,sheenRoughness:e.sheenRoughness??t.sheenRoughness,sheenColor:e.sheenColor??t.sheenColor,clearcoat:e.clearcoat??t.clearcoat,clearcoatRoughness:e.clearcoatRoughness??t.clearcoatRoughness,iridescence:e.iridescence??t.iridescence,iridescenceIOR:e.iridescenceIOR??t.iridescenceIOR,iridescenceThicknessRange:e.iridescenceThicknessRange??t.iridescenceThicknessRange,specularIntensity:i.specularIntensity??e.specularIntensity??t.specularIntensity,specularColor:i.specularColor??e.specularColor??t.specularColor,normalScale:e.normalScale??t.normalScale,bumpScale:e.bumpScale??t.bumpScale,displacementScale:e.displacementScale??t.displacementScale,transparent:e.transparent?1:0,alphaTest:e.alphaTest??t.alphaTest,alphaMode:this.getMaterialAlphaMode(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(e.map,this.maps),normalMap:this.processTexture(e.normalMap,this.normalMaps),bumpMap:this.processTexture(e.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(e.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(e.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(e.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(e.displacementMap,this.displacementMaps),clearcoatMap:this.processTexture(e.clearcoatMap,[]),clearcoatRoughnessMap:this.processTexture(e.clearcoatRoughnessMap,[]),transmissionMap:this.processTexture(e.transmissionMap,[]),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(e.sheenColorMap,[]),sheenRoughnessMap:this.processTexture(e.sheenRoughnessMap,[]),specularIntensityMap:this.processTexture(e.specularIntensityMap,[]),specularColorMap:this.processTexture(e.specularColorMap,[]),iridescenceMap:this.processTexture(e.iridescenceMap,[]),iridescenceThicknessMap:this.processTexture(e.iridescenceThicknessMap,[]),mapMatrix:this.getTextureMatrix(e.map),normalMapMatrices:this.getTextureMatrix(e.normalMap),bumpMapMatrices:this.getTextureMatrix(e.bumpMap),roughnessMapMatrices:this.getTextureMatrix(e.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(e.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(e.emissiveMap),displacementMapMatrices:this.getTextureMatrix(e.displacementMap),originalType:r}}getTextureMatrix(e){return e?(e.updateMatrix(),e.matrix.elements):new n.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case n.FrontSide:return 0;case n.BackSide:return 1;case n.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<La){t.push(e);let i=t.length-1;return n.set(r,i),i}return-1}extractGeometry(e,t,n){e.updateMatrix(),e.updateMatrixWorld();let r=e.geometry;r.attributes.normal||r.computeVertexNormals();let i=r.attributes.position,a=r.attributes.normal,o=r.attributes.uv,s=r.index?r.index.array:null;this._matrixPool.mat4.copy(e.matrixWorld),this._matrixPool.mat3.getNormalMatrix(this._matrixPool.mat4);let c=s?s.length/3:i.count/3;this.extractTrianglesInBatch(i,a,o,s,c,t,n)}extractTrianglesInBatch(e,t,n,r,i,a,o){let s=this._getVec3(0),c=this._getVec3(1),l=this._getVec3(2),u=this._getVec3(3),d=this._getVec3(4),f=this._getVec3(5),p=this._getVec2(0),m=this._getVec2(1),h=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);for(let g=0;g<i;g++){let i=g*3,_=r?r[i+0]:i+0,v=r?r[i+1]:i+1,y=r?r[i+2]:i+2;this.getVertex(e,_,s),this.getVertex(e,v,c),this.getVertex(e,y,l),this.getVertex(t,_,u),this.getVertex(t,v,d),this.getVertex(t,y,f),n?(this.getVertex(n,_,p),this.getVertex(n,v,m),this.getVertex(n,y,h)):(p.set(0,0),m.set(0,0),h.set(0,0)),s.applyMatrix4(this._matrixPool.mat4),c.applyMatrix4(this._matrixPool.mat4),l.applyMatrix4(this._matrixPool.mat4),u.applyMatrix3(this._matrixPool.mat3).normalize(),d.applyMatrix3(this._matrixPool.mat3).normalize(),f.applyMatrix3(this._matrixPool.mat3).normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,s,c,l,u,d,f,p,m,h,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=e*H.FLOATS_PER_TRIANGLE;this.triangleData[f+H.POSITION_A_OFFSET+0]=t.x,this.triangleData[f+H.POSITION_A_OFFSET+1]=t.y,this.triangleData[f+H.POSITION_A_OFFSET+2]=t.z,this.triangleData[f+H.POSITION_A_OFFSET+3]=0,this.triangleData[f+H.POSITION_B_OFFSET+0]=n.x,this.triangleData[f+H.POSITION_B_OFFSET+1]=n.y,this.triangleData[f+H.POSITION_B_OFFSET+2]=n.z,this.triangleData[f+H.POSITION_B_OFFSET+3]=0,this.triangleData[f+H.POSITION_C_OFFSET+0]=r.x,this.triangleData[f+H.POSITION_C_OFFSET+1]=r.y,this.triangleData[f+H.POSITION_C_OFFSET+2]=r.z,this.triangleData[f+H.POSITION_C_OFFSET+3]=0,this.triangleData[f+H.NORMAL_A_OFFSET+0]=i.x,this.triangleData[f+H.NORMAL_A_OFFSET+1]=i.y,this.triangleData[f+H.NORMAL_A_OFFSET+2]=i.z,this.triangleData[f+H.NORMAL_A_OFFSET+3]=0,this.triangleData[f+H.NORMAL_B_OFFSET+0]=a.x,this.triangleData[f+H.NORMAL_B_OFFSET+1]=a.y,this.triangleData[f+H.NORMAL_B_OFFSET+2]=a.z,this.triangleData[f+H.NORMAL_B_OFFSET+3]=0,this.triangleData[f+H.NORMAL_C_OFFSET+0]=o.x,this.triangleData[f+H.NORMAL_C_OFFSET+1]=o.y,this.triangleData[f+H.NORMAL_C_OFFSET+2]=o.z,this.triangleData[f+H.NORMAL_C_OFFSET+3]=0,this.triangleData[f+H.UV_AB_OFFSET+0]=s.x,this.triangleData[f+H.UV_AB_OFFSET+1]=s.y,this.triangleData[f+H.UV_AB_OFFSET+2]=c.x,this.triangleData[f+H.UV_AB_OFFSET+3]=c.y,this.triangleData[f+H.UV_C_MAT_OFFSET+0]=l.x,this.triangleData[f+H.UV_C_MAT_OFFSET+1]=l.y,this.triangleData[f+H.UV_C_MAT_OFFSET+2]=u,this.triangleData[f+H.UV_C_MAT_OFFSET+3]=d}getTriangleData(){return this.triangleData?this.triangleData.subarray(0,this.currentTriangleIndex*H.FLOATS_PER_TRIANGLE):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*H.FLOATS_PER_TRIANGLE*4;console.log(`materials:`,this.materials.length),console.log(`triangles:`,this.currentTriangleIndex),console.log(`triangle data size (MB):`,(e/(1024*1024)).toFixed(2)),console.log(`maps:`,this.maps.length)}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this.triangleData=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.meshes=[],this.meshTriangleRanges=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap,this.sceneFeatures={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0}}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,directionalLights:this.directionalLights,cameras:this.cameras,sceneFeatures:this.sceneFeatures}}},za=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=(t,r)=>{let s=a++,c=s*16,l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0,h=0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];l=Math.min(l,t.bMinX),u=Math.min(u,t.bMinY),d=Math.min(d,t.bMinZ),f=Math.max(f,t.bMaxX),p=Math.max(p,t.bMaxY),m=Math.max(m,t.bMaxZ),h+=t.power,g=Math.min(g,t.cx),_=Math.min(_,t.cy),v=Math.min(v,t.cz),y=Math.max(y,t.cx),b=Math.max(b,t.cy),x=Math.max(x,t.cz)}i[c+0]=l,i[c+1]=u,i[c+2]=d,i[c+3]=h,i[c+4]=f,i[c+5]=p,i[c+6]=m,i[c+12]=0,i[c+13]=0,i[c+14]=0,i[c+15]=0;let S=r-t;if(S<=this.maxLeafSize)i[c+7]=1,i[c+8]=t,i[c+9]=S,i[c+10]=0,i[c+11]=0;else{let a=y-g,s=b-_,l=x-v,u;u=a>=s&&a>=l?0:s>=l?1:2;let d=[`cx`,`cy`,`cz`][u],f=t+r>>1;this._nthElement(n,e,t,r,f,d),i[c+7]=0;let p=o(t,f),m=o(f,r);i[c+8]=p,i[c+9]=m,i[c+10]=0,i[c+11]=0}return s};o(0,t);let s=new Int32Array(t);for(let e=0;e<t;e++)s[e]=n[e];let c=new Float32Array(a*16);return c.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:c,nodeCount:a,sortedPerm:s}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}},Ba=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0}extractEmissiveTriangles(e,t,n){console.log(`[EmissiveTriangleBuilder] Extracting emissive triangles...`),this.emissiveTriangles=[],this.totalEmissivePower=0;let r=H.FLOATS_PER_TRIANGLE,i=H.UV_C_MAT_OFFSET+2;for(let a=0;a<n;a++){let n=a*r,o=Math.floor(e[n+i]),s=t[o];if(!s)continue;let c=s.emissive||{r:0,g:0,b:0},l=s.emissiveIntensity||0;if(l>0&&(c.r>0||c.g>0||c.b>0)){let t=e[n+0],r=e[n+1],i=e[n+2],s=e[n+4],u=e[n+5],d=e[n+6],f=e[n+8],p=e[n+9],m=e[n+10],h=this._calculateTriangleArea(t,r,i,s,u,d,f,p,m),g=(c.r+c.g+c.b)/3*l*h,_=(t+s+f)/3,v=(r+u+p)/3,y=(i+d+m)/3,b=Math.min(t,s,f),x=Math.min(r,u,p),S=Math.min(i,d,m),C=Math.max(t,s,f),w=Math.max(r,u,p),T=Math.max(i,d,m);this.emissiveTriangles.push({triangleIndex:a,materialIndex:o,power:g,area:h,emissive:{r:c.r,g:c.g,b:c.b},emissiveIntensity:l,cx:_,cy:v,cz:y,bMinX:b,bMinY:x,bMinZ:S,bMaxX:C,bMaxY:w,bMaxZ:T}),this.totalEmissivePower+=g}}return this.emissiveCount=this.emissiveTriangles.length,console.log(`[EmissiveTriangleBuilder] Found ${this.emissiveCount} emissive triangles (${(this.emissiveCount/n*100).toFixed(2)}%)`),console.log(`[EmissiveTriangleBuilder] Total emissive power: ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new n.DataTexture(new Float32Array(4),1,1,n.RGBAFormat,n.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),r=Math.ceil(this.emissiveCount/t),i=t*r*4,a=new Float32Array(i);a.set(e);let o=new n.DataTexture(a,t,r,n.RGBAFormat,n.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=n.NearestFilter,o.magFilter=n.NearestFilter,console.log(`[EmissiveTriangleBuilder] Created ${t}x${r} emissive texture (${this.emissiveCount} emissives)`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return console.log(`[EmissiveTriangleBuilder] Created emissive raw data: ${this.emissiveCount} entries (${e.byteLength} bytes)`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=t.emissive||{r:0,g:0,b:0},o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=(a.r+a.g+a.b)/3;this.totalEmissivePower=0;for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t];n.materialIndex===e&&(n.power=c*o*n.area,n.emissive={r:a.r,g:a.g,b:a.b},n.emissiveIntensity=o,this.emissivePowerArray[t]=n.power),this.totalEmissivePower+=this.emissiveTriangles[t].power}return this._buildCDF(),!0}buildLightBVH(){if(this.emissiveCount===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeCount=1,1;let{nodeData:e,nodeCount:t,sortedPerm:n}=new za().build(this.emissiveTriangles);return this.lightBVHNodeData=e,this.lightBVHNodeCount=t,this._rebuildSortedEmissiveData(n),t}_rebuildSortedEmissiveData(e){let t=e.length;this.emissiveIndicesArray=new Int32Array(t),this.emissivePowerArray=new Float32Array(t);for(let n=0;n<t;n++){let t=e[n];this.emissiveIndicesArray[n]=this.emissiveTriangles[t].triangleIndex,this.emissivePowerArray[n]=this.emissiveTriangles[t].power}this._buildCDF();let n=new Float32Array(t*8);for(let r=0;r<t;r++){let t=e[r],i=this.emissiveTriangles[t],a=r*8;n[a+0]=i.triangleIndex,n[a+1]=i.power,n[a+2]=this.cdfArray[r],n[a+3]=this.totalEmissivePower>0?i.power/this.totalEmissivePower:0,n[a+4]=i.emissive.r*i.emissiveIntensity,n[a+5]=i.emissive.g*i.emissiveIntensity,n[a+6]=i.emissive.b*i.emissiveIntensity,n[a+7]=i.area}this.emissiveTriangleData=n,console.log(`[EmissiveTriangleBuilder] Rebuilt sorted emissive data: ${t} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0}},Va=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,...e},this.triangleData=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvhData=null,this.materialData=null,this.instanceTable=null,this.originalToBvhMap=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.albedoTextures=null,this.normalTextures=null,this.bumpTextures=null,this.roughnessTextures=null,this.metalnessTextures=null,this.emissiveTextures=null,this.displacementTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}_initProcessors(){this.geometryExtractor=new Ra,this.bvhBuilder=new ha,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement}),this.textureCreator=new Fa,this.emissiveTriangleBuilder=new Ba,this.tlasBuilder=new Aa}_log(e,t){this.config.verbose&&console.log(`[SceneProcessor] ${e}`,t||``)}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`;let t=new oa(`SceneProcessor (${e.name||`scene`})`);try{this._reset(),this._log(`Starting scene processing`),this.processingStage=`extraction`,t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,z({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||z({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvhData&&(this.bvhData=this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,z({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,console.error(`[SceneProcessor] Processing error:`,e),z({status:`Error: ${e.message}`,progress:100}),e}finally{this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this.triangleData=n.triangleData,this.triangleCount=n.triangleCount,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangleData.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.materialCount=this.materials.length,this.meshes=n.meshes,this.meshTriangleRanges=n.meshTriangleRanges,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.directionalLights=n.directionalLights,this.cameras=n.cameras,this.sceneFeatures=n.sceneFeatures;let r=performance.now()-t;this._log(`Geometry extraction complete (${r.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw console.error(`[SceneProcessor] Geometry extraction error:`,e),z({status:`Extraction error: ${e.message}`,progress:25}),e}}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`);let e=performance.now();try{let t=H.FLOATS_PER_TRIANGLE,n=this.meshTriangleRanges;if(!n||n.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);this.instanceTable=new ja,this.instanceTable.allocate(n.length);let r=n.length,i=this.config.enableTreeletOptimization,a=[],o=[];for(let e=0;e<r;e++){let t=n[e];t.count!==0&&(t.count>=2e5&&Da(t.count)?o.push({m:e,range:t}):a.push({m:e,range:t}))}let s={depth:this.config.bvhDepth,treeletOptimization:{enabled:i!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},c=a.length+o.length,l=this._buildBLASesWithPool(a,s,e=>{z({status:`Building BLAS ${e+o.length}/${c}...`,progress:25+Math.floor(e/c*45)})}),u=o.map(({m:e,range:n})=>wa(this.triangleData.slice(n.start*t,(n.start+n.count)*t),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...s}).then(t=>({m:e,range:n,result:t}))),[d,f]=await Promise.all([l,Promise.all(u)]);for(let{m:e,range:n,result:r}of[...d,...f])r.reorderedTriangles&&this.triangleData.set(r.reorderedTriangles,n.start*t),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:n.start,triCount:n.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData});z({status:`Built all BLASes`,progress:70}),z({status:`Building TLAS...`,progress:72});let p=this.instanceTable.entries.filter(e=>e!==null);if(p.length===1){let e=p[0];this.bvhData=e.bvhData,this.instanceTable.assignOffsets(0),this._buildGlobalOriginalToBvhMap(),e.originalToBvhMap=null,e.bvhData=null}else{this.instanceTable.computeAABBs(this.triangleData);let{root:e,nodeCount:t}=this.tlasBuilder.build(p);this.instanceTable.assignOffsets(t);let n=this.instanceTable.totalNodeCount,r=this.tlasBuilder.flatten(e,p);this.bvhData=new Float32Array(n*16),this.bvhData.set(r);for(let e of p){let t=e.blasOffset*16;this.bvhData.set(e.bvhData,t),this._offsetBLASInPlace(t,e.bvhData.length/16,e.blasOffset,e.triOffset)}this._buildGlobalOriginalToBvhMap();for(let e of p)e.originalToBvhMap=null,e.bvhData=null}this.bvhRoot=!0,this._disposeRefitWorker();let m=performance.now()-e;this._log(`BVH complete: ${p.length} mesh(es), ${this.bvhData.length/16} nodes (${m.toFixed(2)}ms)`),z({status:`BVH construction complete`,progress:75})}catch(e){throw console.error(`[SceneProcessor] BVH building error:`,e),z({status:`BVH error: ${e.message}`,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){for(let i=0;i<t;i++){let t=e+i*16;this.bvhData[t+3]===-1?this.bvhData[t]+=r:(this.bvhData[t+3]+=n,this.bvhData[t+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=H.FLOATS_PER_TRIANGLE,i=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),a=[],o=0,s=0;return new Promise((c,l)=>{let u=[],d=n=>{if(o>=e.length){n.terminate(),u.splice(u.indexOf(n),1),u.length===0&&c(a);return}let{m:i,range:s}=e[o++],l=this.triangleData.slice(s.start*r,(s.start+s.count)*r),d=s.count,f=d<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:i,range:s},n.postMessage({triangleData:l.buffer,triangleByteOffset:l.byteOffset,triangleByteLength:l.byteLength,triangleCount:d,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:f,reinsertionOptimization:t.reinsertionOptimization},[l.buffer])},f=(e,t)=>{let r=t.data;if(r.error){u.forEach(e=>e.terminate()),l(Error(r.error));return}if(r.progress!==void 0)return;let{m:i,range:o}=e._currentTask;a.push({m:i,range:o,result:{bvhData:r.bvhData,reorderedTriangles:r.triangles||null,originalToBvh:r.originalToBvh||null}}),s++,n?.(s),d(e)};for(let e=0;e<i;e++){let e=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BqQTDljT.js`).href:new URL(`assets/BVHWorker-BqQTDljT.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});e.onmessage=t=>f(e,t),e.onerror=e=>{u.forEach(e=>e.terminate()),l(e)},u.push(e),d(e)}})}_buildGlobalOriginalToBvhMap(){this.originalToBvhMap=new Uint32Array(this.triangleCount);for(let e of this.instanceTable.entries){if(!e)continue;let t=new Uint32Array(e.triCount);if(e.originalToBvhMap)for(let n=0;n<e.triCount;n++){let r=e.originalToBvhMap[n];this.originalToBvhMap[e.triOffset+n]=e.triOffset+r,t[r]=n}else for(let n=0;n<e.triCount;n++)this.originalToBvhMap[e.triOffset+n]=e.triOffset+n,t[n]=n;e.bvhToOriginal=t}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let e=[{data:this.maps,prop:`albedoTextures`},{data:this.normalMaps,prop:`normalTextures`},{data:this.bumpMaps,prop:`bumpTextures`},{data:this.roughnessMaps,prop:`roughnessTextures`},{data:this.metalnessMaps,prop:`metalnessTextures`},{data:this.emissiveMaps,prop:`emissiveTextures`},{data:this.displacementMaps,prop:`displacementTextures`}];await Promise.all(e.filter(({data:e})=>e?.length>0).map(({data:e,prop:t})=>this.textureCreator.createTexturesToDataTexture(e).then(e=>{this[t]=e}))),this._log(`Material textures complete`,{materialData:!!this.materialData})}catch(e){throw console.error(`[SceneProcessor] Texture creation error:`,e),e}}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangleData,this.materials,this.triangleCount),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this.triangleData=null,this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvhData=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}_disposeTextures(){[`albedoTextures`,`normalTextures`,`bumpTextures`,`roughnessTextures`,`metalnessTextures`,`emissiveTextures`,`displacementTextures`].forEach(e=>{this[e]&&(typeof this[e].dispose==`function`&&this[e].dispose(),this[e]=null)})}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.materialCount=this.materials.length,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.sceneFeatures=n.sceneFeatures;let r={materials:this.materials,triangles:this.triangleData,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,displacementMaps:this.displacementMaps,bvhRoot:this.bvhRoot},i=await this.textureCreator.createMaterialTextures(r);this.materialData=this.textureCreator.createMaterialRawData(this.materials),this.albedoTextures=i.albedoTexture,this.normalTextures=i.normalTexture,this.bumpTextures=i.bumpTexture,this.roughnessTextures=i.roughnessTexture,this.metalnessTextures=i.metalnessTexture,this.emissiveTextures=i.emissiveTexture,this.displacementTextures=i.displacementTexture;let a=performance.now()-t;return this._log(`Material rebuild complete (${a.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw console.error(`[SceneProcessor] Material rebuild error:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){[`albedoTextures`,`normalTextures`,`bumpTextures`,`roughnessTextures`,`metalnessTextures`,`emissiveTextures`,`displacementTextures`].forEach(e=>{if(this[e])try{typeof this[e].dispose==`function`&&this[e].dispose()}catch(t){console.warn(`[SceneProcessor] Error disposing ${e}:`,t)}finally{this[e]=null}}),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvhData,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangleData?(this.triangleData.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement})),this._log(`Configuration updated`,this.config)}async refitBVH(e,t){if(!this.bvhData||!this.triangleData||!this.originalToBvhMap)throw Error(`No BVH data available for refit. Run buildBVH() first.`);if(this._refitWorker||=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHRefitWorker-GkmNJYvb.js`).href:new URL(`assets/BVHRefitWorker-GkmNJYvb.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),!this._refitSharedBuffers){let t=new SharedArrayBuffer(this.bvhData.byteLength),n=new SharedArrayBuffer(this.triangleData.byteLength),r=new SharedArrayBuffer(e.byteLength),i=new Float32Array(t),a=new Float32Array(n);i.set(this.bvhData),a.set(this.triangleData),this.bvhData=i,this.triangleData=a;let o=this.originalToBvhMap.length,s=new Uint32Array(o);for(let e=0;e<o;e++)s[this.originalToBvhMap[e]]=e;this._refitSharedBuffers={bvhBuf:t,triBuf:n,posBuf:r,posView:new Float32Array(r)},this._refitWorker.postMessage({type:`init`,sharedBvhBuf:t,sharedTriBuf:n,sharedPosBuf:r,bvhToOriginal:s},[s.buffer])}return this._refitSharedBuffers.posView.set(e),new Promise((e,n)=>{this._refitWorker.onmessage=r=>{let i=r.data;i.type===`refitComplete`?(t&&this._patchSmoothNormals(t),e({refitTimeMs:i.refitTimeMs})):i.type===`error`&&n(Error(i.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){this._patchNormalsRange(e,0,this.originalToBvhMap.length)}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvhData||!this.triangleData)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=performance.now();this._blasRefitter||=new ba;for(let r of e){let e=this.instanceTable.entries[r];e&&(this._updateMeshTrianglePositions(e,t),n&&this._patchMeshSmoothNormals(e,n),this._blasRefitter.refitRange(this.bvhData,this.triangleData,e.blasOffset,e.blasNodeCount),this.instanceTable.recomputeAABB(r,this.bvhData,this.triangleData))}return this._refitTLAS(),{refitTimeMs:performance.now()-r}}computeBLASDirtyRanges(e){let t=H.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable.entries[i];e&&(n.push({offset:e.triOffset*t,count:e.triCount*t}),r.push({offset:e.blasOffset*16,count:e.blasNodeCount*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangleData?(e.setTriangleData(this.triangleData,this.triangleCount),this.bvhData?(e.setBVHData(this.bvhData),this.materialData?e.materialData.setMaterialData(this.materialData):console.warn(`SceneProcessor: No material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({albedoMaps:this.albedoTextures,normalMaps:this.normalTextures,bumpMaps:this.bumpTextures,roughnessMaps:this.roughnessTextures,metalnessMaps:this.metalnessTextures,emissiveMaps:this.emissiveTextures,displacementMaps:this.displacementTextures}),this.emissiveTriangleData&&e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n),!0):(console.error(`SceneProcessor: Failed to get BVH data`),!1)):(console.error(`SceneProcessor: Failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangleData,this.materials,this.triangleCount))?null:{rawData:this.emissiveTriangleBuilder.createEmissiveRawData(),emissiveCount:this.emissiveTriangleBuilder.emissiveCount,totalPower:this.emissiveTriangleBuilder.totalEmissivePower}}_updateMeshTrianglePositions(e,t){let n=H.FLOATS_PER_TRIANGLE,r=H.POSITION_A_OFFSET,i=H.POSITION_B_OFFSET,a=H.POSITION_C_OFFSET,o=H.NORMAL_A_OFFSET,s=H.NORMAL_B_OFFSET,c=H.NORMAL_C_OFFSET,l=e.bvhToOriginal;for(let u=0;u<e.triCount;u++){let d=l[u],f=(e.triOffset+u)*n,p=(e.triOffset+d)*9,m=t[p],h=t[p+1],g=t[p+2],_=t[p+3],v=t[p+4],y=t[p+5],b=t[p+6],x=t[p+7],S=t[p+8];this.triangleData[f+r]=m,this.triangleData[f+r+1]=h,this.triangleData[f+r+2]=g,this.triangleData[f+i]=_,this.triangleData[f+i+1]=v,this.triangleData[f+i+2]=y,this.triangleData[f+a]=b,this.triangleData[f+a+1]=x,this.triangleData[f+a+2]=S;let C=_-m,w=v-h,T=y-g,E=b-m,D=x-h,O=S-g,k=w*O-T*D,A=T*E-C*O,j=C*D-w*E;this.triangleData[f+o]=k,this.triangleData[f+o+1]=A,this.triangleData[f+o+2]=j,this.triangleData[f+s]=k,this.triangleData[f+s+1]=A,this.triangleData[f+s+2]=j,this.triangleData[f+c]=k,this.triangleData[f+c+1]=A,this.triangleData[f+c+2]=j}}_patchMeshSmoothNormals(e,t){this._patchNormalsRange(t,e.triOffset,e.triCount)}_patchNormalsRange(e,t,n){let r=H.FLOATS_PER_TRIANGLE,i=H.NORMAL_A_OFFSET,a=H.NORMAL_B_OFFSET,o=H.NORMAL_C_OFFSET;for(let s=0;s<n;s++){let n=t+s,c=this.originalToBvhMap[n]*r,l=n*9;this.triangleData[c+i]=e[l],this.triangleData[c+i+1]=e[l+1],this.triangleData[c+i+2]=e[l+2],this.triangleData[c+a]=e[l+3],this.triangleData[c+a+1]=e[l+4],this.triangleData[c+a+2]=e[l+5],this.triangleData[c+o]=e[l+6],this.triangleData[c+o+1]=e[l+7],this.triangleData[c+o+2]=e[l+8]}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6)),this._blasOffsetMap||=new Map,this._blasOffsetMap.clear();for(let e of this.instanceTable.entries)e&&this._blasOffsetMap.set(e.blasOffset,e);for(let t=e-1;t>=0;t--){let e=t*16,n=this.bvhData[e+3];if(n===-2){let n=this.bvhData[e],r=this._blasOffsetMap.get(n);if(r&&r.worldAABB){let e=t*6;this._tlasBounds[e]=r.worldAABB.minX,this._tlasBounds[e+1]=r.worldAABB.minY,this._tlasBounds[e+2]=r.worldAABB.minZ,this._tlasBounds[e+3]=r.worldAABB.maxX,this._tlasBounds[e+4]=r.worldAABB.maxY,this._tlasBounds[e+5]=r.worldAABB.maxZ}}else if(n>=0){let n=this.bvhData[e+3],r=this.bvhData[e+7],i=n*6,a=r*6,o=this._tlasBounds;this.bvhData[e]=o[i],this.bvhData[e+1]=o[i+1],this.bvhData[e+2]=o[i+2],this.bvhData[e+4]=o[i+3],this.bvhData[e+5]=o[i+4],this.bvhData[e+6]=o[i+5],this.bvhData[e+8]=o[a],this.bvhData[e+9]=o[a+1],this.bvhData[e+10]=o[a+2],this.bvhData[e+12]=o[a+3],this.bvhData[e+13]=o[a+4],this.bvhData[e+14]=o[a+5];let s=t*6;o[s]=Math.min(o[i],o[a]),o[s+1]=Math.min(o[i+1],o[a+1]),o[s+2]=Math.min(o[i+2],o[a+2]),o[s+3]=Math.max(o[i+3],o[a+3]),o[s+4]=Math.max(o[i+4],o[a+4]),o[s+5]=Math.max(o[i+5],o[a+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangleData)return;let n=H.FLOATS_PER_TRIANGLE;this._rebuildGeneration++;let r=this._rebuildGeneration;for(let i of e){let e=this.instanceTable.entries[i];if(!e)continue;let a=this._pendingRebuilds.get(i);a&&a.terminate();let o=this.triangleData.slice(e.triOffset*n,(e.triOffset+e.triCount)*n),s=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BqQTDljT.js`).href:new URL(`assets/BVHWorker-BqQTDljT.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});this._pendingRebuilds.set(i,s),s.onmessage=n=>{let a=n.data;if(s.terminate(),this._pendingRebuilds.delete(i),a.error){console.error(`Background BLAS rebuild error (mesh ${i}):`,a.error);return}r===this._rebuildGeneration&&this._swapBLAS(i,e,a,t)},s.onerror=e=>{console.error(`Background BLAS rebuild worker error (mesh ${i}):`,e),s.terminate(),this._pendingRebuilds.delete(i)};let c=e.triCount>500;s.postMessage({triangleData:o.buffer,triangleByteOffset:o.byteOffset,triangleByteLength:o.byteLength,triangleCount:e.triCount,depth:this.config.bvhDepth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:c,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[o.buffer])}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a!==t.blasNodeCount){console.warn(`Background rebuild: node count mismatch for mesh ${e} (${a} vs ${t.blasNodeCount}), skipping swap`);return}let o=t.blasOffset*16;this.bvhData.set(i,o),this._offsetBLASInPlace(o,a,t.blasOffset,t.triOffset);let s=H.FLOATS_PER_TRIANGLE,c=n.triangles;c&&this.triangleData.set(c,t.triOffset*s);let l=n.originalToBvh;if(l){for(let e=0;e<t.triCount;e++)this.originalToBvhMap[t.triOffset+e]=t.triOffset+l[e];let e=new Uint32Array(t.triCount);for(let n=0;n<t.triCount;n++)e[l[n]]=n;t.bvhToOriginal=e}this.instanceTable.recomputeAABB(e,this.bvhData,this.triangleData),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.()}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},Ha=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new n.Vector3);r=t.sub(i).normalize()}else r=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0;this.directionalLightCache.push({data:[r.x,r.y,r.z,e.color.r,e.color.g,e.color.b,e.intensity,a],importance:i,light:e})}addRectAreaLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=e.getWorldQuaternion(new n.Quaternion),i=e.getWorldScale(new n.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new n.Vector3(a,0,0).applyQuaternion(r),c=new n.Vector3(0,-o,0).applyQuaternion(r),l=this.calculateLightImportance(e,`area`);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,e.color.r,e.color.g,e.color.b,e.intensity],importance:l,light:e})}addPointLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=this.calculateLightImportance(e,`point`);this.pointLightCache.push({data:[t.x,t.y,t.z,e.color.r,e.color.g,e.color.b,e.intensity,e.distance||0,e.decay===void 0?2:e.decay],importance:r,light:e})}addSpotLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=(e.target?e.target.getWorldPosition(new n.Vector3):new n.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`);this.spotLightCache.push({data:[t.x,t.y,t.z,r.x,r.y,r.z,e.color.r,e.color.g,e.color.b,e.intensity,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/8),n=Math.floor(this.lightData.rectArea.length/13),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/14);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},Ua=`https://assets.rayzee.atulmourya.com/noise/simple_bluenoise.png`,Wa=4,Ga=class extends L{constructor(e,t,r,i={}){super(`PathTracer`,{...i,executionMode:I.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=r,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.tileManager=new ge(a,o,V.tiles),this.sdfs=new Va,this.lightSerializer=new Ha,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Oe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ae(0,0),this.uniforms=new He(a,o),this._defineUniformGetters(),this.materialData=new We(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.environment=new yt(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new ca,this._initRenderingState(),this.setupBlueNoise(),this.tempVector2=new n.Vector2,this.lastCameraMatrix=new n.Matrix4,this.lastProjectionMatrix=new n.Matrix4,this.lastRenderMode=-1,this.tileCompletionFrame=0,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.adaptiveSamplingFrameToggle=!1,this.lastInteractionModeState=!1,this.cameraChanged=!1,this.tileChanged=!1,this.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.blueNoiseTexture=null,this.emissiveTriangleStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(4),4),this.emissiveTriangleStorageNode=(0,o.storage)(this.emissiveTriangleStorageAttr,`vec4`,1).toReadOnly(),this.lightBVHStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightBVHStorageNode=(0,o.storage)(this.lightBVHStorageAttr,`vec4`,1).toReadOnly(),this.meshVisibilityStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([1,0,0,0]),4),this.meshVisibilityStorageNode=(0,o.storage)(this.meshVisibilityStorageAttr,`vec4`,1).toReadOnly(),this.adaptiveSamplingTexture=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new _e(this.renderer,{uniforms:{maxBounceCount:{get value(){return e.maxBounces.value},set value(t){e.maxBounces.value=t}},numRaysPerPixel:{get value(){return e.samplesPerPixel.value},set value(t){e.samplesPerPixel.value=t}},useAdaptiveSampling:{get value(){return e.useAdaptiveSampling.value},set value(t){e.useAdaptiveSampling.value=t}},useEnvMapIS:{get value(){return e.useEnvMapIS.value},set value(t){e.useEnvMapIS.value=t}},enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},enableEmissiveTriangleSampling:{get value(){return e.enableEmissiveTriangleSampling.value},set value(t){e.enableEmissiveTriangleSampling.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,enableEmissiveTriangleSampling:!1},onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupBlueNoise(){let e=new n.TextureLoader;e.setCrossOrigin(`anonymous`),e.load(Ua,e=>{e.minFilter=n.NearestFilter,e.magFilter=n.NearestFilter,e.wrapS=n.RepeatWrapping,e.wrapT=n.RepeatWrapping,e.type=n.FloatType,e.generateMipmaps=!1,this.blueNoiseTexture=e,j.value=e,console.log(`PathTracer: Blue noise loaded ${e.image.width}x${e.image.height}`)})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.materialData.injectMaterialFeatureDefines(),this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.materialData.setMaterialData(this.sdfs.materialData),this.totalTriangleCount.value=this.sdfs.triangleCount||0,this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};if(this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this.hasSun.value){let t=this.environment.envParams.skySunIntensity*950,n={intensity:t,color:{r:1,g:1,b:1},userData:{angle:this.sunAngularSize.value},updateMatrixWorld:()=>{},getWorldPosition:e=>{let t=this.sunDirection.value;return e.set(t.x,t.y,t.z).multiplyScalar(1e10)}};this.lightSerializer.addDirectionalLight(n),this.lightSerializer.preprocessLights(),this.lightSerializer.updateShaderUniforms(e),this.directionalLightsData=e.uniforms.directionalLights.value,console.log(`Sun added as directional light (intensity: ${t.toFixed(2)})`)}this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/8)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/13)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/14)):this.numSpotLights.value=0}reset(){this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.tileManager.spiralOrder=this.tileManager.generateSpiralOrder(this.tileManager.tiles),this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastRenderMode=-1,this.tileCompletionFrame=0,this.lastInteractionModeState=!1}setTileCount(e){this.tileManager.setTileCount(e),this.updateCompletionThreshold(),this.reset()}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.tileManager.setSize(e,t),this.createStorageTextures(e,t),this.shaderBuilder.setSize(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=e?1:0}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get tiles(){return this.tileManager.tiles}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}setTriangleData(e,n){if(!e)return;let r=e.length/4;this.triangleStorageNode?(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=r):(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode=(0,o.storage)(this.triangleStorageAttr,`vec4`,r).toReadOnly()),this.triangleCount=n,console.log(`PathTracer: ${this.triangleCount} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let n=e.length/4;this.bvhStorageNode?(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=n):(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode=(0,o.storage)(this.bvhStorageAttr,`vec4`,n).toReadOnly()),this.bvhNodeCount=Math.floor(n/Wa),console.log(`PathTracer: ${this.bvhNodeCount} BVH nodes (storage buffer)`)}setMeshVisibilityData(e){if(!e||e.length===0)return;let n=e.length,r=new Float32Array(n*4);for(let t=0;t<n;t++)r[t*4]=this._isWorldVisible(e[t])?1:0;this.meshVisibilityStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.meshVisibilityStorageNode.value=this.meshVisibilityStorageAttr,this.meshVisibilityStorageNode.bufferCount=n}updateMeshVisibility(e,t){this.meshVisibilityStorageAttr&&(this.meshVisibilityStorageAttr.array[e*4]=t?1:0,this.meshVisibilityStorageAttr.needsUpdate=!0)}updateAllMeshVisibility(){if(!this._meshRefs||!this.meshVisibilityStorageAttr)return;let e=this.meshVisibilityStorageAttr.array;for(let t=0;t<this._meshRefs.length;t++)e[t*4]=this._isWorldVisible(this._meshRefs[t])?1:0;this.meshVisibilityStorageAttr.needsUpdate=!0}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){this._updateStorageBuffer(this.triangleStorageAttr,e)}updateBVHData(e){this._updateStorageBuffer(this.bvhStorageAttr,e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0){this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0){this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){console.error(`PathTracer: Triangle data required`);return}if(!this.bvhStorageNode){console.error(`PathTracer: BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.setupCompute({stage:this,storageTextures:this.storageTextures}),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}render(e,t){if(!this.isReady)return;if(this.isComplete||this.frameCount>=this.completionThreshold){this.isComplete||=!0;return}if(this.performanceMonitor?.start(),e&&this.shaderBuilder.adaptiveSamplingTexNode){let t=e.getTexture(`adaptiveSampling:output`);t&&(this.shaderBuilder.adaptiveSamplingTexNode.value=t)}let n=this.frameCount,r=this.renderMode.value,i=null,a=null;r===1&&n===0&&(i=this.maxBounces.value,a=this.samplesPerPixel.value,this.maxBounces.value=1,this.samplesPerPixel.value=1),this._handleResize(),this.manageASVGFForRenderMode(r,n);let o=this.tileManager.handleTileRendering(this.renderer,r,n,null);if(e&&e.setState(`tileRenderingComplete`,o.isCompleteCycle),o.tileIndex>=0){let e=this.tileManager.calculateTileBounds(o.tileIndex,this.tileManager.tiles,this.width,this.height);this.emit(`tile:changed`,{tileIndex:o.tileIndex,tileBounds:e,renderMode:r}),this.tileChanged=!0}this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this._updateAccumulationUniforms(n,r),this.frame.value=n,this.shaderBuilder.forceCompile(this.renderer),o.tileIndex>=0&&o.tileBounds?this.shaderBuilder.setTileDispatch(o.tileBounds.x,o.tileBounds.y,o.tileBounds.width,o.tileBounds.height):this.shaderBuilder.setFullScreenDispatch();let s=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=s.color,this.shaderBuilder.prevNormalDepthTexNode.value=s.normalDepth,this.shaderBuilder.prevAlbedoTexNode.value=s.albedo),this.renderer.compute(this.shaderBuilder.computeNode),this.storageTextures.copyToReadTargets(this.renderer);let c=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,c),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),a!==null&&(this.samplesPerPixel.value=a),this.performanceMonitor?.end()}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.shaderBuilder.setSize(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e,t){let n=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=n,this.accumulationEnabled?n?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=De(e,t,this.tileManager.totalTilesCache,!1),this.hasPreviousAccumulated.value=e>0?1:0):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value),e.setState(`tiles`,this.tileManager.tiles)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){let e=this.renderMode.value,t=this.maxSamples.value;this.renderLimitMode===`time`?this.completionThreshold=1/0:this.completionThreshold=Ee(e,t,this.tileManager.totalTilesCache)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e,t){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this._onRenderModeChanged(this.pendingRenderMode)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay)),e===1?this._handleTiledASVGF(t):this._handleFullQuadASVGF()}_onRenderModeChanged(e){e===1?this.emit(`asvgf:updateParameters`,{enableDebug:!1,temporalAlpha:.15}):this.emit(`asvgf:updateParameters`,{temporalAlpha:.1}),this.emit(`asvgf:reset`)}_handleTiledASVGF(e){let t=e===0,n=(t?-1:(e-1)%this.tileManager.totalTilesCache)==this.tileManager.totalTilesCache-1;t?this.emit(`asvgf:setTemporal`,{enabled:!0}):n?(this.emit(`asvgf:setTemporal`,{enabled:!0}),this.tileCompletionFrame=e):this.emit(`asvgf:setTemporal`,{enabled:!1})}_handleFullQuadASVGF(){this.emit(`asvgf:setTemporal`,{enabled:!0})}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(e){this.blueNoiseTexture=e,e&&(j.value=e)}setEmissiveTriangleData(e,n,r=0){if(!e)return;let i=e.length/4;this.emissiveTriangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.emissiveTriangleStorageNode.value=this.emissiveTriangleStorageAttr,this.emissiveTriangleStorageNode.bufferCount=i,this.emissiveTriangleCount.value=n,this.emissiveTotalPower.value=r,console.log(`PathTracer: ${n} emissive triangles, totalPower=${r.toFixed(4)} (storage buffer)`)}setLightBVHData(e,n){if(!e)return;let r=e.length/4;this.lightBVHStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.lightBVHStorageNode.value=this.lightBVHStorageAttr,this.lightBVHStorageNode.bufferCount=r,this.lightBVHNodeCount.value=n,console.log(`PathTracer: Light BVH ${n} nodes`)}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{console.log(`PathTracer: Starting material rebuild...`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),console.log(`PathTracer materials rebuilt successfully`)}catch(e){console.error(`Error rebuilding PathTracer materials:`,e);try{console.warn(`Attempting recovery by resetting path tracer...`),this.reset()}catch(e){console.error(`Recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.tileManager?.dispose(),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.storageTextures?.dispose(),this.blueNoiseTexture?.dispose(),this.placeholderTexture?.dispose(),this.triangleStorageAttr=null,this.triangleStorageNode=null,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}},Ka=class extends L{constructor(e,r={}){super(`NormalDepth`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.pathTracer=r.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,o.uniform)(new n.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,o.uniform)(new n.Matrix4,`mat4`),this.resolutionWidth=(0,o.uniform)(r.width||1),this.resolutionHeight=(0,o.uniform)(r.height||1);let i=r.width||1,a=r.height||1;this._outputStorageTex=new t.StorageTexture(i,a),this._outputStorageTex.type=n.HalfFloatType,this._outputStorageTex.format=n.RGBAFormat,this._outputStorageTex.minFilter=n.NearestFilter,this._outputStorageTex.magFilter=n.NearestFilter,this.renderTarget=new t.RenderTarget(i,a,{type:n.HalfFloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._computeNode=null,this._computeBuilt=!1}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;e.triangleStorageAttr&&!this._triStorageNode?this._triStorageNode=(0,o.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly():e.triangleStorageAttr&&this._triStorageNode&&(this._triStorageNode.value=e.triangleStorageAttr,this._triStorageNode.bufferCount=e.triangleStorageAttr.count),e.bvhStorageAttr&&!this._bvhStorageNode?this._bvhStorageNode=(0,o.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly():e.bvhStorageAttr&&this._bvhStorageNode&&(this._bvhStorageNode.value=e.bvhStorageAttr,this._bvhStorageNode.bufferCount=e.bvhStorageAttr.count);let t=e.materialData.materialStorageAttr;return t&&!this._matStorageNode?this._matStorageNode=(0,o.storage)(t,`vec4`,t.count).toReadOnly():t&&this._matStorageNode&&(this._matStorageNode.value=t,this._matStorageNode.bufferCount=t.count),!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,n=this._matStorageNode,r=this.cameraWorldMatrix,i=this.cameraProjectionMatrixInverse,a=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex;this._computeNode=(0,o.Fn)(([r,i])=>{let l=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),u=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(l.lessThan((0,o.int)(a)).and(u.lessThan((0,o.int)(s))),()=>{let d=(0,o.vec3)((0,o.float)(l).add(.5).div(a).mul(2).sub(1),(0,o.float)(u).add(.5).div(s).mul(2).sub(1).negate(),1),f=i.mul((0,o.vec4)(d,1)),p=(0,o.normalize)((0,o.mat3)(r[0].xyz,r[1].xyz,r[2].xyz).mul(f.xyz.div(f.w))),m=xt({origin:(0,o.vec3)(r[3]),direction:p}),h=wt.wrap(_n(m,t,e,n)),g=h.normal.mul(.5).add(.5),_=h.dst,v=h.didHit.select((0,o.vec4)(g,_),(0,o.vec4)(0,0,0,(0,o.float)(1e6)));(0,o.textureStore)(c,(0,o.uvec2)((0,o.uint)(l),(0,o.uint)(u)),v).toWriteOnly()})})(r,i).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._dirty&&this.renderTarget.texture){e.setTexture(`pathtracer:normalDepth`,this.renderTarget.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.renderTarget.width||e.height!==this.renderTarget.height)&&this.setSize(e.width,e.height)}this.renderer.compute(this._computeNode),this.renderer.copyTextureToTexture(this._outputStorageTex,this.renderTarget.texture),e.setTexture(`pathtracer:normalDepth`,this.renderTarget.texture),this._dirty=!1}reset(){this._dirty=!0}setSize(e,t){this._outputStorageTex.setSize(e,t),this.renderTarget.setSize(e,t),this.renderTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&this._computeNode.setCount([this._dispatchX,this._dispatchY,1]),this._dirty=!0}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this.renderTarget?.dispose()}},qa=class extends L{constructor(e,r,i={}){super(`MotionVector`,{...i,executionMode:I.ALWAYS}),this.renderer=e,this.camera=r,this.pathTracer=i.pathTracer||null;let a=i.width||1,s=i.height||1;this.prevViewProjectionMatrix=new n.Matrix4,this.currentViewProjectionMatrix=new n.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,o.uniform)(new n.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,o.uniform)(new n.Matrix4,`mat4`),this.prevVP=(0,o.uniform)(new n.Matrix4,`mat4`),this.isFirstFrameU=(0,o.uniform)(1),this.deltaTime=(0,o.uniform)(1/60),this.velocityScale=(0,o.uniform)(1),this.resolutionWidth=(0,o.uniform)(a),this.resolutionHeight=(0,o.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(a,s),this._screenSpaceStorageTex.type=n.HalfFloatType,this._screenSpaceStorageTex.format=n.RGBAFormat,this._screenSpaceStorageTex.minFilter=n.NearestFilter,this._screenSpaceStorageTex.magFilter=n.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(a,s),this._worldSpaceStorageTex.type=n.HalfFloatType,this._worldSpaceStorageTex.format=n.RGBAFormat,this._worldSpaceStorageTex.minFilter=n.NearestFilter,this._worldSpaceStorageTex.magFilter=n.NearestFilter;let c={type:n.HalfFloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(a,s,c),this.worldSpaceTarget=new t.RenderTarget(a,s,c),this._dispatchX=Math.ceil(a/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,n=this.cameraProjectionMatrixInverse,r=this.prevVP,i=this.resolutionWidth,a=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,o.Fn)(([t,n])=>{let c=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),l=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(c.lessThan((0,o.int)(i)).and(l.lessThan((0,o.int)(a))),()=>{let u=(0,o.textureLoad)(e,(0,o.ivec2)(c,l)).w,d=(0,o.vec2)((0,o.float)(c).add(.5).div(i),(0,o.float)(l).add(.5).div(a)),f=(0,o.vec4)(0,0,u,1).toVar();(0,o.If)(u.lessThan((0,o.float)(1e5)),()=>{let e=(0,o.vec3)((0,o.float)(c).add(.5).div(i).mul(2).sub(1),(0,o.float)(l).add(.5).div(a).mul(2).sub(1).negate(),1),s=n.mul((0,o.vec4)(e,1)),p=(0,o.normalize)((0,o.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,o.vec3)(t[3]).add(p.mul(u)),h=r.mul((0,o.vec4)(m,1)),g=h.xy.div(h.w),_=(0,o.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,o.vec4)(v,u,1),(0,o.vec4)((0,o.float)(1e3),(0,o.float)(1e3),u,0)))}),(0,o.textureStore)(s,(0,o.uvec2)((0,o.uint)(c),(0,o.uint)(l)),f).toWriteOnly()})})(t,n).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,n=this.cameraProjectionMatrixInverse,r=this.prevVP,i=this.isFirstFrameU,a=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,o.Fn)(([t,n])=>{let d=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),f=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(d.lessThan((0,o.int)(c)).and(f.lessThan((0,o.int)(l))),()=>{let p=(0,o.textureLoad)(e,(0,o.ivec2)(d,f)).w,m=(0,o.vec4)(0,0,0,0).toVar();(0,o.If)(i.lessThan(.5).and(p.lessThan((0,o.float)(1e5))),()=>{let e=(0,o.vec3)((0,o.float)(d).add(.5).div(c).mul(2).sub(1),(0,o.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),i=n.mul((0,o.vec4)(e,1)),u=(0,o.normalize)((0,o.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(i.xyz.div(i.w))),h=(0,o.vec3)(t[3]).add(u.mul(p)),g=(0,o.vec2)((0,o.float)(d).add(.5).div(c),(0,o.float)(f).add(.5).div(l)),_=r.mul((0,o.vec4)(h,1)),v=_.xy.div(_.w),y=(0,o.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,o.vec3)(x.x.div(a).mul(s),x.y.div(a).mul(s),0);m.assign(b.select((0,o.vec4)(S,1),(0,o.vec4)(0,0,0,.5)))}),(0,o.textureStore)(u,(0,o.uvec2)((0,o.uint)(d),(0,o.uint)(f)),m).toWriteOnly()})})(t,n).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?1:0,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.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture),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}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this._screenSpaceStorageTex.setSize(e,t),this._worldSpaceStorageTex.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.setCount([this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&this._worldSpaceComputeNode.setCount([this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose()}};function Ja(e,t,n={}){let r=n.textureIndex||0,i=t.isTexture===!0,a;i?(console.warn(`RenderTargetHelper: Direct Texture input is not supported. Pass a RenderTarget instead.`),a=null):a=t;let o={width:n.width||200,height:n.height||200,position:n.position||`bottom-right`,flipX:n.flipX===void 0?!1:n.flipX,flipY:n.flipY===void 0?!1:n.flipY,autoUpdate:n.autoUpdate||!1,theme:n.theme||`dark`,title:n.title||a?.name||`Render Target`},s=document.createElement(`div`);s.className=`render-target-helper`;let c={"bottom-right":{bottom:`48px`,right:`10px`},"bottom-left":{bottom:`10px`,left:`10px`},"top-right":{top:`10px`,right:`10px`},"top-left":{top:`10px`,left:`10px`}},l={light:{backgroundColor:`white`,border:`1px solid #ddd`,color:`#333`},dark:{backgroundColor:`#1e293b`,border:`1px solid #334155`,color:`#f8fafc`}};Object.assign(s.style,{display:`flex`,flexDirection:`column`,position:`fixed`,resize:`both`,overflow:`hidden`,padding:`8px`,borderRadius:`4px`,boxShadow:`0 5px 15px rgba(0,0,0,0.3)`,transition:`opacity 0.2s ease`,zIndex:`1000`,minWidth:`100px`,minHeight:`100px`,maxWidth:`500px`,maxHeight:`500px`,width:`${o.width}px`,height:`${o.height}px`,...c[o.position],...l[o.theme]});let u=document.createElement(`div`);u.style.display=`flex`,u.style.justifyContent=`space-between`,u.style.alignItems=`center`,u.style.marginBottom=`4px`,u.style.cursor=`move`,u.style.userSelect=`none`;let d=document.createElement(`span`);d.textContent=o.title,d.style.fontSize=`12px`,d.style.fontFamily=`monospace`,d.style.color=l[o.theme].color;let f=document.createElement(`div`),p=document.createElement(`button`);p.innerHTML=`×`,p.style.background=`none`,p.style.border=`none`,p.style.cursor=`pointer`,p.style.fontSize=`16px`,p.style.color=l[o.theme].color,p.style.padding=`0 4px`,p.title=`Close`,p.onclick=()=>{s.style.display=`none`,o.autoUpdate&&(cancelAnimationFrame(O),O=null)};let m=document.createElement(`button`);m.innerHTML=`⟳`,m.style.background=`none`,m.style.border=`none`,m.style.cursor=`pointer`,m.style.fontSize=`14px`,m.style.color=l[o.theme].color,m.style.padding=`0 4px`,m.title=`Refresh`,m.onclick=()=>{s.update()},f.appendChild(m),f.appendChild(p),u.appendChild(d),u.appendChild(f),s.appendChild(u);let h=document.createElement(`canvas`);h.style.width=`100%`,h.style.height=`calc(100% - 20px)`;let g=``;o.flipX&&(g+=`scaleX(-1) `),o.flipY&&(g+=`scaleY(-1) `),h.style.transform=g.trim(),s.appendChild(h);let _=a?a.width:1,v=a?a.height:1;h.width=_,h.height=v;let y=h.getContext(`2d`),b=new Uint8ClampedArray(4*_*v),x=!1,S=!1,C=0,w=0;u.addEventListener(`pointerdown`,e=>{S=!0,C=e.clientX-s.offsetLeft,w=e.clientY-s.offsetTop,document.body.style.userSelect=`none`}),window.addEventListener(`pointermove`,e=>{if(!S)return;let t=e.clientX-C,n=e.clientY-w,r=window.innerWidth-s.offsetWidth,i=window.innerHeight-s.offsetHeight;s.style.left=`${Math.max(0,Math.min(t,r))}px`,s.style.top=`${Math.max(0,Math.min(n,i))}px`,s.style.bottom=`auto`,s.style.right=`auto`}),window.addEventListener(`pointerup`,()=>{S=!1,document.body.style.userSelect=``});function T(){if(!a)return;let e=a.width,t=a.height;(_!==e||v!==t)&&(_=e,v=t,h.width=_,h.height=v,b=new Uint8ClampedArray(4*_*v)),d.textContent=`${o.title} (${_}×${v})`}function E(e){let t=(e&32768)>>15,n=(e&31744)>>10,r=e&1023;return n===0?(t?-1:1)*2**-14*(r/1024):n===31?r?NaN:t?-1/0:1/0:(t?-1:1)*2**(n-15)*(1+r/1024)}function D(e){let t=Math.min(e.length,b.length);if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)b.set(e.subarray(0,t));else if(e instanceof Uint16Array)for(let n=0;n<t;n++){let t=E(e[n]);b[n]=Math.min(255,Math.max(0,(t||0)*255))}else for(let n=0;n<t;n++)b[n]=Math.min(255,Math.max(0,e[n]*255));if(_===0||v===0)return;let n=new ImageData(b,_,v);y.putImageData(n,0,0)}s.update=function(){if(a){T();try{if(x)return;x=!0,e.readRenderTargetPixelsAsync(a,0,0,_,v,r).then(e=>{x=!1,D(e)}).catch(e=>{x=!1,console.error(`RenderTargetHelper: readback error:`,e)})}catch(e){console.error(`Error updating render target helper:`,e)}}},s.addEventListener(`mousedown`,()=>{window.addEventListener(`mousemove`,T)}),window.addEventListener(`mouseup`,()=>{window.removeEventListener(`mousemove`,T)}),window.addEventListener(`resize`,T);let O=null;return s.show=function(){s.style.display=`flex`,o.autoUpdate&&!O&&s.startAutoUpdate()},s.hide=function(){s.style.display=`none`,o.autoUpdate&&O&&(cancelAnimationFrame(O),O=null)},s.toggle=function(){return s.style.display===`none`?s.show():s.hide(),s.style.display!==`none`},s.startAutoUpdate=function(){if(O)return;let e=()=>{s.update(),O=requestAnimationFrame(e)};O=requestAnimationFrame(e)},s.stopAutoUpdate=function(){O&&=(cancelAnimationFrame(O),null)},s.dispose=function(){o.autoUpdate&&O&&cancelAnimationFrame(O),s.parentNode&&s.parentNode.removeChild(s),b=null},o.autoUpdate&&s.startAutoUpdate(),s.style.display===`none`&&(s.style.display=`flex`),s}var Ya=class extends L{constructor(e,r={}){super(`ASVGF`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.debugContainer=r.debugContainer||null,this.temporalAlpha=(0,o.uniform)(r.temporalAlpha??.1),this.gradientScale=(0,o.uniform)(r.gradientScale??2),this.gradientMin=(0,o.uniform)(r.gradientMin??.01),this.gradientMax=(0,o.uniform)(r.gradientMax??.5),this.phiColor=(0,o.uniform)(r.phiColor??10),this.phiNormal=(0,o.uniform)(r.phiNormal??128),this.phiDepth=(0,o.uniform)(r.phiDepth??1),this.maxAccumFrames=(0,o.uniform)(r.maxAccumFrames??32),this.varianceClip=(0,o.uniform)(r.varianceClip??1),this.resW=(0,o.uniform)(r.width||1),this.resH=(0,o.uniform)(r.height||1),this.temporalEnabled=!0,this.temporalEnabledU=(0,o.uniform)(1),this._colorTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._readPrevNDTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let i=r.width||1,a=r.height||1;this._temporalTexA=new t.StorageTexture(i,a),this._temporalTexA.type=n.HalfFloatType,this._temporalTexA.format=n.RGBAFormat,this._temporalTexA.minFilter=n.LinearFilter,this._temporalTexA.magFilter=n.LinearFilter,this._temporalTexB=new t.StorageTexture(i,a),this._temporalTexB.type=n.HalfFloatType,this._temporalTexB.format=n.RGBAFormat,this._temporalTexB.minFilter=n.LinearFilter,this._temporalTexB.magFilter=n.LinearFilter,this._prevNDTexA=new t.StorageTexture(i,a),this._prevNDTexA.type=n.HalfFloatType,this._prevNDTexA.format=n.RGBAFormat,this._prevNDTexA.minFilter=n.LinearFilter,this._prevNDTexA.magFilter=n.LinearFilter,this._prevNDTexB=new t.StorageTexture(i,a),this._prevNDTexB.type=n.HalfFloatType,this._prevNDTexB.format=n.RGBAFormat,this._prevNDTexB.minFilter=n.LinearFilter,this._prevNDTexB.magFilter=n.LinearFilter,this._gradientStorageTex=new t.StorageTexture(i,a),this._gradientStorageTex.type=n.HalfFloatType,this._gradientStorageTex.format=n.RGBAFormat,this._gradientStorageTex.minFilter=n.LinearFilter,this._gradientStorageTex.magFilter=n.LinearFilter,this.currentMoments=0,this._compiled=!1,this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,o.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(i,a),this._heatmapStorageTex.type=n.FloatType,this._heatmapStorageTex.format=n.RGBAFormat,this._heatmapStorageTex.minFilter=n.NearestFilter,this._heatmapStorageTex.magFilter=n.NearestFilter,this.heatmapTarget=new t.RenderTarget(i,a,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.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(),this.heatmapHelper=Ja(this.renderer,this.heatmapTarget,{width:400,height:400,position:`bottom-right`,theme:`dark`,title:`ASVGF Debug`,autoUpdate:!1}),this.heatmapHelper.hide(),(this.debugContainer||document.body).appendChild(this.heatmapHelper),this.frameCount=0}_buildGradientCompute(){let e=this._colorTexNode,t=this._motionTexNode,n=this._readTemporalTexNode,r=this._gradientStorageTex,i=this.resW,a=this.resH,s=(0,o.workgroupArray)(`float`,100);this._gradientNode=(0,o.Fn)(()=>{let c=o.localId.x,l=o.localId.y,u=l.mul(8).add(c),d=(0,o.int)(o.workgroupId.x).mul(8).sub(1),f=(0,o.int)(o.workgroupId.y).mul(8).sub(1),p=u.mod(10),m=u.div(10),h=(0,o.textureLoad)(e,(0,o.ivec2)(d.add((0,o.int)(p)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),f.add((0,o.int)(m)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz;s.element(u).assign(Kt(h)),(0,o.If)(u.lessThan((0,o.uint)(36)),()=>{let t=u.add((0,o.uint)(64)),n=t.mod(10),r=t.div(10),c=(0,o.textureLoad)(e,(0,o.ivec2)(d.add((0,o.int)(n)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),f.add((0,o.int)(r)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz;s.element(t).assign(Kt(c))}),(0,o.workgroupBarrier)();let g=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(c)),_=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(l));(0,o.If)(g.lessThan((0,o.int)(i)).and(_.lessThan((0,o.int)(a))),()=>{let e=(0,o.float)(-1).toVar(),u=(0,o.int)(0).toVar(),d=(0,o.int)(0).toVar();for(let t=-1;t<=1;t++)for(let n=-1;n<=1;n++){let r=s.element(l.add(1+t).mul(10).add(c.add(1+n)));(0,o.If)(r.greaterThan(e),()=>{e.assign(r),u.assign((0,o.int)(n)),d.assign((0,o.int)(t))})}let f=g.add(u).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),p=_.add(d).clamp((0,o.int)(0),(0,o.int)(a).sub(1)),m=(0,o.textureLoad)(t,(0,o.ivec2)(f,p)),h=(0,o.float)(f).sub(m.x.mul(i)),v=(0,o.float)(p).sub(m.y.mul(a)),y=(0,o.textureLoad)(n,(0,o.ivec2)((0,o.int)(h).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),(0,o.int)(v).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz,b=Kt(y),x=(0,o.abs)(e.sub(b)).div((0,o.max)(e,(0,o.float)(.001))).clamp(0,1);(0,o.textureStore)(r,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),(0,o.vec4)(x,e,b,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA,this._prevNDTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB,this._prevNDTexB)}_buildTemporalForDirection(e,t){let n=this._colorTexNode,r=this._normalDepthTexNode,i=this._motionTexNode,a=this._readTemporalTexNode,s=this._readPrevNDTexNode;this._gradientReadTexNode;let c=this.temporalAlpha;this.gradientScale,this.gradientMin,this.gradientMax;let l=this.phiNormal,u=this.phiDepth,d=this.maxAccumFrames,f=this.varianceClip,p=this.temporalEnabledU,m=this.resW,h=this.resH;return(0,o.Fn)(()=>{let g=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),_=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(g.lessThan((0,o.int)(m)).and(_.lessThan((0,o.int)(h))),()=>{let v=(0,o.ivec2)(g,_),y=(0,o.textureLoad)(n,v).xyz,b=(0,o.textureLoad)(r,v),x=(0,o.vec4)(y,1).toVar();(0,o.If)(p.greaterThan(.5),()=>{let e=(0,o.textureLoad)(i,v),t=e.w.greaterThan(.5),r=(0,o.float)(g).sub(e.x.mul(m)),p=(0,o.float)(_).sub(e.y.mul(h)),S=r.greaterThanEqual(0).and(r.lessThan((0,o.float)(m))).and(p.greaterThanEqual(0)).and(p.lessThan((0,o.float)(h)));(0,o.If)(t.and(S),()=>{let e=(0,o.ivec2)((0,o.int)(r).clamp((0,o.int)(0),(0,o.int)(m).sub(1)),(0,o.int)(p).clamp((0,o.int)(0),(0,o.int)(h).sub(1))),t=b.xyz.mul(2).sub(1),i=(0,o.textureLoad)(s,e);an(t,i.xyz.mul(2).sub(1),b.w,i.w,l,u);let v=(0,o.textureLoad)(a,e),S=v.xyz,C=v.w,w=C.div(d).clamp(0,1),T=(0,o.vec3)(1e10).toVar(),E=(0,o.vec3)(-1e10).toVar(),D=(0,o.vec3)(0).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){let r=(0,o.textureLoad)(n,(0,o.ivec2)(g.add(t).clamp((0,o.int)(0),(0,o.int)(m).sub(1)),_.add(e).clamp((0,o.int)(0),(0,o.int)(h).sub(1)))).xyz;T.assign((0,o.min)(T,r)),E.assign((0,o.max)(E,r)),D.addAssign(r)}D.divAssign(9);let O=(0,o.float)(1).add(w.mul(3)),k=E.sub(T).mul(f).mul(O),A=T.sub(k),j=E.add(k),M=(0,o.mix)(S.clamp(A,j),y,(0,o.max)((0,o.float)(1).div(C.add(1)),c)),N=(0,o.min)(C.add(1),d);x.assign((0,o.vec4)(M,N))}).Else(()=>{x.assign((0,o.vec4)(y,1))})}),(0,o.textureStore)(e,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),x).toWriteOnly(),(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),b).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,n=this._heatmapTemporalTexNode,r=this._heatmapNDTexNode,i=this._heatmapMotionTexNode,a=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,o.Fn)(()=>{let d=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),f=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(d.lessThan((0,o.int)(l)).and(f.lessThan((0,o.int)(u))),()=>{let p=(0,o.ivec2)(d,f),m=(0,o.vec4)(0,0,0,1).toVar();(0,o.If)(c.equal((0,o.int)(0)),()=>{let e=(0,o.textureLoad)(t,p).xyz;m.assign((0,o.vec4)(e,1))}).ElseIf(c.equal((0,o.int)(1)),()=>{let t=(0,o.float)(0).toVar(),n=(0,o.float)(0).toVar();for(let r=-1;r<=1;r++)for(let i=-1;i<=1;i++){let a=(0,o.textureLoad)(e,(0,o.ivec2)(d.add(i).clamp((0,o.int)(0),(0,o.int)(l).sub(1)),f.add(r).clamp((0,o.int)(0),(0,o.int)(u).sub(1)))).xyz,s=(0,o.dot)(a,(0,o.vec3)(.2126,.7152,.0722));t.addAssign(s),n.addAssign(s.mul(s))}t.divAssign(9),n.divAssign(9);let r=(0,o.max)(n.sub(t.mul(t)),(0,o.float)(0)).div((0,o.max)(t.mul(t),(0,o.float)(1e-4))).mul(10).clamp(0,1),i=r.sub(.5).mul(4).clamp(0,1),a=r.mul(4).clamp(0,1).sub(r.sub(.75).mul(4).clamp(0,1)),s=(0,o.float)(1).sub(r.sub(.25).mul(4).clamp(0,1));m.assign((0,o.vec4)(i,a,s,1))}).ElseIf(c.equal((0,o.int)(2)),()=>{let e=(0,o.textureLoad)(n,p).w.div(32).clamp(0,1);m.assign((0,o.vec4)((0,o.float)(1).sub(e),e,(0,o.float)(.2),1))}).ElseIf(c.equal((0,o.int)(3)),()=>{let e=(0,o.textureLoad)(i,p),t=(0,o.abs)(e.x).mul(100).clamp(0,1),n=(0,o.abs)(e.y).mul(100).clamp(0,1),r=t.add(n).clamp(0,1);m.assign((0,o.vec4)(t,n,r.mul(.3),1))}).ElseIf(c.equal((0,o.int)(4)),()=>{let e=(0,o.textureLoad)(r,p);m.assign((0,o.vec4)(e.xyz,1))}).Else(()=>{let e=(0,o.textureLoad)(a,p).x.mul(5).clamp(0,1);m.assign((0,o.vec4)(e,e.mul(.5),(0,o.float)(1).sub(e),1))}),(0,o.textureStore)(s,(0,o.uvec2)((0,o.uint)(d),(0,o.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:setTemporal`,e=>{e&&e.enabled!==void 0&&(this.temporalEnabled=e.enabled,this.temporalEnabledU.value=e.enabled?1:0)}),this.on(`asvgf:updateParameters`,e=>{e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientScale!==void 0&&(this.gradientScale.value=e.gradientScale),e.phiColor!==void 0&&(this.phiColor.value=e.phiColor),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth))})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:normalDepth`),r=e.getTexture(`motionVector:screenSpace`);if(!t)return;let i=t.image;i&&i.width>0&&i.height>0&&(i.width!==this._temporalTexA.image.width||i.height!==this._temporalTexA.image.height)&&this.setSize(i.width,i.height),this._colorTexNode.value=t,n&&(this._normalDepthTexNode.value=n),r&&(this._motionTexNode.value=r),this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0);let a=this.currentMoments===0?this._temporalTexB:this._temporalTexA,o=this.currentMoments===0?this._prevNDTexB:this._prevNDTexA,s=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,c=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._readTemporalTexNode.value=a,this.renderer.compute(this._gradientNode),this._gradientReadTexNode.value=this._gradientStorageTex,this._readPrevNDTexNode.value=o,this.renderer.compute(s),e.setTexture(`asvgf:output`,c),e.setTexture(`asvgf:temporalColor`,c),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=c,this._heatmapTemporalTexNode.value=c,n&&(this._heatmapNDTexNode.value=n),r&&(this._heatmapMotionTexNode.value=r),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture),this.heatmapHelper.update()),this.frameCount++}toggleHeatmap(e){this.showHeatmap=e,e?this.heatmapHelper.show():this.heatmapHelper.hide()}setTemporalEnabled(e){this.temporalEnabled=e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientScale!==void 0&&(this.gradientScale.value=e.gradientScale),e.phiColor!==void 0&&(this.phiColor.value=e.phiColor),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.frameCount=0,this.currentMoments=0}setSize(e,t){this._temporalTexA.setSize(e,t),this._temporalTexB.setSize(e,t),this._prevNDTexA.setSize(e,t),this._prevNDTexB.setSize(e,t),this._gradientStorageTex.setSize(e,t),this._heatmapStorageTex.setSize(e,t),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.setCount([this._dispatchX,this._dispatchY,1]),this._temporalNodeA.setCount([this._dispatchX,this._dispatchY,1]),this._temporalNodeB.setCount([this._dispatchX,this._dispatchY,1]),this._heatmapComputeNode.setCount([this._dispatchX,this._dispatchY,1])}reset(){}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._prevNDTexA?.dispose(),this._prevNDTexB?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this.heatmapHelper?.dispose()}},Xa=(0,o.wgslFn)(`
|
|
531
|
+
`),aa=(0,o.Fn)(([e,t,n,r,i])=>{let a=(0,o.texture)(n,e.div(t),0),s=(0,o.int)(0).toVar();return(0,o.If)(a.b.greaterThan(.5),()=>{s.assign(0)}).Else(()=>{let e=(0,o.int)((0,o.floor)(a.r.mul((0,o.float)(i)).add(.5)));s.assign((0,o.clamp)(e,r,i))}),s}),oa=e=>{let{pixelCoord:t,writeColorTex:n,writeNDTex:r,writeAlbedoTex:i,resolution:a,frame:s,samplesPerPixel:c,visMode:l,cameraWorldMatrix:u,cameraProjectionMatrixInverse:d,cameraViewMatrix:f,cameraProjectionMatrix:p,bvhBuffer:m,triangleBuffer:h,materialBuffer:g,albedoMaps:_,normalMaps:v,bumpMaps:y,metalnessMaps:b,roughnessMaps:x,emissiveMaps:S,displacementMaps:C,directionalLightsBuffer:w,numDirectionalLights:T,areaLightsBuffer:E,numAreaLights:D,pointLightsBuffer:O,numPointLights:k,spotLightsBuffer:A,numSpotLights:j,envTexture:M,environmentIntensity:N,envMatrix:ee,envMarginalWeights:te,envConditionalWeights:ne,envTotalSum:re,envResolution:F,enableEnvironmentLight:ie,useEnvMapIS:ae,maxBounceCount:oe,transmissiveBounces:se,showBackground:ce,transparentBackground:le,backgroundIntensity:ue,fireflyThreshold:de,globalIlluminationIntensity:fe,totalTriangleCount:pe,enableEmissiveTriangleSampling:I,emissiveTriangleBuffer:L,emissiveTriangleCount:ge,emissiveTotalPower:_e,emissiveBoost:R,lightBVHBuffer:ve,lightBVHNodeCount:ye,debugVisScale:be,enableAccumulation:z,hasPreviousAccumulated:xe,prevAccumTexture:Se,prevNormalDepthTexture:Ce,prevAlbedoTexture:we,accumulationAlpha:Te,cameraIsMoving:B,useAdaptiveSampling:Ee,adaptiveSamplingTexture:De,adaptiveSamplingMin:Oe,adaptiveSamplingMax:ke,enableDOF:Ae,focalLength:V,aperture:je,focusDistance:Me,sceneScale:Ne,apertureScale:Pe,anamorphicRatio:Fe}=e,Ie=(0,o.uvec2)((0,o.uint)((0,o.int)(t.x)),(0,o.uint)((0,o.int)(t.y))),H=t.div(a),U=t.div(a).mul(2).sub(1).toVar();U.y.assign(U.y.negate());let W=(0,o.vec4)(0).toVar(),Le=(0,o.int)(0).toVar(),Re=he({pixelCoord:t,rayIndex:(0,o.int)(0),frame:s}).toVar(),ze=(0,o.int)(t.y).mul((0,o.int)(a.x)).add((0,o.int)(t.x)).toVar(),G=(0,o.vec3)(0,0,1).toVar(),Be=(0,o.float)(1).toVar(),Ve=(0,o.float)(0).toVar(),He=(0,o.int)(c).toVar();(0,o.If)(s.greaterThan((0,o.uint)(2)).and(Ee),()=>{let e=aa(t,a,De,Oe,ke);He.assign(e),(0,o.If)(He.equal((0,o.int)(0)),()=>{(0,o.If)(z.and(xe),()=>{let e=(0,o.texture)(Se,H,0);W.assign(e),Ve.assign(e.w);let t=(0,o.texture)(Ce,H,0);G.assign(t.xyz.mul(2).sub(1)),Be.assign(t.w)}).Else(()=>{He.assign(1)})})});let Ue=(0,o.vec3)(0).toVar(),We=(0,o.vec3)(0).toVar(),Ge=(0,o.float)(-1e3).toVar(),Ke=(0,o.vec2)(2).div(a).toVar();(0,o.Loop)({start:(0,o.int)(0),end:He,type:`int`,condition:`<`},({i:e})=>{let n=P({state:Re.add((0,o.uint)(e))}).toVar(),r=me(t,e,He,n,a,s).toVar();(0,o.If)(l.equal((0,o.int)(9)),()=>{W.assign((0,o.vec4)(r,1,1)),Le.assign(1),(0,o.Break)()});let i=r.sub(.5).mul(Ke),c=U.add(i),he=St.wrap(bn(c,n,u,d,Ae,V,je,Me,Ne,Pe,Fe)),z=(0,o.vec4)(0).toVar();(0,o.If)(l.greaterThan((0,o.int)(0)),()=>{z.assign(ra(he.origin,he.direction,m,h,g,M,ee,N,ie,l,be,t,a,_,v,y,b,x,S,p,f,s))}).Else(()=>{let r=Ki.wrap($i(he,n,e,ze,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee,te,ne,re,F,ie,ae,oe,se,ue,ce,le,de,fe,pe,I,L,ge,_e,R,ve,ye,t,a,s));z.assign(r.radiance),(0,o.If)(e.equal((0,o.int)(0)),()=>{Ue.assign(r.objectNormal),We.assign(r.objectColor),Ge.assign(r.objectID),(0,o.If)(r.firstHitDistance.lessThan(1e9),()=>{G.assign((0,o.normalize)(r.objectNormal)),Be.assign(ia({worldPos:r.firstHitPoint,cameraProjectionMatrix:p,cameraViewMatrix:f}))})})}),W.addAssign(z),Ve.addAssign(z.w),Le.addAssign(1)}),(0,o.If)(Le.greaterThan((0,o.int)(0)),()=>{W.divAssign((0,o.float)(Le)),Ve.divAssign((0,o.float)(Le))});let qe=W.xyz.toVar(),Je=(0,o.vec4)(G.mul(.5).add(.5),Be).toVar(),Ye=(0,o.vec3)(We).toVar(),Xe=(0,o.select)(le,Ve,(0,o.float)(1)).toVar();(0,o.If)(z.and(B.not()).and(s.greaterThan((0,o.uint)(0))).and(xe),()=>{let e=(0,o.texture)(Se,H,0).toVar();qe.assign((0,o.mix)(e.xyz,W.xyz,Te)),Je.assign((0,o.mix)((0,o.texture)(Ce,H,0),Je,Te)),Ye.assign((0,o.mix)((0,o.texture)(we,H,0).xyz,Ye,Te)),(0,o.If)(le,()=>{Xe.assign((0,o.mix)(e.w,Ve,Te))})}),(0,o.textureStore)(n,Ie,(0,o.vec4)(qe.xyz,Xe)).toWriteOnly(),(0,o.textureStore)(r,Ie,Je).toWriteOnly(),(0,o.textureStore)(i,Ie,(0,o.vec4)(Ye,1)).toWriteOnly()},sa=class{constructor(e=`Build`){this.label=e,this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(){let e=performance.now()-this.totalStart,t=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean);return console.log(`[${this.label}] ${Math.round(e)}ms`+(t.length?` | ${t.join(` · `)}`:``)),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(e)}}},ca=8,la=class{constructor(){this.computeNode=null,this.prevColorTexNode=null,this.prevNormalDepthTexNode=null,this.prevAlbedoTexNode=null,this.adaptiveSamplingTexNode=null,this.tileOffsetX=(0,o.uniform)(0,`int`),this.tileOffsetY=(0,o.uniform)(0,`int`),this.renderWidth=(0,o.uniform)(1920,`int`),this.renderHeight=(0,o.uniform)(1080,`int`),this._dispatchX=0,this._dispatchY=0,this._sceneTextureNodes=null}setupCompute(e){let{stage:t,storageTextures:n}=e,r=new sa(`setupCompute`);r.start(`Create texture nodes`);let i=this._createTextureNodes(t,n);r.end(`Create texture nodes`),r.start(`Build compute node (TSL)`);let a=n.renderWidth,o=n.renderHeight;this._dispatchX=Math.ceil(a/ca),this._dispatchY=Math.ceil(o/ca),this.renderWidth.value=a,this.renderHeight.value=o;let s=n.getWriteTextures();this.computeNode=this._buildComputeNode(t,i,s.color,s.normalDepth,s.albedo),r.end(`Build compute node (TSL)`),r.print()}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment,r=e.materialData;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),r.albedoMaps&&t.albedoMapsTex&&(t.albedoMapsTex.value=r.albedoMaps),r.normalMaps&&t.normalMapsTex&&(t.normalMapsTex.value=r.normalMaps),r.bumpMaps&&t.bumpMapsTex&&(t.bumpMapsTex.value=r.bumpMaps),r.metalnessMaps&&t.metalnessMapsTex&&(t.metalnessMapsTex.value=r.metalnessMaps),r.roughnessMaps&&t.roughnessMapsTex&&(t.roughnessMapsTex.value=r.roughnessMaps),r.emissiveMaps&&t.emissiveMapsTex&&(t.emissiveMapsTex.value=r.emissiveMaps),r.displacementMaps&&t.displacementMapsTex&&(t.displacementMapsTex.value=r.displacementMaps),console.log(`ShaderBuilder: Scene textures updated in-place`)}getSceneTextureNodes(){return this._sceneTextureNodes}setSize(e,t){this._dispatchX=Math.ceil(e/ca),this._dispatchY=Math.ceil(t/ca),this.computeNode&&this.computeNode.setCount([this._dispatchX,this._dispatchY,1]),this.renderWidth.value=e,this.renderHeight.value=t,this.tileOffsetX.value=0,this.tileOffsetY.value=0}setTileDispatch(e,t,n,r){this.tileOffsetX.value=e,this.tileOffsetY.value=t;let i=Math.ceil(n/ca),a=Math.ceil(r/ca);this.computeNode&&this.computeNode.setCount([i,a,1])}setFullScreenDispatch(){this.tileOffsetX.value=0,this.tileOffsetY.value=0,this.computeNode&&this.computeNode.setCount([this._dispatchX,this._dispatchY,1])}forceCompile(){}_createTextureNodes(e,r){let i=e.triangleStorageNode,a=e.bvhStorageNode,s=e.materialData.materialStorageNode,c=e.emissiveTriangleStorageNode,l=e.lightBVHStorageNode;pn(e.meshVisibilityStorageNode),Xr(e.uniforms.get(`enableAlphaShadows`));let u=(0,o.texture)(e.environment.environmentTexture),d=new t.TextureNode;this.adaptiveSamplingTexNode=d;let f=e.environment.envMarginalStorageNode,p=e.environment.envConditionalStorageNode,m=r.getReadTextures();this.prevColorTexNode=(0,o.texture)(m.color),this.prevNormalDepthTexNode=(0,o.texture)(m.normalDepth),this.prevAlbedoTexNode=(0,o.texture)(m.albedo);let h=()=>{let e=new n.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=n.LinearFilter,e.magFilter=n.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,o.texture)(e)},g=e.materialData,_=g.albedoMaps?(0,o.texture)(g.albedoMaps):h(),v=g.normalMaps?(0,o.texture)(g.normalMaps):h(),y=g.bumpMaps?(0,o.texture)(g.bumpMaps):h(),b=g.metalnessMaps?(0,o.texture)(g.metalnessMaps):h(),x=g.roughnessMaps?(0,o.texture)(g.roughnessMaps):h(),S=g.emissiveMaps?(0,o.texture)(g.emissiveMaps):h(),C=g.displacementMaps?(0,o.texture)(g.displacementMaps):h();Yr(_);let w={triStorage:i,bvhStorage:a,matStorage:s,emissiveTriStorage:c,lightBVHStorage:l,envTex:u,adaptiveSamplingTex:d,marginalCDFStorage:f,conditionalCDFStorage:p,albedoMapsTex:_,normalMapsTex:v,bumpMapsTex:y,metalnessMapsTex:b,roughnessMapsTex:x,emissiveMapsTex:S,displacementMapsTex:C};return this._sceneTextureNodes=w,w}_buildComputeNode(e,t,n,r,i){let{triStorage:a,bvhStorage:s,matStorage:c,emissiveTriStorage:l,lightBVHStorage:u,envTex:d,adaptiveSamplingTex:f,marginalCDFStorage:p,conditionalCDFStorage:m,albedoMapsTex:h,normalMapsTex:g,bumpMapsTex:_,metalnessMapsTex:v,roughnessMapsTex:y,emissiveMapsTex:b,displacementMapsTex:x}=t,S=this.tileOffsetX,C=this.tileOffsetY,w=this.renderWidth,T=this.renderHeight,E=this.prevColorTexNode,D=this.prevNormalDepthTexNode,O=this.prevAlbedoTexNode;return(0,o.Fn)(()=>{let t=S.add((0,o.int)(o.workgroupId.x).mul(ca)).add((0,o.int)(o.localId.x)),k=C.add((0,o.int)(o.workgroupId.y).mul(ca)).add((0,o.int)(o.localId.y));(0,o.If)(t.lessThan(w).and(k.lessThan(T)),()=>{oa({pixelCoord:(0,o.vec2)((0,o.float)(t).add(.5),(0,o.float)(k).add(.5)),writeColorTex:n,writeNDTex:r,writeAlbedoTex:i,prevAccumTexture:E,prevNormalDepthTexture:D,prevAlbedoTexture:O,resolution:e.resolution,frame:e.frame,samplesPerPixel:e.samplesPerPixel,visMode:e.visMode,cameraWorldMatrix:e.cameraWorldMatrix,cameraProjectionMatrixInverse:e.cameraProjectionMatrixInverse,cameraViewMatrix:e.cameraViewMatrix,cameraProjectionMatrix:e.cameraProjectionMatrix,bvhBuffer:s,triangleBuffer:a,materialBuffer:c,albedoMaps:h,normalMaps:g,bumpMaps:_,metalnessMaps:v,roughnessMaps:y,emissiveMaps:b,displacementMaps:x,directionalLightsBuffer:e.directionalLightsBufferNode,numDirectionalLights:e.numDirectionalLights,areaLightsBuffer:e.areaLightsBufferNode,numAreaLights:e.numAreaLights,pointLightsBuffer:e.pointLightsBufferNode,numPointLights:e.numPointLights,spotLightsBuffer:e.spotLightsBufferNode,numSpotLights:e.numSpotLights,envTexture:d,environmentIntensity:e.environmentIntensity,envMatrix:e.environmentMatrix,envMarginalWeights:p,envConditionalWeights:m,envTotalSum:e.envTotalSum,envResolution:e.envResolution,enableEnvironmentLight:e.enableEnvironment,useEnvMapIS:e.useEnvMapIS,maxBounceCount:e.maxBounces,transmissiveBounces:e.transmissiveBounces,showBackground:e.showBackground,transparentBackground:e.transparentBackground,backgroundIntensity:e.backgroundIntensity,fireflyThreshold:e.fireflyThreshold,globalIlluminationIntensity:e.globalIlluminationIntensity,totalTriangleCount:e.totalTriangleCount,enableEmissiveTriangleSampling:e.enableEmissiveTriangleSampling,emissiveTriangleBuffer:l,emissiveTriangleCount:e.emissiveTriangleCount,emissiveTotalPower:e.emissiveTotalPower,emissiveBoost:e.emissiveBoost,lightBVHBuffer:u,lightBVHNodeCount:e.lightBVHNodeCount,debugVisScale:e.debugVisScale,enableAccumulation:e.enableAccumulation,hasPreviousAccumulated:e.hasPreviousAccumulated,accumulationAlpha:e.accumulationAlpha,cameraIsMoving:e.cameraIsMoving,useAdaptiveSampling:e.useAdaptiveSampling,adaptiveSamplingTexture:f,adaptiveSamplingMin:e.adaptiveSamplingMin,adaptiveSamplingMax:e.adaptiveSamplingMax,enableDOF:e.enableDOF,focalLength:e.focalLength,aperture:e.aperture,focusDistance:e.focusDistance,sceneScale:e.sceneScale,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio})})})().compute([this._dispatchX,this._dispatchY,1],[ca,ca,1])}dispose(){this.computeNode?.dispose(),this.computeNode=null,this.prevColorTexNode=null,this.prevNormalDepthTexNode=null,this.prevAlbedoTexNode=null,this.adaptiveSamplingTexNode=null,this._sceneTextureNodes=null}},ua=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new da;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new da;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}setMaxTreelets(){}getStatistics(){return{...this.stats}}},da=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},fa=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}},pa={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},ma=pa.FLOATS_PER_TRIANGLE,ha=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},ga=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!0,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.maxTreeletDepth=3,this.maxTreeletsPerScene=20,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement))}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=this.triangles,n=pa.POSITION_A_OFFSET,r=pa.POSITION_B_OFFSET,i=pa.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*ma,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(ma*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&typeof Worker<`u`?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;console.log(`[BVHBuilder] SharedArrayBuffer: ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*ma*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BarjE67Z.js`).href:new URL(`assets/BVHWorker-BarjE67Z.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}))}catch(i){i.name===`SecurityError`?Ge(new URL(`data:text/javascript;base64,aW1wb3J0IHsgQlZIQnVpbGRlciB9IGZyb20gJy4uL0JWSEJ1aWxkZXIuanMnOwoKY29uc3QgRlBUID0gMzI7IC8vIEZMT0FUU19QRVJfVFJJQU5HTEUKCi8vIC0tLSBNZXNzYWdlIGRpc3BhdGNoZXIgLS0tCgpzZWxmLm9ubWVzc2FnZSA9IGZ1bmN0aW9uICggZSApIHsKCgljb25zdCBkYXRhID0gZS5kYXRhOwoJY29uc3QgdHlwZSA9IGRhdGEudHlwZTsKCglpZiAoIHR5cGUgPT09ICdidWlsZFBoYXNlMScgKSB7CgoJCWhhbmRsZVBoYXNlMSggZGF0YSApOwoKCX0gZWxzZSBpZiAoIHR5cGUgPT09ICdhc3NlbWJsZScgKSB7CgoJCWhhbm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EsCgkJCQlvcmlnaW5hbFRvQnZoLAoJCQkJdHJpYW5nbGVDb3VudDogaW5wdXRUcmlhbmdsZXMubGVuZ3RoIC8gMzIsCgkJCQl0cmVlbGV0U3RhdHM6IGJ1aWxkZXIuc3BsaXRTdGF0cwoJCQl9LCB0cmFuc2ZlcmFibGVzICk7CgoJCX0gZWxzZSB7CgoJCQljb25zdCByZW9yZGVyZWRGbG9hdDMyQXJyYXkgPSBidWlsZGVyLnJlb3JkZXJlZFRyaWFuZ2xlRGF0YTsKCQkJY29uc3QgdHJpYW5nbGVDb3VudCA9IHJlb3JkZXJlZEZsb2F0MzJBcnJheS5ieXRlTGVuZ3RoIC8gKCAzMiAqIDQgKTsKCgkJCWNvbnN0IHRyYW5zZmVyYWJsZXMgPSBbIGJ2aERhdGEuYnVmZmVyLCByZW9yZGVyZWRGbG9hdDMyQXJyYXkuYnVmZmVyIF07CgkJCWlmICggb3JpZ2luYWxUb0J2aCApIHRyYW5zZmVyYWJsZXMucHVzaCggb3JpZ2luYWxUb0J2aC5idWZmZXIgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCWJ2aERhdGEsCgkJCQl0cmlhbmdsZXM6IHJlb3JkZXJlZEZsb2F0MzJBcnJheSwKCQkJCW9yaWdpbmFsVG9CdmgsCgkJCQl0cmlhbmdsZUNvdW50LAoJCQkJdHJlZWxldFN0YXRzOiBidWlsZGVyLnNwbGl0U3RhdHMKCQkJfSwgdHJhbnNmZXJhYmxlcyApOwoKCQl9CgoJfSBjYXRjaCAoIGVycm9yICkgewoKCQljb25zb2xlLmVycm9yKCAnW0JWSFdvcmtlcl0gRXJyb3I6JywgZXJyb3IgKTsKCQlzZWxmLnBvc3RNZXNzYWdlKCB7IGVycm9yOiBlcnJvci5tZXNzYWdlIH0gKTsKCgl9Cgp9Cg==`,``+{}.url)).then(a).catch(()=>{console.warn(`Worker fetch fallback failed, using synchronous build`),r(this._buildSyncAndFlatten(e,t,n))}):(console.warn(`Worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n)))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(ma*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold,t=e?3:this.treeletSize,r=e?10:this.maxTreeletsPerScene,i=new ua(this.traversalCost,this.intersectionCost);i.setTreeletSize(t),i.setMinImprovement(this.treeletMinImprovement),i.setMaxTreelets(r);let a=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{i.optimizeBVH(c,t)}catch(t){console.error(`TreeletOptimizer: Error in pass ${e+1}:`,t);break}let r=i.getStatistics(),o=performance.now()-a;if(r.treeletsImproved===0&&e>0||o>15e3)break}let o=performance.now()-a;this.splitStats.treeletOptimizationTime=o;let s=i.getStatistics();this.splitStats.treeletsProcessed=s.treeletsProcessed,this.splitStats.treeletsImproved=s.treeletsImproved,this.splitStats.averageSAHImprovement=s.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new fa(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){console.error(`ReinsertionOptimizer: Error:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new Float32Array(a*ma);for(let e=0;e<a;e++){let t=this.indices[e]*ma,n=e*ma;f.set(d.subarray(t,t+ma),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return console.log(`[BVH] ${a.toLocaleString()} tris → ${this.totalNodes} nodes in ${Math.round(m)}ms | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new ha;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new ha;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Q={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},_a=Q.FLOATS_PER_TRIANGLE,va=16,ya=-1,ba=-2,xa=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length;for(let i=0;i<r;i++){let r=n[i],a=i*_a,o=r*9,s=t[o],c=t[o+1],l=t[o+2],u=t[o+3],d=t[o+4],f=t[o+5],p=t[o+6],m=t[o+7],h=t[o+8];e[a+Q.POSITION_A_OFFSET]=s,e[a+Q.POSITION_A_OFFSET+1]=c,e[a+Q.POSITION_A_OFFSET+2]=l,e[a+Q.POSITION_B_OFFSET]=u,e[a+Q.POSITION_B_OFFSET+1]=d,e[a+Q.POSITION_B_OFFSET+2]=f,e[a+Q.POSITION_C_OFFSET]=p,e[a+Q.POSITION_C_OFFSET+1]=m,e[a+Q.POSITION_C_OFFSET+2]=h;let g=u-s,_=d-c,v=f-l,y=p-s,b=m-c,x=h-l,S=_*x-v*b,C=v*y-g*x,w=g*b-_*y;e[a+Q.NORMAL_A_OFFSET]=S,e[a+Q.NORMAL_A_OFFSET+1]=C,e[a+Q.NORMAL_A_OFFSET+2]=w,e[a+Q.NORMAL_B_OFFSET]=S,e[a+Q.NORMAL_B_OFFSET+1]=C,e[a+Q.NORMAL_B_OFFSET+2]=w,e[a+Q.NORMAL_C_OFFSET]=S,e[a+Q.NORMAL_C_OFFSET+1]=C,e[a+Q.NORMAL_C_OFFSET+2]=w}}refitRange(e,t,n,r){r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let i=this._bounds,a=n+r;for(let r=a-1;r>=n;r--){let a=r*va,o=(r-n)*6;if(e[a+3]===ya){let n=e[a],r=e[a+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<r;e++){let r=(n+e)*_a,i=t[r+Q.POSITION_A_OFFSET],a=t[r+Q.POSITION_A_OFFSET+1],o=t[r+Q.POSITION_A_OFFSET+2],p=t[r+Q.POSITION_B_OFFSET],m=t[r+Q.POSITION_B_OFFSET+1],h=t[r+Q.POSITION_B_OFFSET+2],g=t[r+Q.POSITION_C_OFFSET],_=t[r+Q.POSITION_C_OFFSET+1],v=t[r+Q.POSITION_C_OFFSET+2];s=Math.min(s,i,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,i,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}i[o]=s,i[o+1]=c,i[o+2]=l,i[o+3]=u,i[o+4]=d,i[o+5]=f}else{let t=e[a+3],r=e[a+7],s=(t-n)*6,c=(r-n)*6,l=i[s],u=i[s+1],d=i[s+2],f=i[s+3],p=i[s+4],m=i[s+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];e[a]=l,e[a+1]=u,e[a+2]=d,e[a+4]=f,e[a+5]=p,e[a+6]=m,e[a+8]=h,e[a+9]=g,e[a+10]=_,e[a+12]=v,e[a+13]=y,e[a+14]=b,i[o]=Math.min(l,h),i[o+1]=Math.min(u,g),i[o+2]=Math.min(d,_),i[o+3]=Math.max(f,v),i[o+4]=Math.max(p,y),i[o+5]=Math.max(m,b)}}}refit(e,t,n){n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let r=this._bounds;for(let i=n-1;i>=0;i--){let n=i*va,a=i*6,o=e[n+3];if(o===ya){let i=e[n],o=e[n+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<o;e++){let n=(i+e)*_a,r=t[n+Q.POSITION_A_OFFSET],a=t[n+Q.POSITION_A_OFFSET+1],o=t[n+Q.POSITION_A_OFFSET+2],p=t[n+Q.POSITION_B_OFFSET],m=t[n+Q.POSITION_B_OFFSET+1],h=t[n+Q.POSITION_B_OFFSET+2],g=t[n+Q.POSITION_C_OFFSET],_=t[n+Q.POSITION_C_OFFSET+1],v=t[n+Q.POSITION_C_OFFSET+2];s=Math.min(s,r,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,r,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}r[a]=s,r[a+1]=c,r[a+2]=l,r[a+3]=u,r[a+4]=d,r[a+5]=f}else if(o===ba){let t=e[n]*6;r[a]=r[t],r[a+1]=r[t+1],r[a+2]=r[t+2],r[a+3]=r[t+3],r[a+4]=r[t+4],r[a+5]=r[t+5]}else{let t=e[n+3],i=e[n+7],o=t*6,s=i*6,c=r[o],l=r[o+1],u=r[o+2],d=r[o+3],f=r[o+4],p=r[o+5],m=r[s],h=r[s+1],g=r[s+2],_=r[s+3],v=r[s+4],y=r[s+5];e[n]=c,e[n+1]=l,e[n+2]=u,e[n+4]=d,e[n+5]=f,e[n+6]=p,e[n+8]=m,e[n+9]=h,e[n+10]=g,e[n+12]=_,e[n+13]=v,e[n+14]=y,r[a]=Math.min(c,m),r[a+1]=Math.min(l,h),r[a+2]=Math.min(u,g),r[a+3]=Math.max(d,_),r[a+4]=Math.max(f,v),r[a+5]=Math.max(p,y)}}}},Sa=32,Ca=5e4,wa=8;function Ta(e,t,n,r){let i=e.byteLength/(Sa*4),a=Math.min(navigator.hardwareConcurrency||4,wa),o=Math.ceil(Math.log2(a*2.5+1));return console.log(`[ParallelBVH] Parallel build: ${i.toLocaleString()} triangles, ${a} workers, parallelDepth=${o}`),new Promise((s,c)=>{(async()=>{let c=new SharedArrayBuffer(e.byteLength);new Float32Array(c).set(e);let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*Sa*4),h;try{h=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BarjE67Z.js`).href:new URL(`assets/BVHWorker-BarjE67Z.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;h=await Ge(new URL(`data:text/javascript;base64,aW1wb3J0IHsgQlZIQnVpbGRlciB9IGZyb20gJy4uL0JWSEJ1aWxkZXIuanMnOwoKY29uc3QgRlBUID0gMzI7IC8vIEZMT0FUU19QRVJfVFJJQU5HTEUKCi8vIC0tLSBNZXNzYWdlIGRpc3BhdGNoZXIgLS0tCgpzZWxmLm9ubWVzc2FnZSA9IGZ1bmN0aW9uICggZSApIHsKCgljb25zdCBkYXRhID0gZS5kYXRhOwoJY29uc3QgdHlwZSA9IGRhdGEudHlwZTsKCglpZiAoIHR5cGUgPT09ICdidWlsZFBoYXNlMScgKSB7CgoJCWhhbmRsZVBoYXNlMSggZGF0YSApOwoKCX0gZWxzZSBpZiAoIHR5cGUgPT09ICdhc3NlbWJsZScgKSB7CgoJCWhhbmRsZUFzc2VtYmxlKCBkYXRhICk7CgoJfSBlbHNlIHsKCgkJLy8gTGVnYWN5OiBmdWxsIHNpbmdsZS13b3JrZXIgYnVpbGQgKGJhY2t3YXJkIGNvbXBhdGlibGUpCgkJaGFuZGxlRnVsbEJ1aWxkKCBkYXRhICk7CgoJfQoKfTsKCi8vIC0tLSBQaGFzZSAxOiBJbml0ICsgTW9ydG9uIHNvcnQgKyB0b3AtbGV2ZWwgU0FIIGJ1aWxkIC0tLQoKZnVuY3Rpb24gaGFuZGxlUGhhc2UxKCBkYXRhICkgewoKCWNvbnN0IHsKCQlzaGFyZWRUcmlhbmdsZURhdGEsIHNoYXJlZENlbnRyb2lkcywgc2hhcmVkQk1pbiwgc2hhcmVkQk1heCwKCQlzaGFyZWR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BbIGJ2aERhdGEuYnVmZmVyLCByZW9yZGVyZWRGbG9hdDMyQXJyYXkuYnVmZmVyIF07CgkJCWlmICggb3JpZ2luYWxUb0J2aCApIHRyYW5zZmVyYWJsZXMucHVzaCggb3JpZ2luYWxUb0J2aC5idWZmZXIgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCWJ2aERhdGEsCgkJCQl0cmlhbmdsZXM6IHJlb3JkZXJlZEZsb2F0MzJBcnJheSwKCQkJCW9yaWdpbmFsVG9CdmgsCgkJCQl0cmlhbmdsZUNvdW50LAoJCQkJdHJlZWxldFN0YXRzOiBidWlsZGVyLnNwbGl0U3RhdHMKCQkJfSwgdHJhbnNmZXJhYmxlcyApOwoKCQl9CgoJfSBjYXRjaCAoIGVycm9yICkgewoKCQljb25zb2xlLmVycm9yKCAnW0JWSFdvcmtlcl0gRXJyb3I6JywgZXJyb3IgKTsKCQlzZWxmLnBvc3RNZXNzYWdlKCB7IGVycm9yOiBlcnJvci5tZXNzYWdlIH0gKTsKCgl9Cgp9Cg==`,``+{}.url))}let g=null,_=[h],v={id:null},y=!1,b=()=>{v.id&&=(clearTimeout(v.id),null);for(let e of _)try{e.terminate()}catch{}},x=e=>{if(y)return;y=!0,console.warn(`[ParallelBVH] Parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Float32Array(i).set(new Float32Array(c)),s(Da(new Float32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,Ea(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r).catch(e=>x(e.message));return}if(t.type===`assembleResult`){y=!0,b();let e=new Float32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{console.warn(`[ParallelBVH] Parallel build setup failed:`,e),c(e)})})}async function Ea(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){console.log(`[ParallelBVH] No frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},[_.buffer]);return}console.log(`[ParallelBVH] Phase 2: distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s;try{s=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHSubtreeWorker-CTHfS54a.js`).href:new URL(`assets/BVHSubtreeWorker-CTHfS54a.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;s=await Ge(new URL(`data:text/javascript;base64,aW1wb3J0IHsgQlZIQnVpbGRlciB9IGZyb20gJy4uL0JWSEJ1aWxkZXIuanMnOwppbXBvcnQgeyBUcmVlbGV0T3B0aW1pemVyIH0gZnJvbSAnLi4vVHJlZWxldE9wdGltaXplci5qcyc7CmltcG9ydCB7IFJlaW5zZXJ0aW9uT3B0aW1pemVyIH0gZnJvbSAnLi4vUmVpbnNlcnRpb25PcHRpbWl6ZXIuanMnOwoKc2VsZi5vbm1lc3NhZ2UgPSBmdW5jdGlvbiAoIGUgKSB7CgoJY29uc3QgewoJCXRhc2tzLAoJCXNoYXJlZFRyaWFuZ2xlRGF0YSwgc2hhcmVkQ2VudHJvaWRzLCBzaGFyZWRCTWluLCBzaGFyZWRCTWF4LCBzaGFyZWRJbmRpY2VzLAoJCXRyaWFuZ2xlQ291bnQsCgkJbWF4TGVhZlNpemUsIG51bUJpbnMsIG1heEJpbnMsIG1pbkJpbnMsCgkJdHJlZWxldENvbmZpZywKCQlyZWluc2VydGlvbkNvbmZpZywKCQlyZXBvcnRQcm9ncmVzcwoJfSA9IGUuZGF0YTsKCgkvLyBQcm9jZXNzIGVhY2ggdGFzayBzZXF1ZW50aWFsbHkKCWZvciAoIGxldCB0ID0gMDsgdCA8IHRhc2tzLmxlbmd0aDsgdCArKyApIHsKCgkJY29uc3QgdGFzayA9IHRhc2tzWyB0IF07CgoJCXRyeSB7CgoJCQljb25zdCBidWlsZGVyID0gbmV3IEJWSEJ1aWxkZXIoKTsKCgkJCS8vIEFwcGx5IGNvbmZpZ3VyYXRpb24KCQkJYnVpbGRlci5tYXhMZWFmU2l6ZSA9IG1heExlYWZTaXplOwoJCQlidWlsZGVyLm51bUJpbnMgPSBudW1CaW5zOwoJCQlidWlsZGVyLm1heE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aCAvIDE2OwoKCQkJY29uc3QgYnVpbGRUaW1lID0gcGVyZm9ybWFuY2Uubm93KCkgLSBzdGFydFRpbWU7CgkJCWNvbnNvbGUubG9nKCBgW0JWSFN1YnRyZWVXb3JrZXJdIFRhc2sgJHt0YXNrLnRhc2tJZH06ICR7KCB0YXNrLmVuZCAtIHRhc2suc3RhcnQgKS50b0xvY2FsZVN0cmluZygpfSB0cmlhbmdsZXMsICR7bm9kZUNvdW50fSBub2RlcywgJHtNYXRoLnJvdW5kKCBidWlsZFRpbWUgKX1tc2AgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCXR5cGU6ICdzdWJ0cmVlUmVzdWx0JywKCQkJCXRhc2tJZDogdGFzay50YXNrSWQsCgkJCQlmbGF0RGF0YSwKCQkJCW5vZGVDb3VudAoJCQl9LCBbIGZsYXREYXRhLmJ1ZmZlciBdICk7CgoJCX0gY2F0Y2ggKCBlcnJvciApIHsKCgkJCWNvbnNvbGUuZXJyb3IoIGBbQlZIU3VidHJlZVdvcmtlcl0gVGFzayAke3Rhc2sudGFza0lkfSBlcnJvcjpgLCBlcnJvciApOwoJCQlzZWxmLnBvc3RNZXNzYWdlKCB7CgkJCQl0eXBlOiAnZXJyb3InLAoJCQkJdGFza0lkOiB0YXNrLnRhc2tJZCwKCQkJCWVycm9yOiBlcnJvci5tZXNzYWdlCgkJCX0gKTsKCgkJfQoKCX0KCn07Cg==`,``+{}.url))}d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Da(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o;try{o=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BarjE67Z.js`).href:new URL(`assets/BVHWorker-BarjE67Z.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;o=await Ge(new URL(`data:text/javascript;base64,aW1wb3J0IHsgQlZIQnVpbGRlciB9IGZyb20gJy4uL0JWSEJ1aWxkZXIuanMnOwoKY29uc3QgRlBUID0gMzI7IC8vIEZMT0FUU19QRVJfVFJJQU5HTEUKCi8vIC0tLSBNZXNzYWdlIGRpc3BhdGNoZXIgLS0tCgpzZWxmLm9ubWVzc2FnZSA9IGZ1bmN0aW9uICggZSApIHsKCgljb25zdCBkYXRhID0gZS5kYXRhOwoJY29uc3QgdHlwZSA9IGRhdGEudHlwZTsKCglpZiAoIHR5cGUgPT09ICdidWlsZFBoYXNlMScgKSB7CgoJCWhhbmRsZVBoYXNlMSggZGF0YSApOwoKCX0gZWxzZSBpZiAoIHR5cGUgPT09ICdhc3NlbWJsZScgKSB7CgoJCWhhbmRsZUFzc2VtYmxlKCBkYXRhICk7CgoJfSBlbHNlIHsKCgkJLy8gTGVnYWN5OiBmdWxsIHNpbmdsZS13b3JrZXIgYnVpbGQgKGJhY2t3YXJkIGNvbXBhdGlibGUpCgkJaGFuZGxlRnVsbEJ1aWxkKCBkYXRhICk7CgoJfQoKfTsKCi8vIC0tLSBQa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ZSB7CgoJCQljb25zdCByZW9yZGVyZWRGbG9hdDMyQXJyYXkgPSBidWlsZGVyLnJlb3JkZXJlZFRyaWFuZ2xlRGF0YTsKCQkJY29uc3QgdHJpYW5nbGVDb3VudCA9IHJlb3JkZXJlZEZsb2F0MzJBcnJheS5ieXRlTGVuZ3RoIC8gKCAzMiAqIDQgKTsKCgkJCWNvbnN0IHRyYW5zZmVyYWJsZXMgPSBbIGJ2aERhdGEuYnVmZmVyLCByZW9yZGVyZWRGbG9hdDMyQXJyYXkuYnVmZmVyIF07CgkJCWlmICggb3JpZ2luYWxUb0J2aCApIHRyYW5zZmVyYWJsZXMucHVzaCggb3JpZ2luYWxUb0J2aC5idWZmZXIgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCWJ2aERhdGEsCgkJCQl0cmlhbmdsZXM6IHJlb3JkZXJlZEZsb2F0MzJBcnJheSwKCQkJCW9yaWdpbmFsVG9CdmgsCgkJCQl0cmlhbmdsZUNvdW50LAoJCQkJdHJlZWxldFN0YXRzOiBidWlsZGVyLnNwbGl0U3RhdHMKCQkJfSwgdHJhbnNmZXJhYmxlcyApOwoKCQl9CgoJfSBjYXRjaCAoIGVycm9yICkgewoKCQljb25zb2xlLmVycm9yKCAnW0JWSFdvcmtlcl0gRXJyb3I6JywgZXJyb3IgKTsKCQlzZWxmLnBvc3RNZXNzYWdlKCB7IGVycm9yOiBlcnJvci5tZXNzYWdlIH0gKTsKCgl9Cgp9Cg==`,``+{}.url))}let s=e.byteLength/(Sa*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*Sa*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])})().catch(e=>{console.warn(`[ParallelBVH] Single worker fallback failed:`,e),a(e)})})}function Oa(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Ca}var ka=16,Aa=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.entryIndex=-1}},ja=class{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){if(e.length===0)return{root:null,nodeCount:0};let t=[];for(let n=0;n<e.length;n++)t.push(n);let n=this._buildRecursive(e,t);return{root:n,nodeCount:this._countNodes(n)}}_buildRecursive(e,t){let n=new Aa;if(t.length===1){let r=e[t[0]].worldAABB;return n.minX=r.minX,n.minY=r.minY,n.minZ=r.minZ,n.maxX=r.maxX,n.maxY=r.maxY,n.maxZ=r.maxZ,n.entryIndex=t[0],n}let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let n of t){let t=e[n].worldAABB;t.minX<r&&(r=t.minX),t.minY<i&&(i=t.minY),t.minZ<a&&(a=t.minZ),t.maxX>o&&(o=t.maxX),t.maxY>s&&(s=t.maxY),t.maxZ>c&&(c=t.maxZ)}if(n.minX=r,n.minY=i,n.minZ=a,n.maxX=o,n.maxY=s,n.maxZ=c,t.length===2)return n.leftChild=this._buildRecursive(e,[t[0]]),n.rightChild=this._buildRecursive(e,[t[1]]),n;let l=this._surfaceArea(r,i,a,o,s,c),u=1/0,d=0,f=0;if(l>0&&isFinite(l))for(let n=0;n<3;n++){let r=t.slice().sort((t,r)=>{let i=e[t].worldAABB,a=e[r].worldAABB;return this._centroid(i,n)-this._centroid(a,n)});for(let t=1;t<r.length;t++){let i=this._computeGroupAABB(e,r,0,t),a=this._computeGroupAABB(e,r,t,r.length),o=this._surfaceArea(i.minX,i.minY,i.minZ,i.maxX,i.maxY,i.maxZ),s=this._surfaceArea(a.minX,a.minY,a.minZ,a.maxX,a.maxY,a.maxZ),c=1+(o*t+s*(r.length-t))/l;c<u&&(u=c,d=n,f=t)}}if(f<=0||f>=t.length){d=0;let e=o-r,n=s-i,l=c-a;n>e&&n>l?d=1:l>e&&(d=2),f=t.length>>1}let p=t.slice().sort((t,n)=>this._centroid(e[t].worldAABB,d)-this._centroid(e[n].worldAABB,d)),m=p.slice(0,f),h=p.slice(f);return n.leftChild=this._buildRecursive(e,m),n.rightChild=this._buildRecursive(e,h),n}flatten(e,t){if(!e)return new Float32Array;let n=[],r=[e];for(;r.length>0;){let e=r.pop();e._flatIndex=n.length,n.push(e),e.rightChild&&r.push(e.rightChild),e.leftChild&&r.push(e.leftChild)}let i=n.length*ka;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer;a.fill(0,0,i);for(let e=0;e<n.length;e++){let r=n[e],i=e*ka;if(r.leftChild){let e=r.leftChild,t=r.rightChild;a[i]=e.minX,a[i+1]=e.minY,a[i+2]=e.minZ,a[i+3]=e._flatIndex,a[i+4]=e.maxX,a[i+5]=e.maxY,a[i+6]=e.maxZ,a[i+7]=t._flatIndex,a[i+8]=t.minX,a[i+9]=t.minY,a[i+10]=t.minZ,a[i+12]=t.maxX,a[i+13]=t.maxY,a[i+14]=t.maxZ}else a[i]=t[r.entryIndex].blasOffset,a[i+1]=r.entryIndex,a[i+3]=W.BLAS_POINTER_LEAF}return a.subarray(0,i)}_centroid(e,t){return t===0?(e.minX+e.maxX)*.5:t===1?(e.minY+e.maxY)*.5:(e.minZ+e.maxZ)*.5}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}_computeGroupAABB(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=e[t[u]].worldAABB;n.minX<i&&(i=n.minX),n.minY<a&&(a=n.minY),n.minZ<o&&(o=n.minZ),n.maxX>s&&(s=n.maxX),n.maxY>c&&(c=n.maxY),n.maxZ>l&&(l=n.maxZ)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l}}_countNodes(e){if(!e)return 0;let t=0,n=[e];for(;n.length>0;){let e=n.pop();t++,e.leftChild&&n.push(e.leftChild),e.rightChild&&n.push(e.rightChild)}return t}},Ma=class{constructor(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}allocate(e){this.entries=Array(e).fill(null)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a}){this.entries[e]={meshIndex:e,blasOffset:0,blasNodeCount:t,triOffset:n,triCount:r,worldAABB:null,originalToBvhMap:i,bvhData:a}}computeAABBs(e){for(let t of this.entries)t&&(t.worldAABB=this._readRootAABB(t.bvhData,t,e))}recomputeAABB(e,t,n){let r=this.entries[e],i=t.subarray(r.blasOffset*16,r.blasOffset*16+16);r.worldAABB=this._readRootAABB(i,r,n)}_readRootAABB(e,t,n){if(e[3]===-1)return this._computeAABBFromTriangles(t,n);let r=e[0],i=e[1],a=e[2],o=e[4],s=e[5],c=e[6],l=e[8],u=e[9],d=e[10],f=e[12],p=e[13],m=e[14];return{minX:Math.min(r,l),minY:Math.min(i,u),minZ:Math.min(a,d),maxX:Math.max(o,f),maxY:Math.max(s,p),maxZ:Math.max(c,m)}}_computeAABBFromTriangles(e,t){let n=H.FLOATS_PER_TRIANGLE,r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let l=0;l<e.triCount;l++){let u=(e.triOffset+l)*n;for(let e=0;e<=8;e+=4){let n=t[u+e],l=t[u+e+1],d=t[u+e+2];n<r&&(r=n),l<i&&(i=l),d<a&&(a=d),n>o&&(o=n),l>s&&(s=l),d>c&&(c=d)}}return{minX:r,minY:i,minZ:a,maxX:o,maxY:s,maxZ:c}}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e of this.entries)e&&(e.blasOffset=t,t+=e.blasNodeCount);this.totalBLASNodes=t-e}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}get count(){return this.entries.length}clear(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}},Na=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Le.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},Pa=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Be.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Be.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<Le.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},Fa=class{constructor(e=Le.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``;t+=`${e}x${r}_${i.slice(-8)}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e),this.cache.get(e)}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Ia=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Le.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this.canvasPool=new Na,this.bufferPool=new Pa({maxMemory:e.maxBufferMemory||Be.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Fa,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:navigator.hardwareConcurrency||4}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}async createTexturesToDataTexture(e){if(!e||e.length===0)return null;let t=this.textureCache.generateHash(e),n=this.textureCache.get(t);if(n)return n;let{normalized:r,bitmapsToClose:i}=await this._normalizeTexturesForProcessing(e),a=this.selectProcessingStrategy(r),o;try{switch(a.method){case`worker-direct`:o=await this.processWithWorkerDirect(r);break;case`worker-chunked`:o=await this.processWithWorkerChunked(r,a.chunkSize);break;case`main-batch`:o=await this.processOnMainThreadBatch(r,a.batchSize);break;case`main-streaming`:o=await this.processOnMainThreadStreaming(r);break;default:o=await this.processOnMainThreadSync(r)}return o&&this.textureCache.set(t,o),o}catch(e){return console.warn(`Texture processing failed, trying fallback:`,e),await this.processOnMainThreadSync(r)}finally{for(let e of i)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Be.MAX_TEXTURE_MEMORY?{method:`worker-chunked`,chunkSize:Math.max(1,Math.floor(e.length/4))}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;try{let t;try{t=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/TexturesWorker-DBqGmVdR.js`).href:new URL(`assets/TexturesWorker-DBqGmVdR.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;t=await Ge(new URL(`data:text/javascript;base64,bGV0IGNhbnZhcywgY3R4OwoKLy8gTWVtb3J5IGxpbWl0cyBhbmQgY2h1bmtpbmcgY29uZmlndXJhdGlvbgpjb25zdCBNRU1P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3JpZ2luYWwubWF4V2lkdGggLyAyICkgKSwKCQltYXhIZWlnaHQ6IE1hdGgubWF4KCAxLCBNYXRoLmZsb29yKCBvcmlnaW5hbC5tYXhIZWlnaHQgLyAyICkgKQoJfTsKCn0KCg==`,``+{}.url))}let n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:Le.MAX_TEXTURE_SIZE,method:`direct-transfer`},i)});return t.terminate(),this.createDataArrayTextureFromResult(r)}finally{this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[];for(let n of e)if(n?.image)try{if(typeof createImageBitmap<`u`&&n.image instanceof HTMLImageElement){let e=await createImageBitmap(n.image);t.push({bitmap:e,width:n.image.width,height:n.image.height,isDirect:!0})}else{let e=this.canvasPool.getCanvasWithContext(n.image.width,n.image.height);e.context.drawImage(n.image,0,0);let r=e.context.getImageData(0,0,n.image.width,n.image.height);t.push({data:r.data.buffer,width:n.image.width,height:n.image.height,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(e)}}catch(e){console.warn(`Failed to prepare texture for worker:`,e)}return t}async processWithWorkerChunked(e,t){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t),a=await this.processWithWorkerDirect(i);n.push(a)}return this.combineTextureResults(n)}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`});s.push(a.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e];o.context.clearRect(0,0,n,r),o.context.drawImage(i.image,0,0,n,r);let s=o.context.getImageData(0,0,n,r),c=n*r*4*e;a.set(s.data,c),e%Be.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e];o.context.clearRect(0,0,n,r),o.context.drawImage(i.image,0,0,n,r);let s=o.context.getImageData(0,0,n,r),c=n*r*4*e;a.set(s.data,c)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=U.FLOATS_PER_MATERIAL,n=e.length,r=n*t,i=new Float32Array(r);for(let r=0;r<n;r++){let n=e[r],a=r*t,o=n.mapMatrix??Re,s=n.normalMapMatrices??Re,c=n.roughnessMapMatrices??Re,l=n.metalnessMapMatrices??Re,u=n.emissiveMapMatrices??Re,d=n.bumpMapMatrices??Re,f=n.displacementMapMatrices??Re,p=[n.ior,n.transmission,n.thickness,n.emissiveIntensity,n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b,n.attenuationDistance,n.opacity,n.side,n.transparent,n.alphaTest,n.alphaMode,n.depthWrite,n.normalScale?.x??1,n.normalScale?.y??1,n.color.r,n.color.g,n.color.b,n.metalness,n.emissive.r,n.emissive.g,n.emissive.b,n.roughness,n.map,n.normalMap,n.roughnessMap,n.metalnessMap,n.emissiveMap,n.bumpMap,n.clearcoat,n.clearcoatRoughness,n.dispersion,n.visible,n.sheen,n.sheenRoughness,n.sheenColor.r,n.sheenColor.g,n.sheenColor.b,1,n.specularIntensity,n.specularColor.r,n.specularColor.g,n.specularColor.b,n.iridescence,n.iridescenceIOR,n.iridescenceThicknessRange[0],n.iridescenceThicknessRange[1],n.bumpScale,n.displacementScale,n.displacementMap,0,o[0],o[1],o[2],o[3],o[4],o[5],o[6],1,s[0],s[1],s[2],s[3],s[4],s[5],s[6],1,c[0],c[1],c[2],c[3],c[4],c[5],c[6],1,l[0],l[1],l[2],l[3],l[4],l[5],l[6],1,u[0],u[1],u[2],u[3],u[4],u[5],u[6],1,d[0],d[1],d[2],d[3],d[4],d[5],d[6],1,f[0],f[1],f[2],f[3],f[4],f[5],f[6],1];i.set(p,a)}return i}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=Le.VEC4_PER_BVH_NODE*Le.FLOATS_PER_VEC4,i=t.length*r,a=new Float32Array(i);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,o=t[e],s=t[r];a[n]=o.boundsMin.x,a[n+1]=o.boundsMin.y,a[n+2]=o.boundsMin.z,a[n+3]=e,a[n+4]=o.boundsMax.x,a[n+5]=o.boundsMax.y,a[n+6]=o.boundsMax.z,a[n+7]=r,a[n+8]=s.boundsMin.x,a[n+9]=s.boundsMin.y,a[n+10]=s.boundsMin.z,a[n+12]=s.boundsMax.x,a[n+13]=s.boundsMax.y,a[n+14]=s.boundsMax.z}else a[n]=i.triangleOffset,a[n+1]=i.triangleCount,a[n+3]=-1}return a}async createMaterialTextures(e){let{materials:t,maps:r,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new Fa;let e=[];r&&r.length>0&&e.push(this.createTexturesToDataTexture(r).then(e=>({type:`albedo`,texture:e})).catch(e=>(console.warn(`Failed to create albedo textures:`,e),{type:`albedo`,texture:null}))),i&&i.length>0&&e.push(this.createTexturesToDataTexture(i).then(e=>({type:`normal`,texture:e})).catch(e=>(console.warn(`Failed to create normal textures:`,e),{type:`normal`,texture:null}))),a&&a.length>0&&e.push(this.createTexturesToDataTexture(a).then(e=>({type:`bump`,texture:e})).catch(e=>(console.warn(`Failed to create bump textures:`,e),{type:`bump`,texture:null}))),o&&o.length>0&&e.push(this.createTexturesToDataTexture(o).then(e=>({type:`roughness`,texture:e})).catch(e=>(console.warn(`Failed to create roughness textures:`,e),{type:`roughness`,texture:null}))),s&&s.length>0&&e.push(this.createTexturesToDataTexture(s).then(e=>({type:`metalness`,texture:e})).catch(e=>(console.warn(`Failed to create metalness textures:`,e),{type:`metalness`,texture:null}))),c&&c.length>0&&e.push(this.createTexturesToDataTexture(c).then(e=>({type:`emissive`,texture:e})).catch(e=>(console.warn(`Failed to create emissive textures:`,e),{type:`emissive`,texture:null}))),l&&l.length>0&&e.push(this.createTexturesToDataTexture(l).then(e=>({type:`displacement`,texture:e})).catch(e=>(console.warn(`Failed to create displacement textures:`,e),{type:`displacement`,texture:null})));let d=await Promise.allSettled(e),f={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:r}=e.value;if(r)switch(t){case`albedo`:r.colorSpace=n.SRGBColorSpace,f.albedoTexture=r;break;case`normal`:f.normalTexture=r;break;case`bump`:f.bumpTexture=r;break;case`roughness`:f.roughnessTexture=r;break;case`metalness`:f.metalnessTexture=r;break;case`emissive`:r.colorSpace=n.SRGBColorSpace,f.emissiveTexture=r;break;case`displacement`:f.displacementTexture=r;break}}});let p=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${p.toFixed(2)}ms)`),f}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);for(t=2**Math.ceil(Math.log2(t)),n=2**Math.ceil(Math.log2(n));t>=Le.MAX_TEXTURE_SIZE/2||n>=Le.MAX_TEXTURE_SIZE/2;)t=Math.max(1,Math.floor(t/2)),n=Math.max(1,Math.floor(n/2));return{maxWidth:t,maxHeight:n}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,r,i){let a=new n.DataArrayTexture(e,t,r,i);a.minFilter=n.LinearFilter,a.magFilter=n.LinearFilter,a.format=n.RGBAFormat,a.type=n.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],r=[],i=[];for(let r of e)if(r?.image){if(r.isCompressedTexture&&r.format===n.RGBAFormat&&r.mipmaps?.[0]?.data){let e=r.mipmaps[0],n=t.length;t.push(null),i.push({index:n,promise:La(e.data,e.width,e.height)});continue}if(r.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(r.image.data&&!(r.image instanceof HTMLImageElement)&&!(r.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&r.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,promise:La(r.image.data,r.image.width,r.image.height)});continue}t.push(r)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let n=0;n<i.length;n++){let{index:a}=i[n],o=e[n];if(o.status===`fulfilled`){let e=o.value;r.push(e),t[a]={image:e}}else console.warn(`[TextureCreator] Failed to create ImageBitmap:`,o.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let n=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(n,1,1));r.push(i),t[e]={image:i}}return{normalized:t,bitmapsToClose:r}}createFallbackTexture(){let e=new n.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=n.LinearFilter,e.magFilter=n.LinearFilter,e.format=n.RGBAFormat,e.type=n.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}combineTextureResults(e){return e[0]}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function La(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var Ra=128,za=class{constructor(){this._vectorPool={vec3:Array(9).fill().map(()=>new n.Vector3),vec2:[,,,,,,].fill().map(()=>new n.Vector2)},this._matrixPool={mat3:new n.Matrix3,mat4:new n.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){return this.resetArrays(),this._triangleCapacity=1024,this.triangleData=new Float32Array(this._triangleCapacity*H.FLOATS_PER_TRIANGLE),this.currentTriangleIndex=0,this.traverseObject(e),this.logStats(),this.getExtractedData()}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this._triangleCapacity;for(;t<e;)t*=2;let n=new Float32Array(t*H.FLOATS_PER_TRIANGLE);n.set(this.triangleData),this.triangleData=n,this._triangleCapacity=t}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=this.currentTriangleIndex;this.extractGeometry(e,t,n),this.meshTriangleRanges.push({start:r,count:this.currentTriangleIndex-r})}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,console.warn(`Depth write is disabled in material, enabling it for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t),n.clearcoat>0&&(this.sceneFeatures.hasClearcoat=!0),n.transmission>0&&(this.sceneFeatures.hasTransmission=!0),n.dispersion>0&&(this.sceneFeatures.hasDispersion=!0),n.iridescence>0&&(this.sceneFeatures.hasIridescence=!0),n.sheen>0&&(this.sceneFeatures.hasSheen=!0),(n.transparent||n.opacity<1||n.alphaTest>0)&&(this.sceneFeatures.hasTransparency=!0),[n.clearcoat>0,n.transmission>0,n.iridescence>0,n.sheen>0].filter(Boolean).length>=2&&(this.sceneFeatures.hasMultiLobeMaterials=!0)}return t}getMaterialAlphaMode(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:t===`MASK`?1:0}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===n.RGBAFormat&&e.transparent?2:0}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){return{emissive:new n.Color(0,0,0),emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:.1,attenuationColor:new n.Color(16777215),attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:new n.Color(0),specularIntensity:1,specularColor:new n.Color(16777215),clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:{x:1,y:1},bumpScale:1,displacementScale:1,alphaTest:0}}mapLegacyMaterialToPhysical(e,t){let r={};switch(t){case`basic`:r.emissive=e.color.clone(),r.emissiveIntensity=1,r.color=new n.Color(0),r.roughness=1,r.metalness=0;break;case`lambert`:r.roughness=1,r.metalness=0,r.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;r.roughness=Math.sqrt(2/(t+2)),r.metalness=0}if(e.specular){let t=e.specular.r*.299+e.specular.g*.587+e.specular.b*.114;r.specularIntensity=Math.min(t*2,1),r.specularColor=e.specular.clone()}break;case`toon`:r.roughness=.9,r.metalness=0;break;case`standard`:case`physical`:break}return r}createMaterialObject(e){let t=this.getPhysicalDefaults(),r=this.getMaterialType(e),i=this.mapLegacyMaterialToPhysical(e,r),a=(e.metalness??i.metalness??0)>.1,o=t.ior;a?o=2.5:e.transmission>0&&(o=1.5);let s=e.color||new n.Color(16777215);return r===`basic`&&!e.map&&(s=new n.Color(0)),{uuid:e.uuid,color:s,emissive:i.emissive??e.emissive??t.emissive,emissiveIntensity:i.emissiveIntensity??e.emissiveIntensity??t.emissiveIntensity,roughness:Math.max(.05,i.roughness??e.roughness??t.roughness),metalness:i.metalness??e.metalness??t.metalness,ior:e.ior??o,opacity:e.opacity??t.opacity,transmission:e.transmission??t.transmission,thickness:e.thickness??t.thickness,attenuationColor:e.attenuationColor??t.attenuationColor,attenuationDistance:e.attenuationDistance??t.attenuationDistance,dispersion:e.dispersion??t.dispersion,sheen:e.sheen??t.sheen,sheenRoughness:e.sheenRoughness??t.sheenRoughness,sheenColor:e.sheenColor??t.sheenColor,clearcoat:e.clearcoat??t.clearcoat,clearcoatRoughness:e.clearcoatRoughness??t.clearcoatRoughness,iridescence:e.iridescence??t.iridescence,iridescenceIOR:e.iridescenceIOR??t.iridescenceIOR,iridescenceThicknessRange:e.iridescenceThicknessRange??t.iridescenceThicknessRange,specularIntensity:i.specularIntensity??e.specularIntensity??t.specularIntensity,specularColor:i.specularColor??e.specularColor??t.specularColor,normalScale:e.normalScale??t.normalScale,bumpScale:e.bumpScale??t.bumpScale,displacementScale:e.displacementScale??t.displacementScale,transparent:e.transparent?1:0,alphaTest:e.alphaTest??t.alphaTest,alphaMode:this.getMaterialAlphaMode(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(e.map,this.maps),normalMap:this.processTexture(e.normalMap,this.normalMaps),bumpMap:this.processTexture(e.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(e.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(e.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(e.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(e.displacementMap,this.displacementMaps),clearcoatMap:this.processTexture(e.clearcoatMap,[]),clearcoatRoughnessMap:this.processTexture(e.clearcoatRoughnessMap,[]),transmissionMap:this.processTexture(e.transmissionMap,[]),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(e.sheenColorMap,[]),sheenRoughnessMap:this.processTexture(e.sheenRoughnessMap,[]),specularIntensityMap:this.processTexture(e.specularIntensityMap,[]),specularColorMap:this.processTexture(e.specularColorMap,[]),iridescenceMap:this.processTexture(e.iridescenceMap,[]),iridescenceThicknessMap:this.processTexture(e.iridescenceThicknessMap,[]),mapMatrix:this.getTextureMatrix(e.map),normalMapMatrices:this.getTextureMatrix(e.normalMap),bumpMapMatrices:this.getTextureMatrix(e.bumpMap),roughnessMapMatrices:this.getTextureMatrix(e.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(e.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(e.emissiveMap),displacementMapMatrices:this.getTextureMatrix(e.displacementMap),originalType:r}}getTextureMatrix(e){return e?(e.updateMatrix(),e.matrix.elements):new n.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case n.FrontSide:return 0;case n.BackSide:return 1;case n.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<Ra){t.push(e);let i=t.length-1;return n.set(r,i),i}return-1}extractGeometry(e,t,n){e.updateMatrix(),e.updateMatrixWorld();let r=e.geometry;r.attributes.normal||r.computeVertexNormals();let i=r.attributes.position,a=r.attributes.normal,o=r.attributes.uv,s=r.index?r.index.array:null;this._matrixPool.mat4.copy(e.matrixWorld),this._matrixPool.mat3.getNormalMatrix(this._matrixPool.mat4);let c=s?s.length/3:i.count/3;this.extractTrianglesInBatch(i,a,o,s,c,t,n)}extractTrianglesInBatch(e,t,n,r,i,a,o){let s=this._getVec3(0),c=this._getVec3(1),l=this._getVec3(2),u=this._getVec3(3),d=this._getVec3(4),f=this._getVec3(5),p=this._getVec2(0),m=this._getVec2(1),h=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);for(let g=0;g<i;g++){let i=g*3,_=r?r[i+0]:i+0,v=r?r[i+1]:i+1,y=r?r[i+2]:i+2;this.getVertex(e,_,s),this.getVertex(e,v,c),this.getVertex(e,y,l),this.getVertex(t,_,u),this.getVertex(t,v,d),this.getVertex(t,y,f),n?(this.getVertex(n,_,p),this.getVertex(n,v,m),this.getVertex(n,y,h)):(p.set(0,0),m.set(0,0),h.set(0,0)),s.applyMatrix4(this._matrixPool.mat4),c.applyMatrix4(this._matrixPool.mat4),l.applyMatrix4(this._matrixPool.mat4),u.applyMatrix3(this._matrixPool.mat3).normalize(),d.applyMatrix3(this._matrixPool.mat3).normalize(),f.applyMatrix3(this._matrixPool.mat3).normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,s,c,l,u,d,f,p,m,h,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=e*H.FLOATS_PER_TRIANGLE;this.triangleData[f+H.POSITION_A_OFFSET+0]=t.x,this.triangleData[f+H.POSITION_A_OFFSET+1]=t.y,this.triangleData[f+H.POSITION_A_OFFSET+2]=t.z,this.triangleData[f+H.POSITION_A_OFFSET+3]=0,this.triangleData[f+H.POSITION_B_OFFSET+0]=n.x,this.triangleData[f+H.POSITION_B_OFFSET+1]=n.y,this.triangleData[f+H.POSITION_B_OFFSET+2]=n.z,this.triangleData[f+H.POSITION_B_OFFSET+3]=0,this.triangleData[f+H.POSITION_C_OFFSET+0]=r.x,this.triangleData[f+H.POSITION_C_OFFSET+1]=r.y,this.triangleData[f+H.POSITION_C_OFFSET+2]=r.z,this.triangleData[f+H.POSITION_C_OFFSET+3]=0,this.triangleData[f+H.NORMAL_A_OFFSET+0]=i.x,this.triangleData[f+H.NORMAL_A_OFFSET+1]=i.y,this.triangleData[f+H.NORMAL_A_OFFSET+2]=i.z,this.triangleData[f+H.NORMAL_A_OFFSET+3]=0,this.triangleData[f+H.NORMAL_B_OFFSET+0]=a.x,this.triangleData[f+H.NORMAL_B_OFFSET+1]=a.y,this.triangleData[f+H.NORMAL_B_OFFSET+2]=a.z,this.triangleData[f+H.NORMAL_B_OFFSET+3]=0,this.triangleData[f+H.NORMAL_C_OFFSET+0]=o.x,this.triangleData[f+H.NORMAL_C_OFFSET+1]=o.y,this.triangleData[f+H.NORMAL_C_OFFSET+2]=o.z,this.triangleData[f+H.NORMAL_C_OFFSET+3]=0,this.triangleData[f+H.UV_AB_OFFSET+0]=s.x,this.triangleData[f+H.UV_AB_OFFSET+1]=s.y,this.triangleData[f+H.UV_AB_OFFSET+2]=c.x,this.triangleData[f+H.UV_AB_OFFSET+3]=c.y,this.triangleData[f+H.UV_C_MAT_OFFSET+0]=l.x,this.triangleData[f+H.UV_C_MAT_OFFSET+1]=l.y,this.triangleData[f+H.UV_C_MAT_OFFSET+2]=u,this.triangleData[f+H.UV_C_MAT_OFFSET+3]=d}getTriangleData(){return this.triangleData?this.triangleData.subarray(0,this.currentTriangleIndex*H.FLOATS_PER_TRIANGLE):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*H.FLOATS_PER_TRIANGLE*4;console.log(`materials:`,this.materials.length),console.log(`triangles:`,this.currentTriangleIndex),console.log(`triangle data size (MB):`,(e/(1024*1024)).toFixed(2)),console.log(`maps:`,this.maps.length)}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this.triangleData=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.meshes=[],this.meshTriangleRanges=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap,this.sceneFeatures={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0}}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,directionalLights:this.directionalLights,cameras:this.cameras,sceneFeatures:this.sceneFeatures}}},Ba=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=(t,r)=>{let s=a++,c=s*16,l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0,h=0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];l=Math.min(l,t.bMinX),u=Math.min(u,t.bMinY),d=Math.min(d,t.bMinZ),f=Math.max(f,t.bMaxX),p=Math.max(p,t.bMaxY),m=Math.max(m,t.bMaxZ),h+=t.power,g=Math.min(g,t.cx),_=Math.min(_,t.cy),v=Math.min(v,t.cz),y=Math.max(y,t.cx),b=Math.max(b,t.cy),x=Math.max(x,t.cz)}i[c+0]=l,i[c+1]=u,i[c+2]=d,i[c+3]=h,i[c+4]=f,i[c+5]=p,i[c+6]=m,i[c+12]=0,i[c+13]=0,i[c+14]=0,i[c+15]=0;let S=r-t;if(S<=this.maxLeafSize)i[c+7]=1,i[c+8]=t,i[c+9]=S,i[c+10]=0,i[c+11]=0;else{let a=y-g,s=b-_,l=x-v,u;u=a>=s&&a>=l?0:s>=l?1:2;let d=[`cx`,`cy`,`cz`][u],f=t+r>>1;this._nthElement(n,e,t,r,f,d),i[c+7]=0;let p=o(t,f),m=o(f,r);i[c+8]=p,i[c+9]=m,i[c+10]=0,i[c+11]=0}return s};o(0,t);let s=new Int32Array(t);for(let e=0;e<t;e++)s[e]=n[e];let c=new Float32Array(a*16);return c.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:c,nodeCount:a,sortedPerm:s}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}},Va=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0}extractEmissiveTriangles(e,t,n){console.log(`[EmissiveTriangleBuilder] Extracting emissive triangles...`),this.emissiveTriangles=[],this.totalEmissivePower=0;let r=H.FLOATS_PER_TRIANGLE,i=H.UV_C_MAT_OFFSET+2;for(let a=0;a<n;a++){let n=a*r,o=Math.floor(e[n+i]),s=t[o];if(!s)continue;let c=s.emissive||{r:0,g:0,b:0},l=s.emissiveIntensity||0;if(l>0&&(c.r>0||c.g>0||c.b>0)){let t=e[n+0],r=e[n+1],i=e[n+2],s=e[n+4],u=e[n+5],d=e[n+6],f=e[n+8],p=e[n+9],m=e[n+10],h=this._calculateTriangleArea(t,r,i,s,u,d,f,p,m),g=(c.r+c.g+c.b)/3*l*h,_=(t+s+f)/3,v=(r+u+p)/3,y=(i+d+m)/3,b=Math.min(t,s,f),x=Math.min(r,u,p),S=Math.min(i,d,m),C=Math.max(t,s,f),w=Math.max(r,u,p),T=Math.max(i,d,m);this.emissiveTriangles.push({triangleIndex:a,materialIndex:o,power:g,area:h,emissive:{r:c.r,g:c.g,b:c.b},emissiveIntensity:l,cx:_,cy:v,cz:y,bMinX:b,bMinY:x,bMinZ:S,bMaxX:C,bMaxY:w,bMaxZ:T}),this.totalEmissivePower+=g}}return this.emissiveCount=this.emissiveTriangles.length,console.log(`[EmissiveTriangleBuilder] Found ${this.emissiveCount} emissive triangles (${(this.emissiveCount/n*100).toFixed(2)}%)`),console.log(`[EmissiveTriangleBuilder] Total emissive power: ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new n.DataTexture(new Float32Array(4),1,1,n.RGBAFormat,n.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),r=Math.ceil(this.emissiveCount/t),i=t*r*4,a=new Float32Array(i);a.set(e);let o=new n.DataTexture(a,t,r,n.RGBAFormat,n.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=n.NearestFilter,o.magFilter=n.NearestFilter,console.log(`[EmissiveTriangleBuilder] Created ${t}x${r} emissive texture (${this.emissiveCount} emissives)`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return console.log(`[EmissiveTriangleBuilder] Created emissive raw data: ${this.emissiveCount} entries (${e.byteLength} bytes)`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=t.emissive||{r:0,g:0,b:0},o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=(a.r+a.g+a.b)/3;this.totalEmissivePower=0;for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t];n.materialIndex===e&&(n.power=c*o*n.area,n.emissive={r:a.r,g:a.g,b:a.b},n.emissiveIntensity=o,this.emissivePowerArray[t]=n.power),this.totalEmissivePower+=this.emissiveTriangles[t].power}return this._buildCDF(),!0}buildLightBVH(){if(this.emissiveCount===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeCount=1,1;let{nodeData:e,nodeCount:t,sortedPerm:n}=new Ba().build(this.emissiveTriangles);return this.lightBVHNodeData=e,this.lightBVHNodeCount=t,this._rebuildSortedEmissiveData(n),t}_rebuildSortedEmissiveData(e){let t=e.length;this.emissiveIndicesArray=new Int32Array(t),this.emissivePowerArray=new Float32Array(t);for(let n=0;n<t;n++){let t=e[n];this.emissiveIndicesArray[n]=this.emissiveTriangles[t].triangleIndex,this.emissivePowerArray[n]=this.emissiveTriangles[t].power}this._buildCDF();let n=new Float32Array(t*8);for(let r=0;r<t;r++){let t=e[r],i=this.emissiveTriangles[t],a=r*8;n[a+0]=i.triangleIndex,n[a+1]=i.power,n[a+2]=this.cdfArray[r],n[a+3]=this.totalEmissivePower>0?i.power/this.totalEmissivePower:0,n[a+4]=i.emissive.r*i.emissiveIntensity,n[a+5]=i.emissive.g*i.emissiveIntensity,n[a+6]=i.emissive.b*i.emissiveIntensity,n[a+7]=i.area}this.emissiveTriangleData=n,console.log(`[EmissiveTriangleBuilder] Rebuilt sorted emissive data: ${t} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0}},Ha=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,...e},this.triangleData=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvhData=null,this.materialData=null,this.instanceTable=null,this.originalToBvhMap=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.albedoTextures=null,this.normalTextures=null,this.bumpTextures=null,this.roughnessTextures=null,this.metalnessTextures=null,this.emissiveTextures=null,this.displacementTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}_initProcessors(){this.geometryExtractor=new za,this.bvhBuilder=new ga,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement}),this.textureCreator=new Ia,this.emissiveTriangleBuilder=new Va,this.tlasBuilder=new ja}_log(e,t){this.config.verbose&&console.log(`[SceneProcessor] ${e}`,t||``)}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`;let t=new sa(`SceneProcessor (${e.name||`scene`})`);try{this._reset(),this._log(`Starting scene processing`),this.processingStage=`extraction`,t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,z({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||z({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvhData&&(this.bvhData=this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,z({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,console.error(`[SceneProcessor] Processing error:`,e),z({status:`Error: ${e.message}`,progress:100}),e}finally{this.isProcessing=!1}}async _extractGeometry(e){z({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this.triangleData=n.triangleData,this.triangleCount=n.triangleCount,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangleData.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.materialCount=this.materials.length,this.meshes=n.meshes,this.meshTriangleRanges=n.meshTriangleRanges,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.directionalLights=n.directionalLights,this.cameras=n.cameras,this.sceneFeatures=n.sceneFeatures;let r=performance.now()-t;this._log(`Geometry extraction complete (${r.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),z({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw console.error(`[SceneProcessor] Geometry extraction error:`,e),z({status:`Extraction error: ${e.message}`,progress:25}),e}}async _buildBVH(){if(z({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`);let e=performance.now();try{let t=H.FLOATS_PER_TRIANGLE,n=this.meshTriangleRanges;if(!n||n.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);this.instanceTable=new Ma,this.instanceTable.allocate(n.length);let r=n.length,i=this.config.enableTreeletOptimization,a=[],o=[];for(let e=0;e<r;e++){let t=n[e];t.count!==0&&(t.count>=2e5&&Oa(t.count)?o.push({m:e,range:t}):a.push({m:e,range:t}))}let s={depth:this.config.bvhDepth,treeletOptimization:{enabled:i!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},c=a.length+o.length,l=this._buildBLASesWithPool(a,s,e=>{z({status:`Building BLAS ${e+o.length}/${c}...`,progress:25+Math.floor(e/c*45)})}),u=o.map(({m:e,range:n})=>Ta(this.triangleData.slice(n.start*t,(n.start+n.count)*t),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...s}).then(t=>({m:e,range:n,result:t}))),[d,f]=await Promise.all([l,Promise.all(u)]);for(let{m:e,range:n,result:r}of[...d,...f])r.reorderedTriangles&&this.triangleData.set(r.reorderedTriangles,n.start*t),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:n.start,triCount:n.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData});z({status:`Built all BLASes`,progress:70}),z({status:`Building TLAS...`,progress:72});let p=this.instanceTable.entries.filter(e=>e!==null);if(p.length===1){let e=p[0];this.bvhData=e.bvhData,this.instanceTable.assignOffsets(0),this._buildGlobalOriginalToBvhMap(),e.originalToBvhMap=null,e.bvhData=null}else{this.instanceTable.computeAABBs(this.triangleData);let{root:e,nodeCount:t}=this.tlasBuilder.build(p);this.instanceTable.assignOffsets(t);let n=this.instanceTable.totalNodeCount,r=this.tlasBuilder.flatten(e,p);this.bvhData=new Float32Array(n*16),this.bvhData.set(r);for(let e of p){let t=e.blasOffset*16;this.bvhData.set(e.bvhData,t),this._offsetBLASInPlace(t,e.bvhData.length/16,e.blasOffset,e.triOffset)}this._buildGlobalOriginalToBvhMap();for(let e of p)e.originalToBvhMap=null,e.bvhData=null}this.bvhRoot=!0,this._disposeRefitWorker();let m=performance.now()-e;this._log(`BVH complete: ${p.length} mesh(es), ${this.bvhData.length/16} nodes (${m.toFixed(2)}ms)`),z({status:`BVH construction complete`,progress:75})}catch(e){throw console.error(`[SceneProcessor] BVH building error:`,e),z({status:`BVH error: ${e.message}`,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){for(let i=0;i<t;i++){let t=e+i*16;this.bvhData[t+3]===-1?this.bvhData[t]+=r:(this.bvhData[t+3]+=n,this.bvhData[t+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=H.FLOATS_PER_TRIANGLE,i=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),a=[],o=0,s=0;return new Promise((c,l)=>{let u=[],d=n=>{if(o>=e.length){n.terminate(),u.splice(u.indexOf(n),1),u.length===0&&c(a);return}let{m:i,range:s}=e[o++],l=this.triangleData.slice(s.start*r,(s.start+s.count)*r),d=s.count,f=d<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:i,range:s},n.postMessage({triangleData:l.buffer,triangleByteOffset:l.byteOffset,triangleByteLength:l.byteLength,triangleCount:d,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:f,reinsertionOptimization:t.reinsertionOptimization},[l.buffer])},f=(e,t)=>{let r=t.data;if(r.error){u.forEach(e=>e.terminate()),l(Error(r.error));return}if(r.progress!==void 0)return;let{m:i,range:o}=e._currentTask;a.push({m:i,range:o,result:{bvhData:r.bvhData,reorderedTriangles:r.triangles||null,originalToBvh:r.originalToBvh||null}}),s++,n?.(s),d(e)};(async()=>{for(let e=0;e<i;e++){let e;try{e=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BarjE67Z.js`).href:new URL(`assets/BVHWorker-BarjE67Z.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(t){if(t.name!==`SecurityError`){l(t);return}e=await Ge(new URL(`data:text/javascript;base64,aW1wb3J0IHsgQlZIQnVpbGRlciB9IGZyb20gJy4uL0JWSEJ1aWxkZXIuanMnOwoKY29uc3QgRlBUID0gMzI7IC8vIEZMT0FUU19QRVJfVFJJQU5HTEUKCi8vIC0tLSBNZXNzYWdlIGRpc3BhdGNoZXIgLS0tCgpzZWxmLm9ubWVzc2FnZSA9IGZ1bmN0aW9uICggZSApIHsKCgljb25zdCBkYXRhID0gZS5kYXRhOwoJY29uc3QgdHlwZSA9IGRhdGEudHlwZTsKCglpZiAoIHR5cGUgPT09ICdidWlsZFBoYXNlMScgKSB7CgoJCWhhbmRsZVBoYXNlMSggZGF0YSApOwoKCX0gZWxzZSBpZiAoIHR5cGUgPT09ICdhc3NlbWJsZScgKSB7CgoJCWhhbmRsZUFzc2VtYmxlKCBkYXRhICk7CgoJfSBlbHNlIHsKCgkJLy8gTGVnYWN5OiBmdWxsIHNpbmdsZS13b3JrZXIgYnVpbGQgKGJhY2t3YXJkIGNvbXBhdGlibGUpCgkJaGFuZGxlRnVsbEJ1aWxkKCBkYXRhICk7CgoJfQoKfTsKCi8vIC0tLSBQaGFzZSAxOiBJbml0ICsgTW9ydG9uIHNvcnQgKyB0b3AtbGV2ZWwgU0FIIGJ1aWxkIC0tLQ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RyaWFuZ2xlRGF0YTsKCQkJY29uc3QgdHJpYW5nbGVDb3VudCA9IHJlb3JkZXJlZEZsb2F0MzJBcnJheS5ieXRlTGVuZ3RoIC8gKCAzMiAqIDQgKTsKCgkJCWNvbnN0IHRyYW5zZmVyYWJsZXMgPSBbIGJ2aERhdGEuYnVmZmVyLCByZW9yZGVyZWRGbG9hdDMyQXJyYXkuYnVmZmVyIF07CgkJCWlmICggb3JpZ2luYWxUb0J2aCApIHRyYW5zZmVyYWJsZXMucHVzaCggb3JpZ2luYWxUb0J2aC5idWZmZXIgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCWJ2aERhdGEsCgkJCQl0cmlhbmdsZXM6IHJlb3JkZXJlZEZsb2F0MzJBcnJheSwKCQkJCW9yaWdpbmFsVG9CdmgsCgkJCQl0cmlhbmdsZUNvdW50LAoJCQkJdHJlZWxldFN0YXRzOiBidWlsZGVyLnNwbGl0U3RhdHMKCQkJfSwgdHJhbnNmZXJhYmxlcyApOwoKCQl9CgoJfSBjYXRjaCAoIGVycm9yICkgewoKCQljb25zb2xlLmVycm9yKCAnW0JWSFdvcmtlcl0gRXJyb3I6JywgZXJyb3IgKTsKCQlzZWxmLnBvc3RNZXNzYWdlKCB7IGVycm9yOiBlcnJvci5tZXNzYWdlIH0gKTsKCgl9Cgp9Cg==`,``+{}.url))}e.onmessage=t=>f(e,t),e.onerror=e=>{u.forEach(e=>e.terminate()),l(e)},u.push(e),d(e)}})().catch(l)})}_buildGlobalOriginalToBvhMap(){this.originalToBvhMap=new Uint32Array(this.triangleCount);for(let e of this.instanceTable.entries){if(!e)continue;let t=new Uint32Array(e.triCount);if(e.originalToBvhMap)for(let n=0;n<e.triCount;n++){let r=e.originalToBvhMap[n];this.originalToBvhMap[e.triOffset+n]=e.triOffset+r,t[r]=n}else for(let n=0;n<e.triCount;n++)this.originalToBvhMap[e.triOffset+n]=e.triOffset+n,t[n]=n;e.bvhToOriginal=t}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let e=[{data:this.maps,prop:`albedoTextures`},{data:this.normalMaps,prop:`normalTextures`},{data:this.bumpMaps,prop:`bumpTextures`},{data:this.roughnessMaps,prop:`roughnessTextures`},{data:this.metalnessMaps,prop:`metalnessTextures`},{data:this.emissiveMaps,prop:`emissiveTextures`},{data:this.displacementMaps,prop:`displacementTextures`}];await Promise.all(e.filter(({data:e})=>e?.length>0).map(({data:e,prop:t})=>this.textureCreator.createTexturesToDataTexture(e).then(e=>{this[t]=e}))),this._log(`Material textures complete`,{materialData:!!this.materialData})}catch(e){throw console.error(`[SceneProcessor] Texture creation error:`,e),e}}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangleData,this.materials,this.triangleCount),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this.triangleData=null,this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvhData=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}_disposeTextures(){[`albedoTextures`,`normalTextures`,`bumpTextures`,`roughnessTextures`,`metalnessTextures`,`emissiveTextures`,`displacementTextures`].forEach(e=>{this[e]&&(typeof this[e].dispose==`function`&&this[e].dispose(),this[e]=null)})}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.materialCount=this.materials.length,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.sceneFeatures=n.sceneFeatures;let r={materials:this.materials,triangles:this.triangleData,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,displacementMaps:this.displacementMaps,bvhRoot:this.bvhRoot},i=await this.textureCreator.createMaterialTextures(r);this.materialData=this.textureCreator.createMaterialRawData(this.materials),this.albedoTextures=i.albedoTexture,this.normalTextures=i.normalTexture,this.bumpTextures=i.bumpTexture,this.roughnessTextures=i.roughnessTexture,this.metalnessTextures=i.metalnessTexture,this.emissiveTextures=i.emissiveTexture,this.displacementTextures=i.displacementTexture;let a=performance.now()-t;return this._log(`Material rebuild complete (${a.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw console.error(`[SceneProcessor] Material rebuild error:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){[`albedoTextures`,`normalTextures`,`bumpTextures`,`roughnessTextures`,`metalnessTextures`,`emissiveTextures`,`displacementTextures`].forEach(e=>{if(this[e])try{typeof this[e].dispose==`function`&&this[e].dispose()}catch(t){console.warn(`[SceneProcessor] Error disposing ${e}:`,t)}finally{this[e]=null}}),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvhData,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangleData?(this.triangleData.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement})),this._log(`Configuration updated`,this.config)}async refitBVH(e,t){if(!this.bvhData||!this.triangleData||!this.originalToBvhMap)throw Error(`No BVH data available for refit. Run buildBVH() first.`);if(!this._refitWorker)try{this._refitWorker=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHRefitWorker-GkmNJYvb.js`).href:new URL(`assets/BVHRefitWorker-GkmNJYvb.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;this._refitWorker=await Ge(new URL(`data:text/javascript;base64,LyoqCiAqIEJW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ZS5kYXRhLmJ2aFRvT3JpZ2luYWw7IC8vIHRyYW5zZmVycmVkIFVpbnQzMkFycmF5CgkJbm9kZUNvdW50ID0gYnZoRGF0YS5sZW5ndGggLyBGTE9BVFNfUEVSX05PREU7CgkJcmV0dXJuOwoKCX0KCglpZiAoIHR5cGUgPT09ICdyZWZpdCcgKSB7CgoJCXRyeSB7CgoJCQljb25zdCBzdGFydFRpbWUgPSBwZXJmb3JtYW5jZS5ub3coKTsKCgkJCXJlZml0dGVyLnVwZGF0ZVRyaWFuZ2xlUG9zaXRpb25zKCB0cmlEYXRhLCBwb3NEYXRhLCBidmhUb09yaWdpbmFsICk7CgkJCXJlZml0dGVyLnJlZml0KCBidmhEYXRhLCB0cmlEYXRhLCBub2RlQ291bnQgKTsKCgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsKCQkJCXR5cGU6ICdyZWZpdENvbXBsZXRlJywKCQkJCXJlZml0VGltZU1zOiBwZXJmb3JtYW5jZS5ub3coKSAtIHN0YXJ0VGltZQoJCQl9ICk7CgoJCX0gY2F0Y2ggKCBlcnJvciApIHsKCgkJCWNvbnNvbGUuZXJyb3IoICdbQlZIUmVmaXRXb3JrZXJdIFJlZml0IGVycm9yOicsIGVycm9yICk7CgkJCXNlbGYucG9zdE1lc3NhZ2UoIHsgdHlwZTogJ2Vycm9yJywgZXJyb3I6IGVycm9yLm1lc3NhZ2UgfSApOwoKCQl9CgoJfQoKfTsK`,``+{}.url))}if(!this._refitSharedBuffers){let t=new SharedArrayBuffer(this.bvhData.byteLength),n=new SharedArrayBuffer(this.triangleData.byteLength),r=new SharedArrayBuffer(e.byteLength),i=new Float32Array(t),a=new Float32Array(n);i.set(this.bvhData),a.set(this.triangleData),this.bvhData=i,this.triangleData=a;let o=this.originalToBvhMap.length,s=new Uint32Array(o);for(let e=0;e<o;e++)s[this.originalToBvhMap[e]]=e;this._refitSharedBuffers={bvhBuf:t,triBuf:n,posBuf:r,posView:new Float32Array(r)},this._refitWorker.postMessage({type:`init`,sharedBvhBuf:t,sharedTriBuf:n,sharedPosBuf:r,bvhToOriginal:s},[s.buffer])}return this._refitSharedBuffers.posView.set(e),new Promise((e,n)=>{this._refitWorker.onmessage=r=>{let i=r.data;i.type===`refitComplete`?(t&&this._patchSmoothNormals(t),e({refitTimeMs:i.refitTimeMs})):i.type===`error`&&n(Error(i.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){this._patchNormalsRange(e,0,this.originalToBvhMap.length)}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvhData||!this.triangleData)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=performance.now();this._blasRefitter||=new xa;for(let r of e){let e=this.instanceTable.entries[r];e&&(this._updateMeshTrianglePositions(e,t),n&&this._patchMeshSmoothNormals(e,n),this._blasRefitter.refitRange(this.bvhData,this.triangleData,e.blasOffset,e.blasNodeCount),this.instanceTable.recomputeAABB(r,this.bvhData,this.triangleData))}return this._refitTLAS(),{refitTimeMs:performance.now()-r}}computeBLASDirtyRanges(e){let t=H.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable.entries[i];e&&(n.push({offset:e.triOffset*t,count:e.triCount*t}),r.push({offset:e.blasOffset*16,count:e.blasNodeCount*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangleData?(e.setTriangleData(this.triangleData,this.triangleCount),this.bvhData?(e.setBVHData(this.bvhData),this.materialData?e.materialData.setMaterialData(this.materialData):console.warn(`SceneProcessor: No material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({albedoMaps:this.albedoTextures,normalMaps:this.normalTextures,bumpMaps:this.bumpTextures,roughnessMaps:this.roughnessTextures,metalnessMaps:this.metalnessTextures,emissiveMaps:this.emissiveTextures,displacementMaps:this.displacementTextures}),this.emissiveTriangleData&&e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n),!0):(console.error(`SceneProcessor: Failed to get BVH data`),!1)):(console.error(`SceneProcessor: Failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangleData,this.materials,this.triangleCount))?null:{rawData:this.emissiveTriangleBuilder.createEmissiveRawData(),emissiveCount:this.emissiveTriangleBuilder.emissiveCount,totalPower:this.emissiveTriangleBuilder.totalEmissivePower}}_updateMeshTrianglePositions(e,t){let n=H.FLOATS_PER_TRIANGLE,r=H.POSITION_A_OFFSET,i=H.POSITION_B_OFFSET,a=H.POSITION_C_OFFSET,o=H.NORMAL_A_OFFSET,s=H.NORMAL_B_OFFSET,c=H.NORMAL_C_OFFSET,l=e.bvhToOriginal;for(let u=0;u<e.triCount;u++){let d=l[u],f=(e.triOffset+u)*n,p=(e.triOffset+d)*9,m=t[p],h=t[p+1],g=t[p+2],_=t[p+3],v=t[p+4],y=t[p+5],b=t[p+6],x=t[p+7],S=t[p+8];this.triangleData[f+r]=m,this.triangleData[f+r+1]=h,this.triangleData[f+r+2]=g,this.triangleData[f+i]=_,this.triangleData[f+i+1]=v,this.triangleData[f+i+2]=y,this.triangleData[f+a]=b,this.triangleData[f+a+1]=x,this.triangleData[f+a+2]=S;let C=_-m,w=v-h,T=y-g,E=b-m,D=x-h,O=S-g,k=w*O-T*D,A=T*E-C*O,j=C*D-w*E;this.triangleData[f+o]=k,this.triangleData[f+o+1]=A,this.triangleData[f+o+2]=j,this.triangleData[f+s]=k,this.triangleData[f+s+1]=A,this.triangleData[f+s+2]=j,this.triangleData[f+c]=k,this.triangleData[f+c+1]=A,this.triangleData[f+c+2]=j}}_patchMeshSmoothNormals(e,t){this._patchNormalsRange(t,e.triOffset,e.triCount)}_patchNormalsRange(e,t,n){let r=H.FLOATS_PER_TRIANGLE,i=H.NORMAL_A_OFFSET,a=H.NORMAL_B_OFFSET,o=H.NORMAL_C_OFFSET;for(let s=0;s<n;s++){let n=t+s,c=this.originalToBvhMap[n]*r,l=n*9;this.triangleData[c+i]=e[l],this.triangleData[c+i+1]=e[l+1],this.triangleData[c+i+2]=e[l+2],this.triangleData[c+a]=e[l+3],this.triangleData[c+a+1]=e[l+4],this.triangleData[c+a+2]=e[l+5],this.triangleData[c+o]=e[l+6],this.triangleData[c+o+1]=e[l+7],this.triangleData[c+o+2]=e[l+8]}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6)),this._blasOffsetMap||=new Map,this._blasOffsetMap.clear();for(let e of this.instanceTable.entries)e&&this._blasOffsetMap.set(e.blasOffset,e);for(let t=e-1;t>=0;t--){let e=t*16,n=this.bvhData[e+3];if(n===-2){let n=this.bvhData[e],r=this._blasOffsetMap.get(n);if(r&&r.worldAABB){let e=t*6;this._tlasBounds[e]=r.worldAABB.minX,this._tlasBounds[e+1]=r.worldAABB.minY,this._tlasBounds[e+2]=r.worldAABB.minZ,this._tlasBounds[e+3]=r.worldAABB.maxX,this._tlasBounds[e+4]=r.worldAABB.maxY,this._tlasBounds[e+5]=r.worldAABB.maxZ}}else if(n>=0){let n=this.bvhData[e+3],r=this.bvhData[e+7],i=n*6,a=r*6,o=this._tlasBounds;this.bvhData[e]=o[i],this.bvhData[e+1]=o[i+1],this.bvhData[e+2]=o[i+2],this.bvhData[e+4]=o[i+3],this.bvhData[e+5]=o[i+4],this.bvhData[e+6]=o[i+5],this.bvhData[e+8]=o[a],this.bvhData[e+9]=o[a+1],this.bvhData[e+10]=o[a+2],this.bvhData[e+12]=o[a+3],this.bvhData[e+13]=o[a+4],this.bvhData[e+14]=o[a+5];let s=t*6;o[s]=Math.min(o[i],o[a]),o[s+1]=Math.min(o[i+1],o[a+1]),o[s+2]=Math.min(o[i+2],o[a+2]),o[s+3]=Math.max(o[i+3],o[a+3]),o[s+4]=Math.max(o[i+4],o[a+4]),o[s+5]=Math.max(o[i+5],o[a+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangleData)return;let n=H.FLOATS_PER_TRIANGLE;this._rebuildGeneration++;let r=this._rebuildGeneration,i=(e,i,a)=>{let o=this.triangleData.slice(i.triOffset*n,(i.triOffset+i.triCount)*n);this._pendingRebuilds.set(e,a),a.onmessage=n=>{let o=n.data;if(a.terminate(),this._pendingRebuilds.delete(e),o.error){console.error(`Background BLAS rebuild error (mesh ${e}):`,o.error);return}r===this._rebuildGeneration&&this._swapBLAS(e,i,o,t)},a.onerror=t=>{console.error(`Background BLAS rebuild worker error (mesh ${e}):`,t),a.terminate(),this._pendingRebuilds.delete(e)};let s=i.triCount>500;a.postMessage({triangleData:o.buffer,triangleByteOffset:o.byteOffset,triangleByteLength:o.byteLength,triangleCount:i.triCount,depth:this.config.bvhDepth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:s,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[o.buffer])};for(let t of e){let e=this.instanceTable.entries[t];if(!e)continue;let n=this._pendingRebuilds.get(t);n&&n.terminate();let r;try{r=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/BVHWorker-BarjE67Z.js`).href:new URL(`assets/BVHWorker-BarjE67Z.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),i(t,e,r)}catch(n){if(n.name!==`SecurityError`)thro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IHJlb3JkZXJlZEZsb2F0MzJBcnJheSwKCQkJCW9yaWdpbmFsVG9CdmgsCgkJCQl0cmlhbmdsZUNvdW50LAoJCQkJdHJlZWxldFN0YXRzOiBidWlsZGVyLnNwbGl0U3RhdHMKCQkJfSwgdHJhbnNmZXJhYmxlcyApOwoKCQl9CgoJfSBjYXRjaCAoIGVycm9yICkgewoKCQljb25zb2xlLmVycm9yKCAnW0JWSFdvcmtlcl0gRXJyb3I6JywgZXJyb3IgKTsKCQlzZWxmLnBvc3RNZXNzYWdlKCB7IGVycm9yOiBlcnJvci5tZXNzYWdlIH0gKTsKCgl9Cgp9Cg==`,``+{}.url)).then(n=>i(t,e,n))}}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a!==t.blasNodeCount){console.warn(`Background rebuild: node count mismatch for mesh ${e} (${a} vs ${t.blasNodeCount}), skipping swap`);return}let o=t.blasOffset*16;this.bvhData.set(i,o),this._offsetBLASInPlace(o,a,t.blasOffset,t.triOffset);let s=H.FLOATS_PER_TRIANGLE,c=n.triangles;c&&this.triangleData.set(c,t.triOffset*s);let l=n.originalToBvh;if(l){for(let e=0;e<t.triCount;e++)this.originalToBvhMap[t.triOffset+e]=t.triOffset+l[e];let e=new Uint32Array(t.triCount);for(let n=0;n<t.triCount;n++)e[l[n]]=n;t.bvhToOriginal=e}this.instanceTable.recomputeAABB(e,this.bvhData,this.triangleData),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.()}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},Ua=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new n.Vector3);r=t.sub(i).normalize()}else r=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0;this.directionalLightCache.push({data:[r.x,r.y,r.z,e.color.r,e.color.g,e.color.b,e.intensity,a],importance:i,light:e})}addRectAreaLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=e.getWorldQuaternion(new n.Quaternion),i=e.getWorldScale(new n.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new n.Vector3(a,0,0).applyQuaternion(r),c=new n.Vector3(0,-o,0).applyQuaternion(r),l=this.calculateLightImportance(e,`area`);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,e.color.r,e.color.g,e.color.b,e.intensity],importance:l,light:e})}addPointLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=this.calculateLightImportance(e,`point`);this.pointLightCache.push({data:[t.x,t.y,t.z,e.color.r,e.color.g,e.color.b,e.intensity,e.distance||0,e.decay===void 0?2:e.decay],importance:r,light:e})}addSpotLight(e){if(e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new n.Vector3),r=(e.target?e.target.getWorldPosition(new n.Vector3):new n.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`);this.spotLightCache.push({data:[t.x,t.y,t.z,r.x,r.y,r.z,e.color.r,e.color.g,e.color.b,e.intensity,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/8),n=Math.floor(this.lightData.rectArea.length/13),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/14);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},Wa=`https://assets.rayzee.atulmourya.com/noise/simple_bluenoise.png`,Ga=4,Ka=class extends L{constructor(e,t,r,i={}){super(`PathTracer`,{...i,executionMode:I.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=r,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.tileManager=new ge(a,o,V.tiles),this.sdfs=new Ha,this.lightSerializer=new Ua,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Oe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Ae(0,0),this.uniforms=new He(a,o),this._defineUniformGetters(),this.materialData=new We(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.environment=new bt(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new la,this._initRenderingState(),this.setupBlueNoise(),this.tempVector2=new n.Vector2,this.lastCameraMatrix=new n.Matrix4,this.lastProjectionMatrix=new n.Matrix4,this.lastRenderMode=-1,this.tileCompletionFrame=0,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.adaptiveSamplingFrameToggle=!1,this.lastInteractionModeState=!1,this.cameraChanged=!1,this.tileChanged=!1,this.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.blueNoiseTexture=null,this.emissiveTriangleStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(4),4),this.emissiveTriangleStorageNode=(0,o.storage)(this.emissiveTriangleStorageAttr,`vec4`,1).toReadOnly(),this.lightBVHStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightBVHStorageNode=(0,o.storage)(this.lightBVHStorageAttr,`vec4`,1).toReadOnly(),this.meshVisibilityStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([1,0,0,0]),4),this.meshVisibilityStorageNode=(0,o.storage)(this.meshVisibilityStorageAttr,`vec4`,1).toReadOnly(),this.adaptiveSamplingTexture=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new _e(this.renderer,{uniforms:{maxBounceCount:{get value(){return e.maxBounces.value},set value(t){e.maxBounces.value=t}},numRaysPerPixel:{get value(){return e.samplesPerPixel.value},set value(t){e.samplesPerPixel.value=t}},useAdaptiveSampling:{get value(){return e.useAdaptiveSampling.value},set value(t){e.useAdaptiveSampling.value=t}},useEnvMapIS:{get value(){return e.useEnvMapIS.value},set value(t){e.useEnvMapIS.value=t}},enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},enableEmissiveTriangleSampling:{get value(){return e.enableEmissiveTriangleSampling.value},set value(t){e.enableEmissiveTriangleSampling.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:V.interactionModeEnabled,qualitySettings:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,enableEmissiveTriangleSampling:!1},onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupBlueNoise(){let e=new n.TextureLoader;e.setCrossOrigin(`anonymous`),e.load(Wa,e=>{e.minFilter=n.NearestFilter,e.magFilter=n.NearestFilter,e.wrapS=n.RepeatWrapping,e.wrapT=n.RepeatWrapping,e.type=n.FloatType,e.generateMipmaps=!1,this.blueNoiseTexture=e,j.value=e,console.log(`PathTracer: Blue noise loaded ${e.image.width}x${e.image.height}`)})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.materialData.injectMaterialFeatureDefines(),this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.materialData.setMaterialData(this.sdfs.materialData),this.totalTriangleCount.value=this.sdfs.triangleCount||0,this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};if(this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this.hasSun.value){let t=this.environment.envParams.skySunIntensity*950,n={intensity:t,color:{r:1,g:1,b:1},userData:{angle:this.sunAngularSize.value},updateMatrixWorld:()=>{},getWorldPosition:e=>{let t=this.sunDirection.value;return e.set(t.x,t.y,t.z).multiplyScalar(1e10)}};this.lightSerializer.addDirectionalLight(n),this.lightSerializer.preprocessLights(),this.lightSerializer.updateShaderUniforms(e),this.directionalLightsData=e.uniforms.directionalLights.value,console.log(`Sun added as directional light (intensity: ${t.toFixed(2)})`)}this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/8)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/13)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/14)):this.numSpotLights.value=0}reset(){this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.tileManager.spiralOrder=this.tileManager.generateSpiralOrder(this.tileManager.tiles),this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastRenderMode=-1,this.tileCompletionFrame=0,this.lastInteractionModeState=!1}setTileCount(e){this.tileManager.setTileCount(e),this.updateCompletionThreshold(),this.reset()}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.tileManager.setSize(e,t),this.createStorageTextures(e,t),this.shaderBuilder.setSize(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=e?1:0}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get tiles(){return this.tileManager.tiles}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}setTriangleData(e,n){if(!e)return;let r=e.length/4;this.triangleStorageNode?(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=r):(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode=(0,o.storage)(this.triangleStorageAttr,`vec4`,r).toReadOnly()),this.triangleCount=n,console.log(`PathTracer: ${this.triangleCount} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let n=e.length/4;this.bvhStorageNode?(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=n):(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode=(0,o.storage)(this.bvhStorageAttr,`vec4`,n).toReadOnly()),this.bvhNodeCount=Math.floor(n/Ga),console.log(`PathTracer: ${this.bvhNodeCount} BVH nodes (storage buffer)`)}setMeshVisibilityData(e){if(!e||e.length===0)return;let n=e.length,r=new Float32Array(n*4);for(let t=0;t<n;t++)r[t*4]=this._isWorldVisible(e[t])?1:0;this.meshVisibilityStorageAttr=new t.StorageInstancedBufferAttribute(r,4),this.meshVisibilityStorageNode.value=this.meshVisibilityStorageAttr,this.meshVisibilityStorageNode.bufferCount=n}updateMeshVisibility(e,t){this.meshVisibilityStorageAttr&&(this.meshVisibilityStorageAttr.array[e*4]=t?1:0,this.meshVisibilityStorageAttr.needsUpdate=!0)}updateAllMeshVisibility(){if(!this._meshRefs||!this.meshVisibilityStorageAttr)return;let e=this.meshVisibilityStorageAttr.array;for(let t=0;t<this._meshRefs.length;t++)e[t*4]=this._isWorldVisible(this._meshRefs[t])?1:0;this.meshVisibilityStorageAttr.needsUpdate=!0}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){this._updateStorageBuffer(this.triangleStorageAttr,e)}updateBVHData(e){this._updateStorageBuffer(this.bvhStorageAttr,e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0){this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0){this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){console.error(`PathTracer: Triangle data required`);return}if(!this.bvhStorageNode){console.error(`PathTracer: BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.setupCompute({stage:this,storageTextures:this.storageTextures}),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}render(e,t){if(!this.isReady)return;if(this.isComplete||this.frameCount>=this.completionThreshold){this.isComplete||=!0;return}if(this.performanceMonitor?.start(),e&&this.shaderBuilder.adaptiveSamplingTexNode){let t=e.getTexture(`adaptiveSampling:output`);t&&(this.shaderBuilder.adaptiveSamplingTexNode.value=t)}let n=this.frameCount,r=this.renderMode.value,i=null,a=null;r===1&&n===0&&(i=this.maxBounces.value,a=this.samplesPerPixel.value,this.maxBounces.value=1,this.samplesPerPixel.value=1),this._handleResize(),this.manageASVGFForRenderMode(r,n);let o=this.tileManager.handleTileRendering(this.renderer,r,n,null);if(e&&e.setState(`tileRenderingComplete`,o.isCompleteCycle),o.tileIndex>=0){let e=this.tileManager.calculateTileBounds(o.tileIndex,this.tileManager.tiles,this.width,this.height);this.emit(`tile:changed`,{tileIndex:o.tileIndex,tileBounds:e,renderMode:r}),this.tileChanged=!0}this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this._updateAccumulationUniforms(n,r),this.frame.value=n,this.shaderBuilder.forceCompile(this.renderer),o.tileIndex>=0&&o.tileBounds?this.shaderBuilder.setTileDispatch(o.tileBounds.x,o.tileBounds.y,o.tileBounds.width,o.tileBounds.height):this.shaderBuilder.setFullScreenDispatch();let s=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=s.color,this.shaderBuilder.prevNormalDepthTexNode.value=s.normalDepth,this.shaderBuilder.prevAlbedoTexNode.value=s.albedo),this.renderer.compute(this.shaderBuilder.computeNode),this.storageTextures.copyToReadTargets(this.renderer);let c=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,c),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),a!==null&&(this.samplesPerPixel.value=a),this.performanceMonitor?.end()}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.shaderBuilder.setSize(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e,t){let n=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=n,this.accumulationEnabled?n?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=De(e,t,this.tileManager.totalTilesCache,!1),this.hasPreviousAccumulated.value=e>0?1:0):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value),e.setState(`tiles`,this.tileManager.tiles)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){let e=this.renderMode.value,t=this.maxSamples.value;this.renderLimitMode===`time`?this.completionThreshold=1/0:this.completionThreshold=Ee(e,t,this.tileManager.totalTilesCache)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e,t){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this._onRenderModeChanged(this.pendingRenderMode)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay)),e===1?this._handleTiledASVGF(t):this._handleFullQuadASVGF()}_onRenderModeChanged(e){e===1?this.emit(`asvgf:updateParameters`,{enableDebug:!1,temporalAlpha:.15}):this.emit(`asvgf:updateParameters`,{temporalAlpha:.1}),this.emit(`asvgf:reset`)}_handleTiledASVGF(e){let t=e===0,n=(t?-1:(e-1)%this.tileManager.totalTilesCache)==this.tileManager.totalTilesCache-1;t?this.emit(`asvgf:setTemporal`,{enabled:!0}):n?(this.emit(`asvgf:setTemporal`,{enabled:!0}),this.tileCompletionFrame=e):this.emit(`asvgf:setTemporal`,{enabled:!1})}_handleFullQuadASVGF(){this.emit(`asvgf:setTemporal`,{enabled:!0})}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(e){this.blueNoiseTexture=e,e&&(j.value=e)}setEmissiveTriangleData(e,n,r=0){if(!e)return;let i=e.length/4;this.emissiveTriangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.emissiveTriangleStorageNode.value=this.emissiveTriangleStorageAttr,this.emissiveTriangleStorageNode.bufferCount=i,this.emissiveTriangleCount.value=n,this.emissiveTotalPower.value=r,console.log(`PathTracer: ${n} emissive triangles, totalPower=${r.toFixed(4)} (storage buffer)`)}setLightBVHData(e,n){if(!e)return;let r=e.length/4;this.lightBVHStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.lightBVHStorageNode.value=this.lightBVHStorageAttr,this.lightBVHStorageNode.bufferCount=r,this.lightBVHNodeCount.value=n,console.log(`PathTracer: Light BVH ${n} nodes`)}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{console.log(`PathTracer: Starting material rebuild...`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),console.log(`PathTracer materials rebuilt successfully`)}catch(e){console.error(`Error rebuilding PathTracer materials:`,e);try{console.warn(`Attempting recovery by resetting path tracer...`),this.reset()}catch(e){console.error(`Recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.tileManager?.dispose(),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.storageTextures?.dispose(),this.blueNoiseTexture?.dispose(),this.placeholderTexture?.dispose(),this.triangleStorageAttr=null,this.triangleStorageNode=null,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}},qa=class extends L{constructor(e,r={}){super(`NormalDepth`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.pathTracer=r.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,o.uniform)(new n.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,o.uniform)(new n.Matrix4,`mat4`),this.resolutionWidth=(0,o.uniform)(r.width||1),this.resolutionHeight=(0,o.uniform)(r.height||1);let i=r.width||1,a=r.height||1;this._outputStorageTex=new t.StorageTexture(i,a),this._outputStorageTex.type=n.HalfFloatType,this._outputStorageTex.format=n.RGBAFormat,this._outputStorageTex.minFilter=n.NearestFilter,this._outputStorageTex.magFilter=n.NearestFilter,this.renderTarget=new t.RenderTarget(i,a,{type:n.HalfFloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._computeNode=null,this._computeBuilt=!1}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;e.triangleStorageAttr&&!this._triStorageNode?this._triStorageNode=(0,o.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly():e.triangleStorageAttr&&this._triStorageNode&&(this._triStorageNode.value=e.triangleStorageAttr,this._triStorageNode.bufferCount=e.triangleStorageAttr.count),e.bvhStorageAttr&&!this._bvhStorageNode?this._bvhStorageNode=(0,o.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly():e.bvhStorageAttr&&this._bvhStorageNode&&(this._bvhStorageNode.value=e.bvhStorageAttr,this._bvhStorageNode.bufferCount=e.bvhStorageAttr.count);let t=e.materialData.materialStorageAttr;return t&&!this._matStorageNode?this._matStorageNode=(0,o.storage)(t,`vec4`,t.count).toReadOnly():t&&this._matStorageNode&&(this._matStorageNode.value=t,this._matStorageNode.bufferCount=t.count),!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,n=this._matStorageNode,r=this.cameraWorldMatrix,i=this.cameraProjectionMatrixInverse,a=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex;this._computeNode=(0,o.Fn)(([r,i])=>{let l=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),u=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(l.lessThan((0,o.int)(a)).and(u.lessThan((0,o.int)(s))),()=>{let d=(0,o.vec3)((0,o.float)(l).add(.5).div(a).mul(2).sub(1),(0,o.float)(u).add(.5).div(s).mul(2).sub(1).negate(),1),f=i.mul((0,o.vec4)(d,1)),p=(0,o.normalize)((0,o.mat3)(r[0].xyz,r[1].xyz,r[2].xyz).mul(f.xyz.div(f.w))),m=St({origin:(0,o.vec3)(r[3]),direction:p}),h=Tt.wrap(vn(m,t,e,n)),g=h.normal.mul(.5).add(.5),_=h.dst,v=h.didHit.select((0,o.vec4)(g,_),(0,o.vec4)(0,0,0,(0,o.float)(1e6)));(0,o.textureStore)(c,(0,o.uvec2)((0,o.uint)(l),(0,o.uint)(u)),v).toWriteOnly()})})(r,i).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._dirty&&this.renderTarget.texture){e.setTexture(`pathtracer:normalDepth`,this.renderTarget.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.renderTarget.width||e.height!==this.renderTarget.height)&&this.setSize(e.width,e.height)}this.renderer.compute(this._computeNode),this.renderer.copyTextureToTexture(this._outputStorageTex,this.renderTarget.texture),e.setTexture(`pathtracer:normalDepth`,this.renderTarget.texture),this._dirty=!1}reset(){this._dirty=!0}setSize(e,t){this._outputStorageTex.setSize(e,t),this.renderTarget.setSize(e,t),this.renderTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&this._computeNode.setCount([this._dispatchX,this._dispatchY,1]),this._dirty=!0}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this.renderTarget?.dispose()}},Ja=class extends L{constructor(e,r,i={}){super(`MotionVector`,{...i,executionMode:I.ALWAYS}),this.renderer=e,this.camera=r,this.pathTracer=i.pathTracer||null;let a=i.width||1,s=i.height||1;this.prevViewProjectionMatrix=new n.Matrix4,this.currentViewProjectionMatrix=new n.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,o.uniform)(new n.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,o.uniform)(new n.Matrix4,`mat4`),this.prevVP=(0,o.uniform)(new n.Matrix4,`mat4`),this.isFirstFrameU=(0,o.uniform)(1),this.deltaTime=(0,o.uniform)(1/60),this.velocityScale=(0,o.uniform)(1),this.resolutionWidth=(0,o.uniform)(a),this.resolutionHeight=(0,o.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(a,s),this._screenSpaceStorageTex.type=n.HalfFloatType,this._screenSpaceStorageTex.format=n.RGBAFormat,this._screenSpaceStorageTex.minFilter=n.NearestFilter,this._screenSpaceStorageTex.magFilter=n.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(a,s),this._worldSpaceStorageTex.type=n.HalfFloatType,this._worldSpaceStorageTex.format=n.RGBAFormat,this._worldSpaceStorageTex.minFilter=n.NearestFilter,this._worldSpaceStorageTex.magFilter=n.NearestFilter;let c={type:n.HalfFloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(a,s,c),this.worldSpaceTarget=new t.RenderTarget(a,s,c),this._dispatchX=Math.ceil(a/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,n=this.cameraProjectionMatrixInverse,r=this.prevVP,i=this.resolutionWidth,a=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,o.Fn)(([t,n])=>{let c=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),l=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(c.lessThan((0,o.int)(i)).and(l.lessThan((0,o.int)(a))),()=>{let u=(0,o.textureLoad)(e,(0,o.ivec2)(c,l)).w,d=(0,o.vec2)((0,o.float)(c).add(.5).div(i),(0,o.float)(l).add(.5).div(a)),f=(0,o.vec4)(0,0,u,1).toVar();(0,o.If)(u.lessThan((0,o.float)(1e5)),()=>{let e=(0,o.vec3)((0,o.float)(c).add(.5).div(i).mul(2).sub(1),(0,o.float)(l).add(.5).div(a).mul(2).sub(1).negate(),1),s=n.mul((0,o.vec4)(e,1)),p=(0,o.normalize)((0,o.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,o.vec3)(t[3]).add(p.mul(u)),h=r.mul((0,o.vec4)(m,1)),g=h.xy.div(h.w),_=(0,o.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,o.vec4)(v,u,1),(0,o.vec4)((0,o.float)(1e3),(0,o.float)(1e3),u,0)))}),(0,o.textureStore)(s,(0,o.uvec2)((0,o.uint)(c),(0,o.uint)(l)),f).toWriteOnly()})})(t,n).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,n=this.cameraProjectionMatrixInverse,r=this.prevVP,i=this.isFirstFrameU,a=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,o.Fn)(([t,n])=>{let d=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),f=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(d.lessThan((0,o.int)(c)).and(f.lessThan((0,o.int)(l))),()=>{let p=(0,o.textureLoad)(e,(0,o.ivec2)(d,f)).w,m=(0,o.vec4)(0,0,0,0).toVar();(0,o.If)(i.lessThan(.5).and(p.lessThan((0,o.float)(1e5))),()=>{let e=(0,o.vec3)((0,o.float)(d).add(.5).div(c).mul(2).sub(1),(0,o.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),i=n.mul((0,o.vec4)(e,1)),u=(0,o.normalize)((0,o.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(i.xyz.div(i.w))),h=(0,o.vec3)(t[3]).add(u.mul(p)),g=(0,o.vec2)((0,o.float)(d).add(.5).div(c),(0,o.float)(f).add(.5).div(l)),_=r.mul((0,o.vec4)(h,1)),v=_.xy.div(_.w),y=(0,o.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,o.vec3)(x.x.div(a).mul(s),x.y.div(a).mul(s),0);m.assign(b.select((0,o.vec4)(S,1),(0,o.vec4)(0,0,0,.5)))}),(0,o.textureStore)(u,(0,o.uvec2)((0,o.uint)(d),(0,o.uint)(f)),m).toWriteOnly()})})(t,n).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?1:0,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.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture),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}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this._screenSpaceStorageTex.setSize(e,t),this._worldSpaceStorageTex.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.setCount([this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&this._worldSpaceComputeNode.setCount([this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose()}};function Ya(e,t,n={}){let r=n.textureIndex||0,i=t.isTexture===!0,a;i?(console.warn(`RenderTargetHelper: Direct Texture input is not supported. Pass a RenderTarget instead.`),a=null):a=t;let o={width:n.width||200,height:n.height||200,position:n.position||`bottom-right`,flipX:n.flipX===void 0?!1:n.flipX,flipY:n.flipY===void 0?!1:n.flipY,autoUpdate:n.autoUpdate||!1,theme:n.theme||`dark`,title:n.title||a?.name||`Render Target`},s=document.createElement(`div`);s.className=`render-target-helper`;let c={"bottom-right":{bottom:`48px`,right:`10px`},"bottom-left":{bottom:`10px`,left:`10px`},"top-right":{top:`10px`,right:`10px`},"top-left":{top:`10px`,left:`10px`}},l={light:{backgroundColor:`white`,border:`1px solid #ddd`,color:`#333`},dark:{backgroundColor:`#1e293b`,border:`1px solid #334155`,color:`#f8fafc`}};Object.assign(s.style,{display:`flex`,flexDirection:`column`,position:`fixed`,resize:`both`,overflow:`hidden`,padding:`8px`,borderRadius:`4px`,boxShadow:`0 5px 15px rgba(0,0,0,0.3)`,transition:`opacity 0.2s ease`,zIndex:`1000`,minWidth:`100px`,minHeight:`100px`,maxWidth:`500px`,maxHeight:`500px`,width:`${o.width}px`,height:`${o.height}px`,...c[o.position],...l[o.theme]});let u=document.createElement(`div`);u.style.display=`flex`,u.style.justifyContent=`space-between`,u.style.alignItems=`center`,u.style.marginBottom=`4px`,u.style.cursor=`move`,u.style.userSelect=`none`;let d=document.createElement(`span`);d.textContent=o.title,d.style.fontSize=`12px`,d.style.fontFamily=`monospace`,d.style.color=l[o.theme].color;let f=document.createElement(`div`),p=document.createElement(`button`);p.innerHTML=`×`,p.style.background=`none`,p.style.border=`none`,p.style.cursor=`pointer`,p.style.fontSize=`16px`,p.style.color=l[o.theme].color,p.style.padding=`0 4px`,p.title=`Close`,p.onclick=()=>{s.style.display=`none`,o.autoUpdate&&(cancelAnimationFrame(O),O=null)};let m=document.createElement(`button`);m.innerHTML=`⟳`,m.style.background=`none`,m.style.border=`none`,m.style.cursor=`pointer`,m.style.fontSize=`14px`,m.style.color=l[o.theme].color,m.style.padding=`0 4px`,m.title=`Refresh`,m.onclick=()=>{s.update()},f.appendChild(m),f.appendChild(p),u.appendChild(d),u.appendChild(f),s.appendChild(u);let h=document.createElement(`canvas`);h.style.width=`100%`,h.style.height=`calc(100% - 20px)`;let g=``;o.flipX&&(g+=`scaleX(-1) `),o.flipY&&(g+=`scaleY(-1) `),h.style.transform=g.trim(),s.appendChild(h);let _=a?a.width:1,v=a?a.height:1;h.width=_,h.height=v;let y=h.getContext(`2d`),b=new Uint8ClampedArray(4*_*v),x=!1,S=!1,C=0,w=0;u.addEventListener(`pointerdown`,e=>{S=!0,C=e.clientX-s.offsetLeft,w=e.clientY-s.offsetTop,document.body.style.userSelect=`none`}),window.addEventListener(`pointermove`,e=>{if(!S)return;let t=e.clientX-C,n=e.clientY-w,r=window.innerWidth-s.offsetWidth,i=window.innerHeight-s.offsetHeight;s.style.left=`${Math.max(0,Math.min(t,r))}px`,s.style.top=`${Math.max(0,Math.min(n,i))}px`,s.style.bottom=`auto`,s.style.right=`auto`}),window.addEventListener(`pointerup`,()=>{S=!1,document.body.style.userSelect=``});function T(){if(!a)return;let e=a.width,t=a.height;(_!==e||v!==t)&&(_=e,v=t,h.width=_,h.height=v,b=new Uint8ClampedArray(4*_*v)),d.textContent=`${o.title} (${_}×${v})`}function E(e){let t=(e&32768)>>15,n=(e&31744)>>10,r=e&1023;return n===0?(t?-1:1)*2**-14*(r/1024):n===31?r?NaN:t?-1/0:1/0:(t?-1:1)*2**(n-15)*(1+r/1024)}function D(e){let t=Math.min(e.length,b.length);if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)b.set(e.subarray(0,t));else if(e instanceof Uint16Array)for(let n=0;n<t;n++){let t=E(e[n]);b[n]=Math.min(255,Math.max(0,(t||0)*255))}else for(let n=0;n<t;n++)b[n]=Math.min(255,Math.max(0,e[n]*255));if(_===0||v===0)return;let n=new ImageData(b,_,v);y.putImageData(n,0,0)}s.update=function(){if(a){T();try{if(x)return;x=!0,e.readRenderTargetPixelsAsync(a,0,0,_,v,r).then(e=>{x=!1,D(e)}).catch(e=>{x=!1,console.error(`RenderTargetHelper: readback error:`,e)})}catch(e){console.error(`Error updating render target helper:`,e)}}},s.addEventListener(`mousedown`,()=>{window.addEventListener(`mousemove`,T)}),window.addEventListener(`mouseup`,()=>{window.removeEventListener(`mousemove`,T)}),window.addEventListener(`resize`,T);let O=null;return s.show=function(){s.style.display=`flex`,o.autoUpdate&&!O&&s.startAutoUpdate()},s.hide=function(){s.style.display=`none`,o.autoUpdate&&O&&(cancelAnimationFrame(O),O=null)},s.toggle=function(){return s.style.display===`none`?s.show():s.hide(),s.style.display!==`none`},s.startAutoUpdate=function(){if(O)return;let e=()=>{s.update(),O=requestAnimationFrame(e)};O=requestAnimationFrame(e)},s.stopAutoUpdate=function(){O&&=(cancelAnimationFrame(O),null)},s.dispose=function(){o.autoUpdate&&O&&cancelAnimationFrame(O),s.parentNode&&s.parentNode.removeChild(s),b=null},o.autoUpdate&&s.startAutoUpdate(),s.style.display===`none`&&(s.style.display=`flex`),s}var Xa=class extends L{constructor(e,r={}){super(`ASVGF`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.debugContainer=r.debugContainer||null,this.temporalAlpha=(0,o.uniform)(r.temporalAlpha??.1),this.gradientScale=(0,o.uniform)(r.gradientScale??2),this.gradientMin=(0,o.uniform)(r.gradientMin??.01),this.gradientMax=(0,o.uniform)(r.gradientMax??.5),this.phiColor=(0,o.uniform)(r.phiColor??10),this.phiNormal=(0,o.uniform)(r.phiNormal??128),this.phiDepth=(0,o.uniform)(r.phiDepth??1),this.maxAccumFrames=(0,o.uniform)(r.maxAccumFrames??32),this.varianceClip=(0,o.uniform)(r.varianceClip??1),this.resW=(0,o.uniform)(r.width||1),this.resH=(0,o.uniform)(r.height||1),this.temporalEnabled=!0,this.temporalEnabledU=(0,o.uniform)(1),this._colorTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._readPrevNDTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let i=r.width||1,a=r.height||1;this._temporalTexA=new t.StorageTexture(i,a),this._temporalTexA.type=n.HalfFloatType,this._temporalTexA.format=n.RGBAFormat,this._temporalTexA.minFilter=n.LinearFilter,this._temporalTexA.magFilter=n.LinearFilter,this._temporalTexB=new t.StorageTexture(i,a),this._temporalTexB.type=n.HalfFloatType,this._temporalTexB.format=n.RGBAFormat,this._temporalTexB.minFilter=n.LinearFilter,this._temporalTexB.magFilter=n.LinearFilter,this._prevNDTexA=new t.StorageTexture(i,a),this._prevNDTexA.type=n.HalfFloatType,this._prevNDTexA.format=n.RGBAFormat,this._prevNDTexA.minFilter=n.LinearFilter,this._prevNDTexA.magFilter=n.LinearFilter,this._prevNDTexB=new t.StorageTexture(i,a),this._prevNDTexB.type=n.HalfFloatType,this._prevNDTexB.format=n.RGBAFormat,this._prevNDTexB.minFilter=n.LinearFilter,this._prevNDTexB.magFilter=n.LinearFilter,this._gradientStorageTex=new t.StorageTexture(i,a),this._gradientStorageTex.type=n.HalfFloatType,this._gradientStorageTex.format=n.RGBAFormat,this._gradientStorageTex.minFilter=n.LinearFilter,this._gradientStorageTex.magFilter=n.LinearFilter,this.currentMoments=0,this._compiled=!1,this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,o.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(i,a),this._heatmapStorageTex.type=n.FloatType,this._heatmapStorageTex.format=n.RGBAFormat,this._heatmapStorageTex.minFilter=n.NearestFilter,this._heatmapStorageTex.magFilter=n.NearestFilter,this.heatmapTarget=new t.RenderTarget(i,a,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.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(),this.heatmapHelper=Ya(this.renderer,this.heatmapTarget,{width:400,height:400,position:`bottom-right`,theme:`dark`,title:`ASVGF Debug`,autoUpdate:!1}),this.heatmapHelper.hide(),(this.debugContainer||document.body).appendChild(this.heatmapHelper),this.frameCount=0}_buildGradientCompute(){let e=this._colorTexNode,t=this._motionTexNode,n=this._readTemporalTexNode,r=this._gradientStorageTex,i=this.resW,a=this.resH,s=(0,o.workgroupArray)(`float`,100);this._gradientNode=(0,o.Fn)(()=>{let c=o.localId.x,l=o.localId.y,u=l.mul(8).add(c),d=(0,o.int)(o.workgroupId.x).mul(8).sub(1),f=(0,o.int)(o.workgroupId.y).mul(8).sub(1),p=u.mod(10),m=u.div(10),h=(0,o.textureLoad)(e,(0,o.ivec2)(d.add((0,o.int)(p)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),f.add((0,o.int)(m)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz;s.element(u).assign(qt(h)),(0,o.If)(u.lessThan((0,o.uint)(36)),()=>{let t=u.add((0,o.uint)(64)),n=t.mod(10),r=t.div(10),c=(0,o.textureLoad)(e,(0,o.ivec2)(d.add((0,o.int)(n)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),f.add((0,o.int)(r)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz;s.element(t).assign(qt(c))}),(0,o.workgroupBarrier)();let g=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(c)),_=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(l));(0,o.If)(g.lessThan((0,o.int)(i)).and(_.lessThan((0,o.int)(a))),()=>{let e=(0,o.float)(-1).toVar(),u=(0,o.int)(0).toVar(),d=(0,o.int)(0).toVar();for(let t=-1;t<=1;t++)for(let n=-1;n<=1;n++){let r=s.element(l.add(1+t).mul(10).add(c.add(1+n)));(0,o.If)(r.greaterThan(e),()=>{e.assign(r),u.assign((0,o.int)(n)),d.assign((0,o.int)(t))})}let f=g.add(u).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),p=_.add(d).clamp((0,o.int)(0),(0,o.int)(a).sub(1)),m=(0,o.textureLoad)(t,(0,o.ivec2)(f,p)),h=(0,o.float)(f).sub(m.x.mul(i)),v=(0,o.float)(p).sub(m.y.mul(a)),y=(0,o.textureLoad)(n,(0,o.ivec2)((0,o.int)(h).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),(0,o.int)(v).clamp((0,o.int)(0),(0,o.int)(a).sub(1)))).xyz,b=qt(y),x=(0,o.abs)(e.sub(b)).div((0,o.max)(e,(0,o.float)(.001))).clamp(0,1);(0,o.textureStore)(r,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),(0,o.vec4)(x,e,b,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA,this._prevNDTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB,this._prevNDTexB)}_buildTemporalForDirection(e,t){let n=this._colorTexNode,r=this._normalDepthTexNode,i=this._motionTexNode,a=this._readTemporalTexNode,s=this._readPrevNDTexNode;this._gradientReadTexNode;let c=this.temporalAlpha;this.gradientScale,this.gradientMin,this.gradientMax;let l=this.phiNormal,u=this.phiDepth,d=this.maxAccumFrames,f=this.varianceClip,p=this.temporalEnabledU,m=this.resW,h=this.resH;return(0,o.Fn)(()=>{let g=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),_=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(g.lessThan((0,o.int)(m)).and(_.lessThan((0,o.int)(h))),()=>{let v=(0,o.ivec2)(g,_),y=(0,o.textureLoad)(n,v).xyz,b=(0,o.textureLoad)(r,v),x=(0,o.vec4)(y,1).toVar();(0,o.If)(p.greaterThan(.5),()=>{let e=(0,o.textureLoad)(i,v),t=e.w.greaterThan(.5),r=(0,o.float)(g).sub(e.x.mul(m)),p=(0,o.float)(_).sub(e.y.mul(h)),S=r.greaterThanEqual(0).and(r.lessThan((0,o.float)(m))).and(p.greaterThanEqual(0)).and(p.lessThan((0,o.float)(h)));(0,o.If)(t.and(S),()=>{let e=(0,o.ivec2)((0,o.int)(r).clamp((0,o.int)(0),(0,o.int)(m).sub(1)),(0,o.int)(p).clamp((0,o.int)(0),(0,o.int)(h).sub(1))),t=b.xyz.mul(2).sub(1),i=(0,o.textureLoad)(s,e);on(t,i.xyz.mul(2).sub(1),b.w,i.w,l,u);let v=(0,o.textureLoad)(a,e),S=v.xyz,C=v.w,w=C.div(d).clamp(0,1),T=(0,o.vec3)(1e10).toVar(),E=(0,o.vec3)(-1e10).toVar(),D=(0,o.vec3)(0).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){let r=(0,o.textureLoad)(n,(0,o.ivec2)(g.add(t).clamp((0,o.int)(0),(0,o.int)(m).sub(1)),_.add(e).clamp((0,o.int)(0),(0,o.int)(h).sub(1)))).xyz;T.assign((0,o.min)(T,r)),E.assign((0,o.max)(E,r)),D.addAssign(r)}D.divAssign(9);let O=(0,o.float)(1).add(w.mul(3)),k=E.sub(T).mul(f).mul(O),A=T.sub(k),j=E.add(k),M=(0,o.mix)(S.clamp(A,j),y,(0,o.max)((0,o.float)(1).div(C.add(1)),c)),N=(0,o.min)(C.add(1),d);x.assign((0,o.vec4)(M,N))}).Else(()=>{x.assign((0,o.vec4)(y,1))})}),(0,o.textureStore)(e,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),x).toWriteOnly(),(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(g),(0,o.uint)(_)),b).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,n=this._heatmapTemporalTexNode,r=this._heatmapNDTexNode,i=this._heatmapMotionTexNode,a=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,o.Fn)(()=>{let d=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),f=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(d.lessThan((0,o.int)(l)).and(f.lessThan((0,o.int)(u))),()=>{let p=(0,o.ivec2)(d,f),m=(0,o.vec4)(0,0,0,1).toVar();(0,o.If)(c.equal((0,o.int)(0)),()=>{let e=(0,o.textureLoad)(t,p).xyz;m.assign((0,o.vec4)(e,1))}).ElseIf(c.equal((0,o.int)(1)),()=>{let t=(0,o.float)(0).toVar(),n=(0,o.float)(0).toVar();for(let r=-1;r<=1;r++)for(let i=-1;i<=1;i++){let a=(0,o.textureLoad)(e,(0,o.ivec2)(d.add(i).clamp((0,o.int)(0),(0,o.int)(l).sub(1)),f.add(r).clamp((0,o.int)(0),(0,o.int)(u).sub(1)))).xyz,s=(0,o.dot)(a,(0,o.vec3)(.2126,.7152,.0722));t.addAssign(s),n.addAssign(s.mul(s))}t.divAssign(9),n.divAssign(9);let r=(0,o.max)(n.sub(t.mul(t)),(0,o.float)(0)).div((0,o.max)(t.mul(t),(0,o.float)(1e-4))).mul(10).clamp(0,1),i=r.sub(.5).mul(4).clamp(0,1),a=r.mul(4).clamp(0,1).sub(r.sub(.75).mul(4).clamp(0,1)),s=(0,o.float)(1).sub(r.sub(.25).mul(4).clamp(0,1));m.assign((0,o.vec4)(i,a,s,1))}).ElseIf(c.equal((0,o.int)(2)),()=>{let e=(0,o.textureLoad)(n,p).w.div(32).clamp(0,1);m.assign((0,o.vec4)((0,o.float)(1).sub(e),e,(0,o.float)(.2),1))}).ElseIf(c.equal((0,o.int)(3)),()=>{let e=(0,o.textureLoad)(i,p),t=(0,o.abs)(e.x).mul(100).clamp(0,1),n=(0,o.abs)(e.y).mul(100).clamp(0,1),r=t.add(n).clamp(0,1);m.assign((0,o.vec4)(t,n,r.mul(.3),1))}).ElseIf(c.equal((0,o.int)(4)),()=>{let e=(0,o.textureLoad)(r,p);m.assign((0,o.vec4)(e.xyz,1))}).Else(()=>{let e=(0,o.textureLoad)(a,p).x.mul(5).clamp(0,1);m.assign((0,o.vec4)(e,e.mul(.5),(0,o.float)(1).sub(e),1))}),(0,o.textureStore)(s,(0,o.uvec2)((0,o.uint)(d),(0,o.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:setTemporal`,e=>{e&&e.enabled!==void 0&&(this.temporalEnabled=e.enabled,this.temporalEnabledU.value=e.enabled?1:0)}),this.on(`asvgf:updateParameters`,e=>{e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientScale!==void 0&&(this.gradientScale.value=e.gradientScale),e.phiColor!==void 0&&(this.phiColor.value=e.phiColor),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth))})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:normalDepth`),r=e.getTexture(`motionVector:screenSpace`);if(!t)return;let i=t.image;i&&i.width>0&&i.height>0&&(i.width!==this._temporalTexA.image.width||i.height!==this._temporalTexA.image.height)&&this.setSize(i.width,i.height),this._colorTexNode.value=t,n&&(this._normalDepthTexNode.value=n),r&&(this._motionTexNode.value=r),this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0);let a=this.currentMoments===0?this._temporalTexB:this._temporalTexA,o=this.currentMoments===0?this._prevNDTexB:this._prevNDTexA,s=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,c=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._readTemporalTexNode.value=a,this.renderer.compute(this._gradientNode),this._gradientReadTexNode.value=this._gradientStorageTex,this._readPrevNDTexNode.value=o,this.renderer.compute(s),e.setTexture(`asvgf:output`,c),e.setTexture(`asvgf:temporalColor`,c),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=c,this._heatmapTemporalTexNode.value=c,n&&(this._heatmapNDTexNode.value=n),r&&(this._heatmapMotionTexNode.value=r),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture),this.heatmapHelper.update()),this.frameCount++}toggleHeatmap(e){this.showHeatmap=e,e?this.heatmapHelper.show():this.heatmapHelper.hide()}setTemporalEnabled(e){this.temporalEnabled=e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientScale!==void 0&&(this.gradientScale.value=e.gradientScale),e.phiColor!==void 0&&(this.phiColor.value=e.phiColor),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.frameCount=0,this.currentMoments=0}setSize(e,t){this._temporalTexA.setSize(e,t),this._temporalTexB.setSize(e,t),this._prevNDTexA.setSize(e,t),this._prevNDTexB.setSize(e,t),this._gradientStorageTex.setSize(e,t),this._heatmapStorageTex.setSize(e,t),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.setCount([this._dispatchX,this._dispatchY,1]),this._temporalNodeA.setCount([this._dispatchX,this._dispatchY,1]),this._temporalNodeB.setCount([this._dispatchX,this._dispatchY,1]),this._heatmapComputeNode.setCount([this._dispatchX,this._dispatchY,1])}reset(){}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._prevNDTexA?.dispose(),this._prevNDTexB?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this.heatmapHelper?.dispose()}},Za=(0,o.wgslFn)(`
|
|
532
532
|
fn temporalAccumulate(
|
|
533
533
|
lum: f32,
|
|
534
534
|
prevMean: f32,
|
|
@@ -550,7 +550,7 @@
|
|
|
550
550
|
);
|
|
551
551
|
|
|
552
552
|
}
|
|
553
|
-
`),
|
|
553
|
+
`),Qa=class extends L{constructor(e,r={}){super(`VarianceEstimation`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.inputTextureName=r.inputTextureName||`pathtracer:color`,this.varianceBoost=(0,o.uniform)(r.varianceBoost??1),this.temporalAlpha=(0,o.uniform)(r.temporalAlpha??.1),this.resW=(0,o.uniform)(r.width||1),this.resH=(0,o.uniform)(r.height||1),this._colorTexNode=new t.TextureNode;let i=r.width||1,a=r.height||1;this._storageTexA=new t.StorageTexture(i,a),this._storageTexA.type=n.FloatType,this._storageTexA.format=n.RGBAFormat,this._storageTexA.minFilter=n.LinearFilter,this._storageTexA.magFilter=n.LinearFilter,this._storageTexB=new t.StorageTexture(i,a),this._storageTexB.type=n.FloatType,this._storageTexB.format=n.RGBAFormat,this._storageTexB.minFilter=n.LinearFilter,this._storageTexB.magFilter=n.LinearFilter,this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._buildCompute()}setupEventListeners(){this.on(`pathtracer:viewpointChanged`,()=>this.reset())}_buildCompute(){this._readTexNodeA=new t.TextureNode,this._readTexNodeB=new t.TextureNode,this._computeNodeA=this._buildComputeForDirection(this._storageTexA,this._readTexNodeB),this._computeNodeB=this._buildComputeForDirection(this._storageTexB,this._readTexNodeA)}_buildComputeForDirection(e,t){let n=this._colorTexNode,r=this.temporalAlpha,i=this.varianceBoost,a=this.resW,s=this.resH,c=(0,o.workgroupArray)(`float`,100);return(0,o.Fn)(()=>{let l=o.localId.x,u=o.localId.y,d=u.mul(8).add(l),f=(0,o.int)(o.workgroupId.x).mul(8).sub(1),p=(0,o.int)(o.workgroupId.y).mul(8).sub(1),m=d.mod(10),h=d.div(10),g=(0,o.textureLoad)(n,(0,o.ivec2)(f.add((0,o.int)(m)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)),p.add((0,o.int)(h)).clamp((0,o.int)(0),(0,o.int)(s).sub(1)))).xyz;c.element(d).assign(qt(g)),(0,o.If)(d.lessThan((0,o.uint)(36)),()=>{let e=d.add((0,o.uint)(64)),t=e.mod(10),r=e.div(10),i=(0,o.textureLoad)(n,(0,o.ivec2)(f.add((0,o.int)(t)).clamp((0,o.int)(0),(0,o.int)(a).sub(1)),p.add((0,o.int)(r)).clamp((0,o.int)(0),(0,o.int)(s).sub(1)))).xyz;c.element(e).assign(qt(i))}),(0,o.workgroupBarrier)();let _=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(l)),v=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(u));(0,o.If)(_.lessThan((0,o.int)(a)).and(v.lessThan((0,o.int)(s))),()=>{let n=(0,o.float)(0).toVar(),a=(0,o.float)(0).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){let r=c.element(u.add(1+e).mul(10).add(l.add(1+t)));n.addAssign(r),a.addAssign(r.mul(r))}n.divAssign(9),a.divAssign(9);let s=(0,o.max)(a.sub(n.mul(n)),(0,o.float)(0)),d=c.element(u.add(1).mul(10).add(l.add(1))),f=(0,o.textureLoad)(t,(0,o.ivec2)(_,v));(0,o.textureStore)(e,(0,o.uvec2)((0,o.uint)(_),(0,o.uint)(v)),Za(d,f.x,f.y,r,s,i)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}render(e){if(!this.enabled)return;let t=e.getTexture(this.inputTextureName);if(!t)return;let n=t.image;if(n&&n.width>0&&n.height>0&&(n.width!==this._storageTexA.image.width||n.height!==this._storageTexA.image.height)&&this.setSize(n.width,n.height),this._colorTexNode.value=t,this._compiled||=(this.renderer.compute(this._computeNodeA),this.renderer.compute(this._computeNodeB),!0),this._readTexNodeA.value=this._storageTexA,this._readTexNodeB.value=this._storageTexB,this._needsWarmReset){let e=this.temporalAlpha.value;this.temporalAlpha.value=1,this.renderer.compute(this._computeNodeA),this.renderer.compute(this._computeNodeB),this.temporalAlpha.value=e,this._needsWarmReset=!1}let r=this.currentMoments===0?this._computeNodeA:this._computeNodeB;this.renderer.compute(r);let i=this.currentMoments===0?this._storageTexA:this._storageTexB;this.currentMoments=1-this.currentMoments,e.setTexture(`variance:output`,i)}reset(){this.currentMoments=0,this._needsWarmReset=!0,this.context&&this.context.removeTexture(`variance:output`)}setSize(e,t){this._storageTexA.setSize(e,t),this._storageTexB.setSize(e,t),this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNodeA.setCount([this._dispatchX,this._dispatchY,1]),this._computeNodeB.setCount([this._dispatchX,this._dispatchY,1])}dispose(){this._computeNodeA?.dispose(),this._computeNodeB?.dispose(),this._storageTexA?.dispose(),this._storageTexB?.dispose()}},$a=(0,o.wgslFn)(`
|
|
554
554
|
fn bilateralWeight(
|
|
555
555
|
centerLum: f32, sLum: f32,
|
|
556
556
|
centerNormal: vec3f, sNormal: vec3f,
|
|
@@ -570,7 +570,7 @@
|
|
|
570
570
|
return kernelW * lumW * normW * depW * colW;
|
|
571
571
|
|
|
572
572
|
}
|
|
573
|
-
`)
|
|
573
|
+
`),eo=class extends L{constructor(e,r={}){super(`BilateralFiltering`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.inputTextureName=r.inputTextureName||`asvgf:output`,this.normalDepthTextureName=r.normalDepthTextureName||`pathtracer:normalDepth`,this.iterations=r.iterations??4,this.phiColor=(0,o.uniform)(r.phiColor??10),this.phiNormal=(0,o.uniform)(r.phiNormal??128),this.phiDepth=(0,o.uniform)(r.phiDepth??1),this.phiLuminance=(0,o.uniform)(r.phiLuminance??4),this.stepSizeU=(0,o.uniform)(1,`int`),this.resW=(0,o.uniform)(r.width||1),this.resH=(0,o.uniform)(r.height||1),this._readTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode;let i=r.width||1,a=r.height||1;this._storageTexA=new t.StorageTexture(i,a),this._storageTexA.type=n.HalfFloatType,this._storageTexA.format=n.RGBAFormat,this._storageTexA.minFilter=n.LinearFilter,this._storageTexA.magFilter=n.LinearFilter,this._storageTexB=new t.StorageTexture(i,a),this._storageTexB.type=n.HalfFloatType,this._storageTexB.format=n.RGBAFormat,this._storageTexB.minFilter=n.LinearFilter,this._storageTexB.magFilter=n.LinearFilter,this._compiled=!1,this._dispatchX=Math.ceil(i/8),this._dispatchY=Math.ceil(a/8),this._buildCompute()}_buildCompute(){this._computeNodeA=this._buildComputeForDirection(this._storageTexA),this._computeNodeB=this._buildComputeForDirection(this._storageTexB)}_buildComputeForDirection(e){let t=this._readTexNode,n=this._normalDepthTexNode,r=this.phiColor,i=this.phiNormal,a=this.phiDepth,s=this.phiLuminance,c=this.stepSizeU,l=this.resW,u=this.resH,d=[1/256,4/256,6/256,4/256,1/256,4/256,16/256,24/256,16/256,4/256,6/256,24/256,36/256,24/256,6/256,4/256,16/256,24/256,16/256,4/256,1/256,4/256,6/256,4/256,1/256];return(0,o.Fn)(()=>{let f=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),p=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(f.lessThan((0,o.int)(l)).and(p.lessThan((0,o.int)(u))),()=>{let m=(0,o.ivec2)(f,p),h=(0,o.textureLoad)(t,m).xyz,g=(0,o.textureLoad)(n,m),_=g.xyz.mul(2).sub(1),v=g.w,y=qt(h),b=(0,o.vec3)(0).toVar(),x=(0,o.float)(0).toVar();for(let e=0;e<5;e++)for(let m=0;m<5;m++){let g=m-2,S=e-2,C=d[e*5+m],w=f.add(c.mul(g)).clamp((0,o.int)(0),(0,o.int)(l).sub(1)),T=p.add(c.mul(S)).clamp((0,o.int)(0),(0,o.int)(u).sub(1)),E=(0,o.textureLoad)(t,(0,o.ivec2)(w,T)).xyz,D=(0,o.textureLoad)(n,(0,o.ivec2)(w,T)),O=D.xyz.mul(2).sub(1),k=D.w,A=$a(y,qt(E),_,O,v,k,h,E,(0,o.float)(C),s,i,a,r);b.addAssign(E.mul(A)),x.addAssign(A)}let S=b.div((0,o.max)(x,(0,o.float)(1e-4)));(0,o.textureStore)(e,(0,o.uvec2)((0,o.uint)(f),(0,o.uint)(p)),(0,o.vec4)(S,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}render(e){if(!this.enabled)return;let t=e.getTexture(this.inputTextureName)||e.getTexture(`pathtracer:color`),n=e.getTexture(this.normalDepthTextureName);if(!t)return;let r=t.image;r&&r.width>0&&r.height>0&&(r.width!==this._storageTexA.image.width||r.height!==this._storageTexA.image.height)&&this.setSize(r.width,r.height),n&&(this._normalDepthTexNode.value=n),this._compiled||=(this.renderer.compute(this._computeNodeA),this.renderer.compute(this._computeNodeB),!0);let i=t,a=this._computeNodeA,o=this._computeNodeB;for(let e=0;e<this.iterations;e++){this.stepSizeU.value=1<<e,this._readTexNode.value=i,this.renderer.compute(a),i=a===this._computeNodeA?this._storageTexA:this._storageTexB;let t=a;a=o,o=t}e.setTexture(`bilateralFiltering:output`,i)}setSize(e,t){this._storageTexA.setSize(e,t),this._storageTexB.setSize(e,t),this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNodeA.setCount([this._dispatchX,this._dispatchY,1]),this._computeNodeB.setCount([this._dispatchX,this._dispatchY,1])}reset(){}dispose(){this._computeNodeA?.dispose(),this._computeNodeB?.dispose(),this._storageTexA?.dispose(),this._storageTexB?.dispose()}},to=(0,o.wgslFn)(`
|
|
574
574
|
fn computeSamplingGuidance(
|
|
575
575
|
temporalVariance: f32,
|
|
576
576
|
spatialVariance: f32,
|
|
@@ -632,7 +632,7 @@
|
|
|
632
632
|
);
|
|
633
633
|
|
|
634
634
|
}
|
|
635
|
-
`),
|
|
635
|
+
`),no=(0,o.wgslFn)(`
|
|
636
636
|
fn heatmapGradient( t: f32, normalizedVariance: f32, converged: f32 ) -> vec4f {
|
|
637
637
|
|
|
638
638
|
let r = clamp( ( t - 0.5 ) * 4.0, 0.0, 1.0 );
|
|
@@ -655,7 +655,7 @@
|
|
|
655
655
|
return vec4f( color, 1.0 );
|
|
656
656
|
|
|
657
657
|
}
|
|
658
|
-
`),
|
|
658
|
+
`),ro=class extends L{constructor(e,r={}){super(`AdaptiveSampling`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.debugContainer=r.debugContainer||null,this.frameNumber=0,this.delayByFrames=r.delayByFrames??2,this.showAdaptiveSamplingHelper=!1,this.adaptiveSamplingMax=(0,o.uniform)(r.adaptiveSamplingMax??V.adaptiveSamplingMax??32,`int`),this.varianceThreshold=(0,o.uniform)(r.varianceThreshold??V.adaptiveSamplingVarianceThreshold??.01),this.materialBias=(0,o.uniform)(r.materialBias??V.adaptiveSamplingMaterialBias??1.2),this.edgeBias=(0,o.uniform)(r.edgeBias??V.adaptiveSamplingEdgeBias??1.5),this.convergenceSpeed=(0,o.uniform)(r.convergenceSpeed??V.adaptiveSamplingConvergenceSpeed??2),this.frameNumberUniform=(0,o.uniform)(0,`int`),this.resolutionWidth=(0,o.uniform)(r.width||1024),this.resolutionHeight=(0,o.uniform)(r.height||1024),this.minConvergenceFrames=(0,o.uniform)(10),this.convergenceThreshold=(0,o.uniform)(.01);let i=r.width||1,a=r.height||1;this._outputStorageTex=new t.StorageTexture(i,a),this._outputStorageTex.type=n.HalfFloatType,this._outputStorageTex.format=n.RGBAFormat,this._outputStorageTex.minFilter=n.LinearFilter,this._outputStorageTex.magFilter=n.LinearFilter,this._heatmapStorageTex=new t.StorageTexture(i,a),this._heatmapStorageTex.type=n.FloatType,this._heatmapStorageTex.format=n.RGBAFormat,this._heatmapStorageTex.minFilter=n.NearestFilter,this._heatmapStorageTex.magFilter=n.NearestFilter,this.heatmapTarget=new t.RenderTarget(i,a,{format:n.RGBAFormat,type:n.FloatType,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(i/16),this._dispatchY=Math.ceil(a/16),this._varianceTexNode=new t.TextureNode,this._buildCompute(),this._buildHeatmapCompute(),this.helper=Ya(this.renderer,this.heatmapTarget,{width:400,height:400,position:`bottom-right`,theme:`dark`,title:`Adaptive Sampling`,autoUpdate:!1}),this.helper.hide(),(this.debugContainer||document.body).appendChild(this.helper)}setupEventListeners(){this.on(`pathtracer:viewpointChanged`,()=>this.reset())}_buildCompute(){let e=this._varianceTexNode,t=this.varianceThreshold,n=this.materialBias,r=this.convergenceSpeed,i=this.frameNumberUniform,a=this.minConvergenceFrames,s=this.convergenceThreshold,c=this.resolutionWidth,l=this.resolutionHeight,u=this._outputStorageTex;this._computeNode=(0,o.Fn)(()=>{let d=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),f=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(d.lessThan((0,o.int)(c)).and(f.lessThan((0,o.int)(l))),()=>{let c=(0,o.textureLoad)(e,(0,o.ivec2)(d,f)),l=to(c.z,c.w,c.x,t,(0,o.int)(i),(0,o.int)(a),s,n,r);(0,o.textureStore)(u,(0,o.uvec2)((0,o.uint)(d),(0,o.uint)(f)),l).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildHeatmapCompute(){let e=this._outputStorageTex,t=this._heatmapStorageTex,n=this.resolutionWidth,r=this.resolutionHeight;this._heatmapComputeNode=(0,o.Fn)(()=>{let i=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),a=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(i.lessThan((0,o.int)(n)).and(a.lessThan((0,o.int)(r))),()=>{let n=(0,o.textureLoad)(e,(0,o.ivec2)(i,a)),r=no(n.x.clamp(0,1),n.y,n.z);(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(i),(0,o.uint)(a)),r).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[16,16,1])}toggleHelper(e){this.showAdaptiveSamplingHelper=e,e?this.helper.show():this.helper.hide()}render(e){if(!this.enabled||(this.frameNumber++,this.frameNumber<=this.delayByFrames))return;this.frameNumberUniform.value=this.frameNumber;let t=e.getTexture(`variance:output`);if(!t)return;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this._outputStorageTex.image.width||n.height!==this._outputStorageTex.image.height)&&this.setSize(n.width,n.height),this._varianceTexNode.value=t,this.renderer.compute(this._computeNode),e.setTexture(`adaptiveSampling:output`,this._outputStorageTex),this.showAdaptiveSamplingHelper&&(this.renderer.compute(this._heatmapComputeNode),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture),this.helper.update())}reset(){this.frameNumber=0,this.frameNumberUniform.value=0,this.context&&this.context.removeTexture(`adaptiveSampling:output`)}setSize(e,t){this._outputStorageTex.setSize(e,t),this._heatmapStorageTex.setSize(e,t),this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._computeNode.setCount([this._dispatchX,this._dispatchY,1]),this._heatmapComputeNode.setCount([this._dispatchX,this._dispatchY,1])}setAdaptiveSamplingMax(e){this.adaptiveSamplingMax.value=e}setVarianceThreshold(e){this.varianceThreshold.value=e}setMaterialBias(e){this.materialBias.value=e}setEdgeBias(e){this.edgeBias.value=e}setConvergenceSpeed(e){this.convergenceSpeed.value=e}setAdaptiveSamplingParameters(e){e.threshold!==void 0&&this.setVarianceThreshold(e.threshold),e.materialBias!==void 0&&this.setMaterialBias(e.materialBias),e.edgeBias!==void 0&&this.setEdgeBias(e.edgeBias),e.convergenceSpeedUp!==void 0&&this.setConvergenceSpeed(e.convergenceSpeedUp),e.adaptiveSamplingMax!==void 0&&this.setAdaptiveSamplingMax(e.adaptiveSamplingMax)}dispose(){this._computeNode?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this._outputStorageTex?.dispose(),this.heatmapTarget?.dispose(),this.helper?.dispose()}},io=class extends L{constructor(e,r={}){super(`EdgeAwareFiltering`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.pixelEdgeSharpness=(0,o.uniform)(r.pixelEdgeSharpness??.75),this.edgeSharpenSpeed=(0,o.uniform)(r.edgeSharpenSpeed??.05),this.edgeThreshold=(0,o.uniform)(r.edgeThreshold??1),this.iterationCount=(0,o.uniform)(0),this.resW=(0,o.uniform)(r.width||1),this.resH=(0,o.uniform)(r.height||1),this._iterations=0,this._inputTexNode=new t.TextureNode;let i=2048,a=r.width||1,s=r.height||1;this._outputStorageTex=new t.StorageTexture(i,i),this._outputStorageTex.type=n.HalfFloatType,this._outputStorageTex.format=n.RGBAFormat,this._outputStorageTex.minFilter=n.NearestFilter,this._outputStorageTex.magFilter=n.NearestFilter,this._srcRegion=new n.Box2(new n.Vector2(0,0),new n.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,s,{type:n.HalfFloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(a/16),this._dispatchY=Math.ceil(s/16),this._buildCompute()}_buildCompute(){let e=this._inputTexNode,t=this._outputStorageTex,n=this.pixelEdgeSharpness,r=this.edgeSharpenSpeed,i=this.edgeThreshold,a=this.iterationCount,s=this.resW,c=this.resH;this._computeNode=(0,o.Fn)(()=>{let l=(0,o.int)(o.workgroupId.x).mul(16).add((0,o.int)(o.localId.x)),u=(0,o.int)(o.workgroupId.y).mul(16).add((0,o.int)(o.localId.y));(0,o.If)(l.lessThan((0,o.int)(s)).and(u.lessThan((0,o.int)(c))),()=>{let d=(0,o.textureLoad)(e,(0,o.ivec2)(l,u)).xyz,f=(0,o.dot)(d,(0,o.vec3)(.2126,.7152,.0722)),p=n.add(a.mul(r)).clamp(0,.95),m=d.toVar(),h=(0,o.float)(1).toVar();for(let[t,n]of[[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]])for(let r of[1,2]){let a=(0,o.textureLoad)(e,(0,o.ivec2)(l.add(t*r).clamp((0,o.int)(0),(0,o.int)(s).sub(1)),u.add(n*r).clamp((0,o.int)(0),(0,o.int)(c).sub(1)))).xyz,d=(0,o.dot)(a,(0,o.vec3)(.2126,.7152,.0722)),p=(0,o.abs)(f.sub(d)).div((0,o.max)(i,(0,o.float)(.001))).negate().exp(),g=(0,o.float)(1).div((0,o.float)(r).add(.5)),_=p.mul(g);m.addAssign(a.mul(_)),h.addAssign(_)}let g=(0,o.mix)(m.div((0,o.max)(h,(0,o.float)(1e-4))),d,p),_=(0,o.dot)(g,(0,o.vec3)(.2126,.7152,.0722)),v=g.toVar();(0,o.If)(_.greaterThan(10),()=>{v.assign(g.mul((0,o.float)(10).div(_)))}),(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(l),(0,o.uint)(u)),(0,o.vec4)(v,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[16,16,1])}render(e){if(!this.enabled)return;let t=e.getTexture(`asvgf:output`)||e.getTexture(`bilateralFiltering:output`)||e.getTexture(`pathtracer:color`);if(!t)return;if(e.getState(`interactionMode`)){e.setTexture(`edgeFiltering:output`,t);return}let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.outputTarget.width||n.height!==this.outputTarget.height)&&this.setSize(n.width,n.height),this._inputTexNode.value=t,this._iterations++,this.iterationCount.value=this._iterations,this.renderer.compute(this._computeNode),this._srcRegion.min.set(0,0),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._outputStorageTex,this.outputTarget.texture,this._srcRegion),e.setTexture(`edgeFiltering:output`,this.outputTarget.texture)}setFilteringEnabled(e){this.enabled=e}updateUniforms(e){e&&(e.pixelEdgeSharpness!==void 0&&(this.pixelEdgeSharpness.value=e.pixelEdgeSharpness),e.edgeSharpenSpeed!==void 0&&(this.edgeSharpenSpeed.value=e.edgeSharpenSpeed),e.edgeThreshold!==void 0&&(this.edgeThreshold.value=e.edgeThreshold))}reset(){this._iterations=0,this.iterationCount.value=0}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._computeNode.setCount([this._dispatchX,this._dispatchY,1])}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this.outputTarget?.dispose()}},ao=(0,o.wgslFn)(`
|
|
659
659
|
fn adaptExposure(
|
|
660
660
|
geoMean: f32,
|
|
661
661
|
prevExposure: f32,
|
|
@@ -684,5 +684,5 @@
|
|
|
684
684
|
return vec4f( newExposure, geoMean, targetExp, 1.0 );
|
|
685
685
|
|
|
686
686
|
}
|
|
687
|
-
`),ao=class extends L{constructor(e,n={}){super(`AutoExposure`,{...n,executionMode:I.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,o.uniform)(n.keyValue??.18),this.minExposureU=(0,o.uniform)(n.minExposure??.1),this.maxExposureU=(0,o.uniform)(n.maxExposure??20),this.adaptSpeedBrightU=(0,o.uniform)(n.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,o.uniform)(n.adaptSpeedDark??.5),this.epsilonU=(0,o.uniform)(n.epsilon??1e-4),this.deltaTimeU=(0,o.uniform)(1/60),this.isFirstFrameU=(0,o.uniform)(1),this.previousExposureU=(0,o.uniform)(n.initialExposure??1),this.inputResW=(0,o.uniform)(1),this.inputResH=(0,o.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=n.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=n.FloatType,this._downsampleStorageTex.format=n.RGBAFormat,this._downsampleStorageTex.minFilter=n.NearestFilter,this._downsampleStorageTex.magFilter=n.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=n.FloatType,this._reductionStorageTex.format=n.RGBAFormat,this._reductionStorageTex.minFilter=n.NearestFilter,this._reductionStorageTex.magFilter=n.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationStorageTex=new t.StorageTexture(1,1),this._adaptationStorageTex.type=n.FloatType,this._adaptationStorageTex.format=n.RGBAFormat,this._adaptationStorageTex.minFilter=n.NearestFilter,this._adaptationStorageTex.magFilter=n.NearestFilter,this._adaptationTarget=new t.RenderTarget(1,1,e)}_buildCompute(){this._buildDownsampleCompute(),this._buildReductionCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,n=this.epsilonU,r=this.inputResW,i=this.inputResH;this._downsampleComputeNode=(0,o.Fn)(()=>{let a=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),s=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y)),c=r.div((0,o.float)(64)),l=i.div((0,o.float)(64)),u=(0,o.float)(a).mul(c),d=(0,o.float)(s).mul(l),f=(0,o.float)(0).toVar(),p=(0,o.float)(0).toVar();for(let t=0;t<4;t++)for(let r=0;r<4;r++){let i=Kt((0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(u.add((0,o.float)((r+.5)/4).mul(c))),(0,o.int)(d.add((0,o.float)((t+.5)/4).mul(l))))).xyz);(0,o.If)(i.greaterThan(n),()=>{f.addAssign(i.add(n).log()),p.addAssign(1)})}(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(a),(0,o.uint)(s)),(0,o.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildReductionCompute(){let e=this._downsampleTarget.texture,t=this._reductionStorageTex,n=(0,o.workgroupArray)(`float`,256),r=(0,o.workgroupArray)(`float`,256);this._reductionComputeNode=(0,o.Fn)(()=>{let i=o.localId.x,a=(0,o.float)(0).toVar(),s=(0,o.float)(0).toVar();for(let t=0;t<16;t++){let n=i.mul(16).add(t),r=n.mod(64),c=n.div(64),l=(0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(r),(0,o.int)(c)));a.addAssign(l.x),s.addAssign(l.y)}n.element(i).assign(a),r.element(i).assign(s);for(let e=256/2;e>=1;e=Math.floor(e/2))(0,o.workgroupBarrier)(),(0,o.If)(i.lessThan((0,o.uint)(e)),()=>{n.element(i).addAssign(n.element(i.add((0,o.uint)(e)))),r.element(i).addAssign(r.element(i.add((0,o.uint)(e))))});(0,o.workgroupBarrier)(),(0,o.If)(i.equal((0,o.uint)(0)),()=>{let e=n.element((0,o.uint)(0)),i=r.element((0,o.uint)(0)),a=(0,o.max)(i,(0,o.float)(1)),s=e.div(a),c=s.exp();(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(0),(0,o.uint)(0)),(0,o.vec4)(c,i,s,1)).toWriteOnly()})})().compute(1,[256,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationStorageTex,n=this.keyValueU,r=this.minExposureU,i=this.maxExposureU,a=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,o.Fn)(()=>{let d=(0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(0),(0,o.int)(0))).x,f=io(d,u,n,r,i,a,s,c,l);(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(0),(0,o.uint)(0)),f).toWriteOnly()})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>{e&&(e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark))})}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=this.isFirstFrame?1:0,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._reductionComputeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),this.renderer.copyTextureToTexture(this._adaptationStorageTex,this._adaptationTarget.texture),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.readRenderTargetPixelsAsync(this._adaptationTarget,0,0,1,1).then(t=>{this._pendingReadback=!1,e===this._readbackGeneration&&this._applyReadback(t)}).catch(()=>{this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark)}dispose(){this._downsampleComputeNode?.dispose(),this._reductionComputeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._adaptationStorageTex?.dispose(),this._adaptationTarget?.dispose()}};function oo({colorTexNode:e,ndTexNode:t,motionTexNode:n,readCacheTexNode:r,readPrevNDTexNode:i,writeCacheTex:a,writePrevNDTex:s,resW:c,resH:l,temporalAlpha:u,phiNormal:d,phiDepth:f,maxHistory:p,framesSinceReset:m}){return(0,o.Fn)(()=>{let h=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),g=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(h.lessThan((0,o.int)(c)).and(g.lessThan((0,o.int)(l))),()=>{let _=(0,o.ivec2)(h,g),v=(0,o.textureLoad)(e,_).xyz,y=(0,o.textureLoad)(t,_),b=(0,o.vec4)(v,1).toVar();(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{let e=(0,o.textureLoad)(n,_),t=e.w.greaterThan(.5),a=(0,o.float)(h).sub(e.x.mul(c)),s=(0,o.float)(g).sub(e.y.mul(l)),m=a.greaterThanEqual(0).and(a.lessThan((0,o.float)(c))).and(s.greaterThanEqual(0)).and(s.lessThan((0,o.float)(l)));(0,o.If)(t.and(m),()=>{let e=(0,o.ivec2)((0,o.int)(a).clamp((0,o.int)(0),(0,o.int)(c).sub(1)),(0,o.int)(s).clamp((0,o.int)(0),(0,o.int)(l).sub(1))),t=y.xyz.mul(2).sub(1),n=(0,o.textureLoad)(i,e),m=an(t,n.xyz.mul(2).sub(1),y.w,n.w,d,f);(0,o.If)(m.greaterThan(.01),()=>{let t=(0,o.textureLoad)(r,e),n=t.xyz,i=t.w,a=(0,o.mix)(n,v,(0,o.min)((0,o.max)(u,(0,o.float)(1).div(i.add(1))).div((0,o.max)(m,(0,o.float)(.1))),1)),s=(0,o.min)(i.add(1),p);b.assign((0,o.vec4)(a,s))}).Else(()=>{b.assign((0,o.vec4)(v,1))})}).Else(()=>{b.assign((0,o.vec4)(v,1))})}),(0,o.textureStore)(a,(0,o.uvec2)(h,g),b).toWriteOnly(),(0,o.textureStore)(s,(0,o.uvec2)(h,g),y).toWriteOnly()})})}function so({colorTexNode:e,ndTexNode:t,readCacheTexNode:n,outputTex:r,resW:i,resH:a,spatialRadius:s,spatialWeight:c,phiNormal:l,phiDepth:u}){let d=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];return(0,o.Fn)(()=>{let f=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),p=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(f.lessThan((0,o.int)(i)).and(p.lessThan((0,o.int)(a))),()=>{let m=(0,o.ivec2)(f,p),h=(0,o.textureLoad)(n,m),g=h.xyz,_=h.w,v=(0,o.textureLoad)(t,m),y=v.xyz.mul(2).sub(1),b=(0,o.float)(1).sub(_.div(16).clamp(0,1)),x=c.mul(b),S=(0,o.vec3)(g).toVar(),C=(0,o.float)(1).toVar();for(let e=0;e<d.length;e++){let[r,c]=d[e],m=(0,o.ivec2)(f.add((0,o.int)(s).mul(r)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),p.add((0,o.int)(s).mul(c)).clamp((0,o.int)(0),(0,o.int)(a).sub(1))),h=(0,o.textureLoad)(n,m).xyz,g=(0,o.textureLoad)(t,m),_=an(y,g.xyz.mul(2).sub(1),v.w,g.w,l,u);S.addAssign(h.mul(_)),C.addAssign(_)}let w=(0,o.mix)(g,S.div((0,o.max)(C,1e-4)),x),T=(0,o.textureLoad)(e,m).w;(0,o.textureStore)(r,(0,o.uvec2)(f,p),(0,o.vec4)(w,T)).toWriteOnly()})})}var co=class extends L{constructor(e,r={}){super(`SSRC`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.resW=(0,o.uniform)(1),this.resH=(0,o.uniform)(1),this.temporalAlpha=(0,o.uniform)(r.temporalAlpha??.1),this.phiNormal=(0,o.uniform)(r.phiNormal??128),this.phiDepth=(0,o.uniform)(r.phiDepth??.5),this.maxHistory=(0,o.uniform)(r.maxHistory??128),this.spatialRadius=(0,o.uniform)(r.spatialRadius??4,`int`),this.spatialWeight=(0,o.uniform)(r.spatialWeight??.4),this._framesSinceReset=(0,o.uniform)(0,`int`),this._colorTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._readCacheTexNode=new t.TextureNode,this._readPrevNDTexNode=new t.TextureNode,this._readPass1CacheTexNode=new t.TextureNode,this._cacheTexA=this._createStorageTex(1,1,n.NearestFilter),this._cacheTexB=this._createStorageTex(1,1,n.NearestFilter),this._prevNDTexA=this._createStorageTex(1,1,n.NearestFilter),this._prevNDTexB=this._createStorageTex(1,1,n.NearestFilter),this._outputTex=this._createStorageTex(1,1,n.LinearFilter),this._currentPingPong=0,this._dispatchX=1,this._dispatchY=1,this._buildComputeNodes()}setupEventListeners(){this.on(`pipeline:reset`,()=>this._resetCache()),this.on(`camera:moved`,()=>this._resetCache())}render(e){if(!this.enabled){e.removeTexture(`ssrc:output`);return}let t=e.getTexture(`pathtracer:color`);if(t?.image){let{width:e,height:n}=t.image;(e!==this._cacheTexA.image.width||n!==this._cacheTexA.image.height)&&this.setSize(e,n)}let n=e.getTexture(`pathtracer:normalDepth`);if(!n||!t)return;this._colorTexNode.value=t,this._ndTexNode.value=n;let r=e.getTexture(`motionVector:screenSpace`);r&&(this._motionTexNode.value=r);let[i,a,o]=this._currentPingPong===0?[this._cacheTexB,this._cacheTexA,this._prevNDTexB]:[this._cacheTexA,this._cacheTexB,this._prevNDTexA];this._readCacheTexNode.value=i,this._readPrevNDTexNode.value=o,this.renderer.compute(this._currentPingPong===0?this._pass1NodeA:this._pass1NodeB),this._readPass1CacheTexNode.value=a,this.renderer.compute(this._pass2Node),this._framesSinceReset.value=Math.min(this._framesSinceReset.value+1,9999),e.setTexture(`ssrc:output`,this._outputTex),this._currentPingPong=1-this._currentPingPong}reset(){this._resetCache()}setSize(e,t){if(e<1||t<1)return;this._cacheTexA.setSize(e,t),this._cacheTexB.setSize(e,t),this._prevNDTexA.setSize(e,t),this._prevNDTexB.setSize(e,t),this._outputTex.setSize(e,t),this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8);let n=[this._dispatchX,this._dispatchY,1];this._pass1NodeA&&this._pass1NodeA.setCount(n),this._pass1NodeB&&this._pass1NodeB.setCount(n),this._pass2Node&&this._pass2Node.setCount(n),this._resetCache()}dispose(){this._pass1NodeA?.dispose(),this._pass1NodeB?.dispose(),this._pass2Node?.dispose(),this._cacheTexA.dispose(),this._cacheTexB.dispose(),this._prevNDTexA.dispose(),this._prevNDTexB.dispose(),this._outputTex.dispose()}updateParameters(e){e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth),e.maxHistory!==void 0&&(this.maxHistory.value=e.maxHistory),e.spatialRadius!==void 0&&(this.spatialRadius.value=e.spatialRadius),e.spatialWeight!==void 0&&(this.spatialWeight.value=e.spatialWeight)}_createStorageTex(e,r,i){let a=new t.StorageTexture(e,r);return a.type=n.HalfFloatType,a.format=n.RGBAFormat,a.minFilter=i,a.magFilter=i,a}_resetCache(){this._currentPingPong=0,this._framesSinceReset.value=0}_buildComputeNodes(){let e={colorTexNode:this._colorTexNode,ndTexNode:this._ndTexNode,motionTexNode:this._motionTexNode,readCacheTexNode:this._readCacheTexNode,readPrevNDTexNode:this._readPrevNDTexNode,resW:this.resW,resH:this.resH,temporalAlpha:this.temporalAlpha,phiNormal:this.phiNormal,phiDepth:this.phiDepth,maxHistory:this.maxHistory},t=oo({...e,writeCacheTex:this._cacheTexA,writePrevNDTex:this._prevNDTexA,framesSinceReset:this._framesSinceReset}),n=oo({...e,writeCacheTex:this._cacheTexB,writePrevNDTex:this._prevNDTexB,framesSinceReset:this._framesSinceReset}),r=[this._dispatchX,this._dispatchY,1],i=[8,8,1];this._pass1NodeA=t().compute(r,i),this._pass1NodeB=n().compute(r,i),this._pass2Node=so({colorTexNode:this._colorTexNode,ndTexNode:this._ndTexNode,readCacheTexNode:this._readPass1CacheTexNode,outputTex:this._outputTex,resW:this.resW,resH:this.resH,spatialRadius:this.spatialRadius,spatialWeight:this.spatialWeight,phiNormal:this.phiNormal,phiDepth:this.phiDepth})().compute(r,i)}},lo=class extends L{constructor(e,r={}){super(`Display`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.exposure=(0,o.uniform)(r.exposure??1),this.saturation=(0,o.uniform)(r.saturation??1),this._transparentBackground=(0,o.uniform)(0,`int`),this._displayTexNode=new t.TextureNode;let i=this._displayTexNode.sample((0,o.uv)()),a=i.xyz.mul(this.exposure),s=(0,o.mix)((0,o.vec3)((0,o.dot)(a,Vt)),a,this.saturation),c=(0,o.select)(this._transparentBackground,i.w,1);this.displayMaterial=new t.MeshBasicNodeMaterial,this.displayMaterial.colorNode=(0,o.vec4)(s,c),this.displayMaterial.blending=n.NoBlending,this.displayMaterial.toneMapped=!0,this.displayQuad=new t.QuadMesh(this.displayMaterial)}_resolveDisplayTexture(e){return e.getTexture(`bloom:output`)||e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`ssrc:output`)||e.getTexture(`pathtracer:color`)}render(e){if(!this.enabled)return;let t=this._resolveDisplayTexture(e);t&&(this._displayTexNode.value=t,this.renderer.setRenderTarget(null),this.displayQuad.render(this.renderer))}setExposure(e){this.exposure.value=e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=e?1:0}dispose(){this.displayMaterial?.dispose(),this.displayQuad?.dispose()}},uo=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableAdaptiveSampling:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},fo=class extends n.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},po=class{constructor(e,t,n){this.renderer=e,this.width=t,this.height=n,this.stages=[],this.context=new uo,this.eventBus=new fo,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(t.render(this.context,e),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){console.error(`[Pipeline] Error in stage '${t.name}':`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){console.error(`[Pipeline] Error resetting stage '${e.name}':`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}},mo=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t){return e===`time`&&t>0&&this.timeElapsed>=t}isLimitReached(e,t,n){return e?this.isTimeLimitReached(t,n)?!0:e.frameCount>=e.completionThreshold:!1}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},ho=class extends n.EventDispatcher{constructor({scene:e,camera:t,canvas:r,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=r,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new n.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:R.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=e.distance;this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:t/this.assetLoader.getSceneScale(),worldDistance:t})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new n.Mesh(new n.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new n.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object,t=this.selectedObject;t&&t.uuid===e.uuid?this.dispatchEvent({type:`objectDeselected`,object:e,uuid:e.uuid}):this.dispatchEvent({type:`objectSelected`,object:e,uuid:e.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:R.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:`focusChanged`,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:R.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},go={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usdz:{type:`model`,name:`Universal Scene Description`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`}},_o=class extends n.EventDispatcher{constructor(e,t,n){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null}setRenderer(e){this.renderer=e}getFileFormat(e){return go[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);z({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usdz`:return await this.loadUSDZFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let e=await this.loadEnvironment(n);return this.dispatchEvent({type:`load`,texture:e,filename:t}),e}finally{URL.revokeObjectURL(n)}}async loadEnvironment(e){try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:e});let t;if(e.startsWith(`blob:`))t=await this.loadEnvironmentFromBlob(e);else{let n=e.split(`.`).pop().toLowerCase();t=await this.loadEnvironmentByExtension(e,n)}return t.generateMipmaps=!0,this.applyEnvironmentToScene(t),this.dispatchEvent({type:`load`,texture:t}),t}catch(t){throw console.error(`Error loading environment:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(e,t){let r;return t===`hdr`||t===`exr`?r=await(t===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new c.HDRLoader().setDataType(n.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new d.EXRLoader().setDataType(n.FloatType))).loadAsync(e):(this.loaderCache.texture||(this.loaderCache.texture=new n.TextureLoader),r=await this.loaderCache.texture.loadAsync(e)),r.mapping=n.EquirectangularReflectionMapping,r.minFilter=n.LinearFilter,r.magFilter=n.LinearFilter,r}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async loadArchiveFromFile(e,t){try{let n=await this.readFileAsArrayBuffer(e),r=(0,m.unzipSync)(new Uint8Array(n));return await this.processObjMtlPairsInZip(r,t)||await this.findAndLoadModelFromZip(r,t)}catch(e){throw console.error(`Error loading ZIP archive:`,e),e}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(go[n]&&go[n].type===`model`)return console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e)}throw Error(`No supported model files found in the ZIP archive`)}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usdz`:o=await this.loadUSDZFromArrayBuffer(e.buffer,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,r,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new n.LoadingManager,o=r.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();return s.manager=a,await new Promise((t,n)=>{s.parse(e,``,e=>{this.targetModel&&B(this.targetModel),this.targetModel=e.scene,this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}else return await this.loadGLBFromArrayBuffer(t.buffer,r)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.targetModel&&B(this.targetModel),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async loadMtlFromZip(e,t,r){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(r[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(r[e]),o=new n.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,r));let s=new t(o).parse(a,i);return s.preload(),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,r,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new n.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,r,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);f.preload();let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.targetModel&&B(this.targetModel),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){if(this.loaderCache.gltf)return this.loaderCache.gltf;let e=new l.DRACOLoader;e.setDecoderConfig({type:`js`}),e.setDecoderPath(`https://www.gstatic.com/draco/v1/decoders/`);let t=new u.KTX2Loader;t.setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`),this.renderer&&(t.detectSupport(this.renderer),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),this.loaderCache.ktx2=t;let n=new s.GLTFLoader;return n.setDRACOLoader(e),n.setKTX2Loader(t),n.setMeshoptDecoder(p.MeshoptDecoder),this.loaderCache.gltf=n,n}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(e){try{let t=await this.createGLTFLoader();z({status:`Loading Model...`,progress:2});let n=await t.loadAsync(e);return z({status:`Processing Data...`,progress:10}),this.targetModel&&B(this.targetModel),this.targetModel=n.scene,this.animations=n.animations||[],await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n.scene,filename:e.split(`/`).pop()}),n}catch(t){throw console.error(`Error loading model:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t}}async loadGLBFromArrayBuffer(e,t=`model.glb`){try{let n=await this.createGLTFLoader();z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this.targetModel&&B(this.targetModel),this.targetModel=r.scene,this.animations=r.animations||[],z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let r=new n.Mesh(this.loaderCache.stl.parse(e),new n.MeshStandardMaterial);return r.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let r=this.loaderCache.ply.parse(e),i;if(r.index!==null)i=new n.Mesh(r,new n.MeshStandardMaterial);else{let e=new n.PointsMaterial({size:.01});e.vertexColors=r.hasAttribute(`color`),i=new n.Points(r,e)}return i.name=t,this.targetModel&&B(this.targetModel),this.targetModel=i,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDZFromArrayBuffer(e,t=`model.usdz`){try{if(z({isLoading:!0,status:`Processing USDZ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usdz){let{USDZLoader:e}=await import(`three/examples/jsm/loaders/USDZLoader.js`);this.loaderCache.usdz=new e}let n=this.loaderCache.usdz.parse(e);return n.name=t,this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USDZ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){return e.name=e.name||t,this.targetModel&&B(this.targetModel),this.targetModel=e,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e,filename:t}),e}async onModelLoad(e){let t=new oa(`onModelLoad`);t.start(`Camera extraction`);let r=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new n.Box3().setFromObject(e),a=i.getCenter(new n.Vector3),o=i.getSize(new n.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new n.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:r,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[];e.traverse(e=>{let r=e.userData;if(e.isRectAreaLight&&!t.includes(e.uuid)&&t.push(e.uuid),e.name.startsWith(`RectAreaLightPlaceholder`)&&r.name&&r.type===`RectAreaLight`){let i=new n.RectAreaLight(new n.Color(...r.color),r.intensity*.1/Math.PI,r.width,r.height);i.position.z=-2,i.name=r.name,e.add(i),t.push(i.uuid)}if(e.isMesh&&Array.isArray(e.material)){console.log(`Found multi-material mesh:`,e.name);let t=(0,f.createMeshesFromMultiMaterialMesh)(e);e.parent&&(e.parent.add(t),e.parent.remove(e))}})}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new n.Mesh(new n.CircleGeometry,new n.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(go))r.type===e&&(t[n]=r);return t}return go}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},super.dispose(),this.targetModel&&=(B(this.targetModel),null),console.log(`AssetLoader resources disposed`)}removeAllEventListeners(){super.dispose()}},vo={maxBounces:{uniform:`maxBounces`,reset:!0},samplesPerPixel:{uniform:`samplesPerPixel`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},adaptiveSamplingMax:{uniform:`adaptiveSamplingMax`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},yo={bounces:`maxBounces`,adaptiveSampling:`useAdaptiveSampling`,debugMode:`visMode`},bo=class extends n.EventDispatcher{constructor(e=V){super(),this._values=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind({stages:e,resetCallback:t,reconcileCompletion:n}){this._pathTracer=e.pathTracer,this._resetCallback=t,this._delegates={},this._handlers=this._buildHandlers(e,n)}_buildHandlers(e,t){return{handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.display?.setTransparentBackground(t)},handleExposure:t=>{e.autoExposure?.enabled||e.display?.setExposure(t)},handleSaturation:t=>{e.display?.setSaturation(t)},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t)},handleMaxSamples:n=>{e.pathTracer?.setUniform(`maxSamples`,n),e.pathTracer?.updateCompletionThreshold(),t?.()},handleRenderTimeLimit:()=>{t?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)}}}set(e,t,{reset:n,silent:r}={}){let i=this._values.get(e);if(i===t)return;this._values.set(e,t);let a=vo[e];a&&(this._applyRoute(a,t,i),(n===void 0?a.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:R.SETTING_CHANGED,key:e,value:t,prev:i}))}setMany(e,{silent:t}={}){let n=!1;for(let[r,i]of Object.entries(e)){let e=this._values.get(r);if(e===i)continue;this._values.set(r,i);let a=vo[r];a&&(this._applyRoute(a,i,e),(a.reset??!0)&&(n=!0),t||this.dispatchEvent({type:R.SETTING_CHANGED,key:r,value:i,prev:e}))}n&&this._resetCallback?.()}get(e){return this._values.get(e)}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=vo[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(vo))t in e&&this._values.set(t,e[t]);for(let[t,n]of Object.entries(yo))t in e&&this._values.set(n,e[t])}},xo=class extends n.EventDispatcher{constructor(e){super();let t=e.clientWidth,r=e.clientHeight;this.camera=new n.PerspectiveCamera(60,t/r||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this.autoFocusMode=Ie.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Ie.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null}setCameras(e){this.cameras=e}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n}){this._onResize=e,this._onReset=t,this._getSettings=n}switchCamera(e,t,r,i){if(t??=this._getSettings?.(`focusDistance`),r??=this._onResize,i??=this._onReset,!(!this.cameras||this.cameras.length===0)){if((e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let r=this.cameras[e];if(this.camera.position.copy(r.position),this.camera.quaternion.copy(r.quaternion),this.camera.fov=r.fov,this.camera.near=r.near,this.camera.far=r.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=new n.Vector3(0,0,-1).applyQuaternion(r.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i),this.controls.update()}}r?.(),i?.(),this.dispatchEvent({type:`CameraSwitched`,cameraIndex:e})}}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let{meshScene:t,assetLoader:n,floorPlane:r,currentFocusDistance:i,pathTracer:a,setFocusDistance:o,softReset:s,hardReset:c}=e||this._afContext||{};if(!t||this.autoFocusMode===`manual`)return;let l=a;if(l?.isReady&&l.renderMode?.value===1&&l.frameCount>0&&!l.isComplete)return;let u=this.afScreenPoint.x*2-1,d=-(this.afScreenPoint.y*2-1),f=this.interactionManager?.raycaster;if(!f)return;f.setFromCamera({x:u,y:d},this.camera);let p=f.intersectObjects(t.children,!0).find(e=>e.object!==this.interactionManager?.focusPointIndicator&&e.object!==r&&!e.object.name.includes(`Helper`)&&e.object.type===`Mesh`),m;if(p)m=p.distance,this._lastValidFocusDistance=m;else if(this._lastValidFocusDistance!==null)m=this._lastValidFocusDistance;else{let e=n?.getSceneScale()||1;m=Ie.FALLBACK_DISTANCE*e,this._lastValidFocusDistance=m}let h=this._afPointDirty;this._afPointDirty=!1,h||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(m-this._smoothedFocusDistance)/this._smoothedFocusDistance>Ie.SNAP_THRESHOLD?this._smoothedFocusDistance=m:this._smoothedFocusDistance+=this.afSmoothingFactor*(m-this._smoothedFocusDistance);let g=i,_=this._smoothedFocusDistance;if(h||g===0||Math.abs(_-g)/Math.max(g,.001)>.001){o(_);let e=n?.getSceneScale()||1;this.dispatchEvent({type:R.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Ie.RESET_THRESHOLD&&s?.()}}setInteractionManager(e){this.interactionManager=e}initAutoFocus({meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,settings:i,softReset:a,hardReset:o}){this._afContext={meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,setFocusDistance:e=>i.set(`focusDistance`,e,{silent:!0}),softReset:a,hardReset:o},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>i.get(`focusDistance`)})}dispose(){this.controls?.dispose()}},So=class extends n.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:100,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:300,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:500,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let r;if(e===`DirectionalLight`)r=new n.DirectionalLight(t.color,t.intensity),r.position.fromArray(t.position);else if(e===`PointLight`)r=new n.PointLight(t.color,t.intensity),r.position.fromArray(t.position);else if(e===`SpotLight`){r=new n.SpotLight(t.color,t.intensity),r.position.fromArray(t.position),r.angle=n.MathUtils.degToRad(t.angle);let e=new n.Object3D;this.scene.add(e),r.target=e}else e===`RectAreaLight`&&(r=new n.RectAreaLight(t.color,t.intensity,t.width,t.height),r.position.fromArray(t.position),r.lookAt(0,0,0));let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return r.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(r),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(r)}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights()}transferSceneLights(e){this._removeAllLights();let t=e.getObjectsByProperty(`isLight`,!0);if(!t||t.length===0){this.updateLights();return}for(let e of t){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let r=new n.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(r.position),this.scene.add(r),t.target=r}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}_removeAllLights(){this.scene.getObjectsByProperty(`isLight`,!0).forEach(e=>{e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0&&(t=n.MathUtils.radToDeg(e.angle));let r={uuid:e.uuid,name:e.name,type:e.type,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t};if(e.type===`RectAreaLight`){r.width=e.width,r.height=e.height;let t=e.getWorldDirection(e.position.clone());r.target=[e.position.x+t.x,e.position.y+t.y,e.position.z+t.z]}else e.type===`SpotLight`&&e.target&&(r.target=[e.target.position.x,e.target.position.y,e.target.position.z]);return r}},Co=e=>Math.min(Math.max(e,0),1);function wo(e,t,n,r,i){i[0]=Co(e),i[1]=Co(t),i[2]=Co(n)}function To(e,t,n,r,i){i[0]=Co(e*r),i[1]=Co(t*r),i[2]=Co(n*r)}function Eo(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=Co(e/(e+1)),i[1]=Co(t/(t+1)),i[2]=Co(n/(n+1))}function Do(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Oo(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=Co(1.60475*a-.53108*o-.07367*s),i[1]=Co(-.10208*a+1.10813*o-.00605*s),i[2]=Co(-.00327*a-.07276*o+1.07602*s)}function ko(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=Co((Math.log2(Math.max(c,1e-10))-d)/f),l=Co((Math.log2(Math.max(l,1e-10))-d)/f),u=Co((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=Co(1.6605*m-.5876*h-.0728*g),i[1]=Co(-.1246*m+1.1329*h-.0083*g),i[2]=Co(-.0182*m-.1006*h+1.1187*g)}function Ao(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var jo=new Map([[n.NoToneMapping,wo],[n.LinearToneMapping,To],[n.ReinhardToneMapping,Eo],[n.CineonToneMapping,Do],[n.ACESFilmicToneMapping,Oo],[n.AgXToneMapping,ko],[n.NeutralToneMapping,Ao]]),Mo=1/2.2,No=.2126,Po=.7152,Fo=.0722;function Io(e,t){if(t===1)return;let n=e[0]*No+e[1]*Po+e[2]*Fo;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}var Lo=null;async function Ro(){return Lo||=(await import(`oidn-web`)).initUNetFromURL,Lo}var $=new Float32Array(3),zo={BASE_URL:`https://cdn.jsdelivr.net/npm/denoiser/tzas/`,QUALITY_SUFFIXES:{fast:`_small`,balance:``,high:`_large`},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,debugGbufferMaps:!0,tileSize:256}},Bo=class extends n.EventDispatcher{constructor(e,t,r,i,a={}){if(super(),!e||!t||!r||!i)throw Error(`OIDNDenoiser requires output canvas, renderer, scene, and camera`);this.renderer=t,this.scene=r,this.camera=i,this.input=t.domElement,this.output=e,this.debugContainer=a.debugContainer||null,this.extractGBufferData=a.extractGBufferData||null,this.getMRTRenderTarget=a.getMRTRenderTarget||null,this.backendParamsGetter=a.backendParams||null,this.getGPUTextures=a.getGPUTextures||null,this.getExposure=a.getExposure||(()=>1),this.getToneMapping=a.getToneMapping||(()=>n.ACESFilmicToneMapping),this.getSaturation=a.getSaturation||(()=>1),this.getTransparentBackground=a.getTransparentBackground||(()=>!1),this.isGPUMode=!!this.backendParamsGetter,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._cachedAlpha=null,this._cachedAlphaWidth=0,this.config={...zo.DEFAULT_OPTIONS,...a},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.debugGbufferMaps=this.config.debugGbufferMaps,this.tileSize=this.config.tileSize,this.state={isDenoising:!1,isLoading:!1,abortController:null},this.currentTZAUrl=null,this.unet=null,this.debugHelpers=null,this._lastAlbedoTexture=null,this._lastNormalTexture=null,this._initialize().catch(e=>{console.error(`Failed to initialize OIDNDenoiser:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{this._setupCanvas(),this._initDebugVisualization(),await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}_initDebugVisualization(){this.debugHelpers=null}_setupCanvas(){if(!this.output.getContext)throw Error(`Output must be a valid Canvas element`);this.output.willReadFrequently=!0,this.output.width=this.input.width,this.output.height=this.input.height,Object.assign(this.output.style,{position:`absolute`,top:`0`,left:`0`,width:`100%`,height:`100%`,borderRadius:`5px`,background:`repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 20px 20px`}),this.ctx=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0})}async _setupUNetDenoiser(){if(this.state.isLoading)return;this.state.isLoading=!0;let e=this._generateTzaUrl();if(this.currentTZAUrl===e&&this.unet){this.state.isLoading=!1;return}try{this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let t;if(this.isGPUMode&&this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,t=e?.device?e:void 0}this.unet=await(await Ro())(e,t,{aux:!0,hdr:!0,maxTileSize:this.tileSize}),this.currentTZAUrl=e,this.dispatchEvent({type:`loaded`}),console.log(`UNet denoiser loaded successfully:`,e)}catch(e){console.error(`Failed to load UNet denoiser:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}_generateTzaUrl(){let{BASE_URL:e,QUALITY_SUFFIXES:t}=zo;return`${e}rt_hdr_alb_nrm${t[this.quality]||``}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.debugGbufferMaps=this.config.debugGbufferMaps,this.tileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(zo.QUALITY_SUFFIXES,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(zo.QUALITY_SUFFIXES).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start(){if(!this.enabled||this.state.isDenoising||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.(),this.input.style.opacity=`0`;let t=performance.now()-e;console.log(`Denoising completed in ${t.toFixed(1)}ms (quality: ${this.quality})`)}return t}async execute(){if(!this.enabled||!this.unet)return!1;this.state.abortController=new AbortController,this.state.isDenoising=!0,this.input.style.opacity=`0`,this.output.style.display=`block`;try{return await this._executeUNet(),!0}catch(e){return e.name===`AbortError`?console.log(`Denoising was aborted`):console.error(`Denoising error:`,e),this.input.style.opacity=`1`,!1}finally{this.state.isDenoising=!1,this.state.abortController=null,this.dispatchEvent({type:`end`})}}async _executeUNet(){return this._executeUNetGPU()}async _executeUNetGPU(){let{width:e,height:t}=this.output;if(!this.getGPUTextures)return console.warn(`OIDNDenoiser: GPU mode enabled but getGPUTextures not provided`),!1;let n=this.getGPUTextures();if(!n?.color)return console.warn(`OIDNDenoiser: GPU textures not ready yet`),!1;let r=this.gpuDevice;if(!r)return console.warn(`OIDNDenoiser: gpuDevice not available`),!1;this._ensureGPUInputBuffers(e,t);let i=r.createCommandEncoder({label:`oidn-tex-to-buf`}),a=e*16,o=Math.ceil(a/256)*256,s=o!==a,c=[],l=(n,l)=>{if(!s)i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:l,offset:0,bytesPerRow:a,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});else{let s=r.createBuffer({size:o*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC});c.push(s),i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:s,offset:0,bytesPerRow:o,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});for(let e=0;e<t;e++)i.copyBufferToBuffer(s,e*o,l,e*a,a)}};l(n.color,this._gpuInputBuffers.color),l(n.albedo,this._gpuInputBuffers.albedo),l(n.normal,this._gpuInputBuffers.normal),r.queue.submit([i.finish()]);for(let e of c)e.destroy();this.getTransparentBackground()?await this._cacheInputAlpha(r,e,t):this._cachedAlpha=null,this.ctx.drawImage(this.input,0,0,e,t);let u={color:{data:this._gpuInputBuffers.color,width:e,height:t},albedo:{data:this._gpuInputBuffers.albedo,width:e,height:t},normal:{data:this._gpuInputBuffers.normal,width:e,height:t}};return this._executeWithAbortGPU(u)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t}}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0}}async _cacheInputAlpha(e,t,n){let r=t*n*16,i=e.createBuffer({label:`oidn-alpha-staging`,size:r,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),a=e.createCommandEncoder();a.copyBufferToBuffer(this._gpuInputBuffers.color,0,i,0,r),e.queue.submit([a.finish()]),await i.mapAsync(GPUMapMode.READ);let o=new Float32Array(i.getMappedRange()),s=t*n,c=new Uint8Array(s);for(let e=0;e<s;e++)c[e]=Math.min(Math.max(o[e*4+3]*255,0),255)|0;i.unmap(),i.destroy(),this._cachedAlpha=c,this._cachedAlphaWidth=t}_executeWithAbortGPU(e){return new Promise((t,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null,a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{await this._displayGPUOutput(e),t()}catch(e){r(e)}},progress:(e,t,r)=>{if(!e?.data||!r)return;this.dispatchEvent({type:`tileProgress`,tile:r,imageWidth:e.width,imageHeight:e.height});let i=this.gpuDevice,a=e.width,o=e.height,s=Math.min(r.width,a-r.x),c=Math.min(r.height,o-r.y);if(s<=0||c<=0)return;let l=s*16,u=s*c*16,d=i.createBuffer({size:u,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),f=i.createCommandEncoder();for(let t=0;t<c;t++){let n=((r.y+t)*a+r.x)*16,i=t*l;f.copyBufferToBuffer(e.data,n,d,i,l)}i.queue.submit([f.finish()]),d.mapAsync(GPUMapMode.READ).then(()=>{let e=new Float32Array(d.getMappedRange()),t=new ImageData(s,c),i=this.getExposure(),a=this.getSaturation(),o=jo.get(this.getToneMapping())||jo.get(n.ACESFilmicToneMapping),l=this._cachedAlpha,u=this._cachedAlphaWidth;for(let n=0,c=e.length;n<c;n+=4){let c=e[n]*i,d=e[n+1]*i,f=e[n+2]*i;if(a!==1&&($[0]=c,$[1]=d,$[2]=f,Io($,a),c=$[0],d=$[1],f=$[2]),o(c,d,f,1,$),t.data[n]=$[0]**Mo*255|0,t.data[n+1]=$[1]**Mo*255|0,t.data[n+2]=$[2]**Mo*255|0,l){let e=(n>>2)%s,i=(n>>2)/s|0;t.data[n+3]=l[(r.y+i)*u+r.x+e]}else t.data[n+3]=255}d.unmap(),d.destroy(),this.ctx.putImageData(t,r.x,r.y)})}})})}async _displayGPUOutput({data:e,width:t,height:r}){let i=this.gpuDevice;if(!i){console.error(`OIDNDenoiser: gpuDevice not available for output readback`);return}let a=t*r*4*4,o=i.createBuffer({label:`oidn-output-staging`,size:a,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),s=i.createCommandEncoder({label:`oidn-readback`});s.copyBufferToBuffer(e,0,o,0,a),i.queue.submit([s.finish()]),await o.mapAsync(GPUMapMode.READ);let c=new Float32Array(o.getMappedRange()),l=new ImageData(t,r),u=this.getExposure(),d=this.getSaturation(),f=jo.get(this.getToneMapping())||jo.get(n.ACESFilmicToneMapping),p=this._cachedAlpha;for(let e=0,t=c.length;e<t;e+=4){let t=c[e]*u,n=c[e+1]*u,r=c[e+2]*u;d!==1&&($[0]=t,$[1]=n,$[2]=r,Io($,d),t=$[0],n=$[1],r=$[2]),f(t,n,r,1,$),l.data[e]=$[0]**Mo*255|0,l.data[e+1]=$[1]**Mo*255|0,l.data[e+2]=$[2]**Mo*255|0,l.data[e+3]=p?p[e>>2]:255}o.unmap(),o.destroy(),this.ctx.putImageData(l,0,0)}abort(){!this.enabled||!this.state.isDenoising||(this.state.abortController?.abort(),this.input.style.opacity=`1`,this.state.isDenoising=!1,this.dispatchEvent({type:`end`}),console.log(`Denoising aborted`))}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this.output.width=e,this.output.height=t,this._setupUNetDenoiser().catch(e=>{console.error(`Failed to reinitialize denoiser after size change:`,e)})}_updateDebugVisualization(e){if(!e?.textures||e.textures.length<3)return;let t=this.debugHelpers&&(this._lastAlbedoTexture!==e.textures[2]||this._lastNormalTexture!==e.textures[1]);if(!this.debugHelpers||t){this.debugHelpers&&(this.debugHelpers.albedo?.dispose(),this.debugHelpers.normal?.dispose(),console.log(`OIDNDenoiser: Recreating debug helpers due to texture change`)),this.debugHelpers={albedo:Ja(this.renderer,e,{width:250,height:250,position:`bottom-right`,theme:`dark`,title:`OIDN Albedo`,autoUpdate:!1,textureIndex:2}),normal:Ja(this.renderer,e,{width:250,height:250,position:`bottom-left`,theme:`dark`,title:`OIDN Normal`,autoUpdate:!1,textureIndex:1})},this._lastAlbedoTexture=e.textures[2],this._lastNormalTexture=e.textures[1];let t=this.debugContainer||document.body;t.appendChild(this.debugHelpers.albedo),t.appendChild(this.debugHelpers.normal),this.debugHelpers.albedo.hide(),this.debugHelpers.normal.hide()}this.debugHelpers.albedo.update(),this.debugHelpers.normal.update()}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this.debugHelpers&&=(this.debugHelpers.albedo?.dispose(),this.debugHelpers.normal?.dispose(),null),this._lastAlbedoTexture=null,this._lastNormalTexture=null,this.output?.parentNode&&this.output.remove(),this.unet=null,this.ctx=null,this.state.abortController=null,this.removeAllListeners?.(),console.log(`OIDNDenoiser disposed`)}},Vo=`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,Ho={QUALITY_PRESETS:{fast:{2:Vo+`2x-spanx2-ch48.onnx`,4:Vo+`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:Vo+`2xNomosUni_compact_otf_medium.onnx`,4:Vo+`RealESRGAN_x4plus.onnx`},quality:{2:Vo+`2x-realesrgan-x2plus.onnx`,4:Vo+`4xNomos2_hq_mosr_fp32.onnx`}},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Uo=class extends n.EventDispatcher{constructor(e,t,r={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=r.getSourceCanvas||null,this.getGPUTextures=r.getGPUTextures||null,this.getExposure=r.getExposure||(()=>1),this.getToneMapping=r.getToneMapping||(()=>n.ACESFilmicToneMapping),this.getSaturation=r.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=r.scaleFactor||2,this.quality=r.quality||`fast`,this.tileSize=r.tileSize||Ho.TILE_SIZE,this._tileSizeOverride=!!r.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height}async _ensureSession(){let e=Ho.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/AIUpscalerWorker-D58dcMrY.js`).href:new URL(`assets/AIUpscalerWorker-D58dcMrY.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`}),await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))};this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Ho.SESSION_OPTIONS})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.input.style.opacity=`0`,this.output.style.display=`block`,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t);try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:r,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,r*a,i*a),t.isHDR&&(this._hdrToneMapFn=jo.get(this.getToneMapping())||jo.get(n.ACESFilmicToneMapping),this._hdrExposure=this.getExposure(),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Ho.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(r/l),d=Math.ceil(i/l),f=u*d,p=0;for(let n=0;n<d;n++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,r-c)),d=Math.min(n*l,Math.max(0,i-c)),m=Math.min(c,r-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:n,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:r*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i,s=t.createBuffer({size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),s.destroy(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,Io(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut),l[d]=this._tmOut[0]**+Mo,l[c+d]=this._tmOut[1]**+Mo,l[2*c+d]=this._tmOut[2]**+Mo}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:r,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=jo.get(this.getToneMapping())||jo.get(n.ACESFilmicToneMapping),l=this.getExposure(),u=this.getSaturation(),d=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,n=r[t]*l,i=r[t+1]*l,a=r[t+2]*l;u!==1&&(d[0]=n,d[1]=i,d[2]=a,Io(d,u),n=d[0],i=d[1],a=d[2]),c(n,i,a,1,d),s[t]=d[0]**+Mo*255+.5|0,s[t+1]=d[1]**+Mo*255+.5|0,s[t+2]=d[2]**+Mo*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Ho.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}async dispose(){this.abort(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,console.log(`AIUpscaler disposed`)}},Wo=class extends n.EventDispatcher{constructor({renderer:e,mainCanvas:t,scene:n,camera:r,stages:i,pipeline:a,getExposure:o,getSaturation:s,getTransparentBg:c}){super(),this.renderer=e,this.mainCanvas=t,this.denoiserCanvas=this._createDenoiserCanvas(t),this.scene=n,this.camera=r,this.pipeline=a,this._stages=i,this._getExposure=o,this._getSaturation=s,this._getTransparentBg=c,this.denoiser=null,this.upscaler=null,this._lastRenderWidth=0,this._lastRenderHeight=0}_createDenoiserCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.width=`${e.clientWidth}px`,n.style.height=`${e.clientHeight}px`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this.denoiser?.setSize(e,t),this.upscaler?.setBaseSize(e,t)}syncCanvasStyle(e,t){this.denoiserCanvas&&(this.denoiserCanvas.style.width=`${e}px`,this.denoiserCanvas.style.height=`${t}px`)}restoreBaseResolution(){if(!this.denoiserCanvas||!this._lastRenderWidth||!this._lastRenderHeight)return!1;let e=this.denoiserCanvas.width!==this._lastRenderWidth||this.denoiserCanvas.height!==this._lastRenderHeight;return this.denoiserCanvas.width=this._lastRenderWidth,this.denoiserCanvas.height=this._lastRenderHeight,e}setupDenoiser(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.denoiser=new Bo(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...V,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation(),getTransparentBackground:()=>this._getTransparentBg(),getMRTRenderTarget:()=>e?.storageTextures?.readTarget??null}),this.denoiser.enabled=V.enableOIDN,this.denoiser.addEventListener(`start`,()=>this.dispatchEvent({type:R.DENOISING_START})),this.denoiser.addEventListener(`end`,()=>this.dispatchEvent({type:R.DENOISING_END}))}setupUpscaler(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Uo(this.denoiserCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.upscalerQuality||`fast`,getSourceCanvas:()=>this.denoiser?.enabled?null:this.renderer.domElement,getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=V.enableUpscaler||!1,this.upscaler.addEventListener(`resolution_changed`,e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height})),this.upscaler.addEventListener(`start`,()=>this.dispatchEvent({type:R.UPSCALING_START})),this.upscaler.addEventListener(`progress`,e=>this.dispatchEvent({type:R.UPSCALING_PROGRESS,progress:e.progress})),this.upscaler.addEventListener(`end`,()=>this.dispatchEvent({type:R.UPSCALING_END}))}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.variance&&!this._isAdaptiveSamplingActive()&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),n.ssrc&&(n.ssrc.enabled=!1),this._clearDenoiserTextures(),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`ssrc`:n.ssrc&&(n.ssrc.enabled=!0);break;case`edgeaware`:n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e)}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,e?n.display?.setExposure(1):(n.display?.setExposure(t),n.display&&this.renderer&&(this.renderer.toneMappingExposure=1)))}setAdaptiveSamplingEnabled(e){let t=this._stages;t.adaptiveSampling&&(t.adaptiveSampling.enabled=e,t.adaptiveSampling.toggleHelper(!1)),e?t.variance&&(t.variance.enabled=!0):t.asvgf?.enabled||t.variance&&(t.variance.enabled=!1),!e&&this.pipeline?.context&&!t.asvgf?.enabled&&this.pipeline.context.removeTexture(`variance:output`)}onRenderComplete({isStillComplete:e,context:t}){(this.denoiser?.enabled||this.upscaler?.enabled)&&this.denoiserCanvas&&(this.denoiserCanvas.style.display=`block`);let n=()=>{e()&&this.upscaler?.enabled&&this.upscaler.start()};this.denoiser?.enabled?(this.denoiser.addEventListener(`end`,n,{once:!0}),this.denoiser.start()):(this.upscaler?.enabled&&this._stages.display&&t&&this._stages.display.render(t),n())}abort(e){e&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort(),this.denoiser&&(this.denoiser.enabled&&this.denoiser.abort(),this.denoiser.output&&(this.denoiser.output.style.display=`none`))}dispose(){this.denoiser&&=(this.denoiser.dispose(),null),this.upscaler&&=(this.upscaler.dispose(),null),this.denoiserCanvas?.parentNode&&(this.denoiserCanvas.parentNode.removeChild(this.denoiserCanvas),this.denoiserCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.toggleHeatmap?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e))}setSSRCParams(e){this._stages.ssrc?.updateParameters(e)}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}setAdaptiveSamplingParams(e){e.min!==void 0&&this._stages.pathTracer?.setAdaptiveSamplingMin(e.min),e.adaptiveSamplingMax!==void 0&&this._settings?.set(`adaptiveSamplingMax`,e.adaptiveSamplingMax),this._stages.adaptiveSampling?.setAdaptiveSamplingParameters(e)}toggleAdaptiveSamplingHelper(e){this._stages.adaptiveSampling?.toggleHelper(e)}setOIDNEnabled(e){this.denoiser&&(this.denoiser.enabled=e)}setOIDNQuality(e){this.denoiser?.updateQuality(e)}setOIDNTileHelper(e){this._setTileHelper(e)}setTileHelperEnabled(e){this._setTileHelper(e)}setTileHighlightEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e)}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setAdaptiveSampling(e){this._settings?.set(`useAdaptiveSampling`,e),this.setAdaptiveSamplingEnabled(e)}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_isAdaptiveSamplingActive(){return this._stages.adaptiveSampling?.enabled??!1}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:temporalColor`,`asvgf:variance`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`ssrc:output`].forEach(t=>e.removeTexture(t))}_applyASVGFPreset(e){let t=je[e];t&&this._stages.asvgf?.updateParameters(t)}},Go=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidth=2}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a;e.strokeStyle=this._borderColor,e.lineWidth=this._borderWidth,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},Ko=class{constructor(e,r,i){this.layer=`scene`,this.visible=!0,this._outlineNode=(0,g.outline)(r,i,{selectedObjects:[],edgeThickness:(0,o.uniform)(1),edgeGlow:(0,o.uniform)(0)}),this._displayWidth=1,this._displayHeight=1;let a=this._outlineNode.setSize.bind(this._outlineNode);this._outlineNode.setSize=()=>{a(this._displayWidth,this._displayHeight)};let s=(0,o.uniform)(3),c=(0,o.uniform)(new n.Color(16777215)),l=(0,o.uniform)(new n.Color(1640965)),{visibleEdge:u,hiddenEdge:d}=this._outlineNode,f=u.mul(c).add(d.mul(l)).mul(s);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,o.vec4)(f,1),this._material.blending=n.AdditiveBlending,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}render(e){if(this._outlineNode.selectedObjects.length===0)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}setSize(e,t){this._displayWidth=e,this._displayHeight=t,this._outlineNode.setSize(e,t)}show(){this.visible=!0}hide(){this.visible=!1}dispose(){this.visible=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad?.dispose()}},qo=class{constructor(e,t){this.renderer=e,this.camera=t,this._helpers=new Map,this._hudCanvas=document.createElement(`canvas`),this._hudCanvas.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`,this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Go;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`tile:changed`,e=>{e.renderMode===1&&e.tileBounds&&(s.setActiveTile(e.tileBounds),s.show())}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),i.addEventListener(R.RENDER_COMPLETE,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new Ko(this.renderer,t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(console.warn(`OverlayManager: helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){this._helperScene&&this._helperScene.render(this.renderer,this.camera);for(let e of this._helpers.values())e.visible&&e.layer===`scene`&&e.render&&e.render(this.renderer,this.camera);this.refreshHUD()}setSize(e,t){for(let n of this._helpers.values())n.setSize?.(e,t)}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(e.visible&&e.layer===`hud`&&e.render){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}let r=window.devicePixelRatio||1,i=e.clientWidth,a=e.clientHeight,o=Math.round(i*r),s=Math.round(a*r);(e.width!==o||e.height!==s)&&(e.width=o,e.height=s),t.clearRect(0,0,o,s),t.save(),t.scale(r,r);for(let e of this._helpers.values())e.visible&&e.layer===`hud`&&e.render&&e.render(t,i,a);t.restore(),e.style.display!==``&&(e.style.display=``)}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}},Jo=class extends n.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new n.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._tempVec=new n.Vector3,this._skinnedCache=null,this._totalTriangleCount=0,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this.wakeCallback=null}init(e,t,r,i,a){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=r,this._totalTriangleCount=a,this.mixer=new n.AnimationMixer(t);let o=i.map(e=>this.mixer.clipAction(e)),s=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!o.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return s(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new n.AnimationMixer(e),this._mixerRoot=e,o=i.map(e=>this.mixer.clipAction(e))),this.actions=o,this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let c=0;for(let e of r){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:c,count:i,uniqueVerts:a,indices:r}),this._skinnedCache.push(new Float32Array(a*3)),c+=i}this._posBuffer=new Float32Array(a*9);let l=r.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${r.length} meshes (${l} skinned), ${a} triangles`)}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:R.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:R.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:R.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:R.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?n.LoopRepeat:n.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._computePositions(),this._posBuffer}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._computePositions(),this._posBuffer}_computePositions(){let e=this._tempVec,t=this._posBuffer;this._mixerRoot.updateMatrixWorld(!0);for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n],{start:i,count:a,uniqueVerts:o,indices:s}=this._meshTriRanges[n],c=this._skinnedCache[n],l=r.matrixWorld;for(let t=0;t<o;t++)r.getVertexPosition(t,e),e.applyMatrix4(l),c[t*3]=e.x,c[t*3+1]=e.y,c[t*3+2]=e.z;if(s)for(let e=0;e<a;e++){let n=e*3,r=s[n]*3,a=s[n+1]*3,o=s[n+2]*3,l=(i+e)*9;t[l]=c[r],t[l+1]=c[r+1],t[l+2]=c[r+2],t[l+3]=c[a],t[l+4]=c[a+1],t[l+5]=c[a+2],t[l+6]=c[o],t[l+7]=c[o+1],t[l+8]=c[o+2]}else for(let e=0;e<a;e++){let n=e*3*3,r=(e*3+1)*3,a=(e*3+2)*3,o=(i+e)*9;t[o]=c[n],t[o+1]=c[n+1],t[o+2]=c[n+2],t[o+3]=c[r],t[o+4]=c[r+1],t[o+5]=c[r+2],t[o+6]=c[a],t[o+7]=c[a+1],t[o+8]=c[a+2]}}}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._skinnedCache=null,this._clipsCache=null}},Yo=class{constructor({camera:e,canvas:t,orbitControls:r,app:i}){this._app=i,this._orbitControls=r,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new n.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._tempVec=new n.Vector3,this._normalMatrix=new n.Matrix3,this._refitInFlight=!1,this._baselineComputed=!1,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e,t){this._meshes=e,this._meshTriRanges=[],this._skinnedCache=[],this._normalCache=[];let n=0;for(let t of e){let e=t.geometry,r=e.attributes.position,i=e.index?e.index.array:null,a=i?i.length/3:r.count/3,o=r.count;this._meshTriRanges.push({start:n,count:a,uniqueVerts:o,indices:i}),this._skinnedCache.push(new Float32Array(o*3)),this._normalCache.push(new Float32Array(o*3)),n+=a}this._posBuffer=new Float32Array(t*9),this._normalBuffer=new Float32Array(t*9)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e)}detach(){this._attached&&=(this._controls.detach(),null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:R.TRANSFORM_MODE_CHANGED,mode:e})}setSpace(e){this._controls.setSpace(e)}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:R.OBJECT_TRANSFORM_START}):(this._recomputeAndRefit(),this._app.dispatchEvent({type:R.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake()}_recomputeAndRefit(){if(!this._meshes||!this._posBuffer||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){if(!this._baselineComputed)this._computeAllPositions(),this._baselineComputed=!0;else for(let t of e)this._computeMeshPositions(t);this._refitInFlight=!0;try{this._app.refitBLASes(e,this._posBuffer,this._normalBuffer)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}_computeAllPositions(){for(let e=0;e<this._meshes.length;e++)this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._meshes[e],{start:n,count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._skinnedCache[e],s=this._normalCache[e],c=this._tempVec,l=this._posBuffer,u=this._normalBuffer;t.updateMatrixWorld(!0);let d=t.matrixWorld;this._normalMatrix.getNormalMatrix(d);let f=this._normalMatrix.elements,p=t.geometry.attributes.normal;for(let e=0;e<i;e++)if(t.getVertexPosition(e,c),c.applyMatrix4(d),o[e*3]=c.x,o[e*3+1]=c.y,o[e*3+2]=c.z,p){let t=p.getX(e),n=p.getY(e),r=p.getZ(e);s[e*3]=f[0]*t+f[3]*n+f[6]*r,s[e*3+1]=f[1]*t+f[4]*n+f[7]*r,s[e*3+2]=f[2]*t+f[5]*n+f[8]*r}if(a)for(let e=0;e<r;e++){let t=e*3,r=a[t]*3,i=a[t+1]*3,c=a[t+2]*3,d=(n+e)*9;l[d]=o[r],l[d+1]=o[r+1],l[d+2]=o[r+2],l[d+3]=o[i],l[d+4]=o[i+1],l[d+5]=o[i+2],l[d+6]=o[c],l[d+7]=o[c+1],l[d+8]=o[c+2],u[d]=s[r],u[d+1]=s[r+1],u[d+2]=s[r+2],u[d+3]=s[i],u[d+4]=s[i+1],u[d+5]=s[i+2],u[d+6]=s[c],u[d+7]=s[c+1],u[d+8]=s[c+2]}else for(let e=0;e<r;e++){let t=e*3*3,r=(e*3+1)*3,i=(e*3+2)*3,a=(n+e)*9;l[a]=o[t],l[a+1]=o[t+1],l[a+2]=o[t+2],l[a+3]=o[r],l[a+4]=o[r+1],l[a+5]=o[r+2],l[a+6]=o[i],l[a+7]=o[i+1],l[a+8]=o[i+2],u[a]=s[t],u[a+1]=s[t+1],u[a+2]=s[t+2],u[a+3]=s[r],u[a+4]=s[r+1],u[a+5]=s[r+2],u[a+6]=s[i],u[a+7]=s[i+1],u[a+8]=s[i+2]}}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._baselineComputed=!1}},Xo=class extends n.EventDispatcher{constructor(e,t={}){super(),this.canvas=e,this._autoResize=t.autoResize!==!1,this._showStats=t.showStats!==!1,this._statsContainer=t.statsContainer||null,this.settings=new bo(V),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this.pipeline=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new Jo,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this.pathTracerEnabled=!0,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this.completion=new mo,this._resizeDebounceTimer=null}async init(){return await this._initRenderer(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this._showStats&&this._initStats(),this.isInitialized=!0,console.log(`WebGPU Path Tracer App initialized`),this}animate(){if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this._stats?.update();return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>console.error(`Animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}if(this.needsReset&&=(this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.display.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}this.pipeline.render(),this.stages.pathTracer.isComplete||this.completion.updateTime(),xe({timeElapsed:this.completion.timeElapsed,samples:Se(this.stages.pathTracer)}),this.completion.isTimeLimitReached(this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context}),this.dispatchEvent({type:`RenderComplete`}),this.dispatchEvent({type:R.RENDER_COMPLETE}))}this._renderHelperOverlay(),this._stats?.update(),this.renderer.resolveTimestampsAsync?.(n.TimestampQuery.RENDER),this.renderer.resolveTimestampsAsync?.(n.TimestampQuery.COMPUTE)}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}wake(){!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation(),this._stats&&(this._stats.dom.style.display=`none`)}resume(){this._paused=!1,this.animationManagerId||this.animate(),this._stats&&(this._stats.dom.style.display=``)}reset(e=!1){if(this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`asvgf:reset`)),this.denoisingManager?.abort(this.canvas),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:R.RENDER_RESET})}dispose(){this.animationManager?.dispose(),this.stopAnimation(),ye(null),this.assetLoader&&this._onAssetLoaded&&this.assetLoader.removeEventListener(`load`,this._onAssetLoaded),this.transformManager?.dispose(),this.overlayManager?.dispose(),this._sceneHelpers?.clear(),this.denoisingManager?.dispose(),this.pipeline?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.renderer?.dispose(),this._stats&&=(this._stats.dom.remove(),null),clearTimeout(this._resizeDebounceTimer),window.removeEventListener(`resize`,this.resizeHandler),this.isInitialized=!1}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}async loadEnvironment(e){this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}async _loadWithSceneRebuild(e,t){this._loadingInProgress=!0;try{await e(),this._syncControlsAfterLoad(),await this.loadSceneData(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}finally{this._loadingInProgress=!1}}async loadSceneData(){this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1;let e=new oa(`loadSceneData`),t=this.meshScene.environment,n=null;return t?.image?.data&&(e.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=t,n=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>e.end(`Environment CDF build (worker)`))),e.start(`BVH build (SceneProcessor)`),await this._sdf.buildBVH(this.meshScene),e.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),e.start(`GPU data transfer`),this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,t)?(this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),e.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),e.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),e.end(`Material setup (TSL compile)`),n&&(z({status:`Finalizing environment map...`,progress:95}),await n,this.stages.pathTracer.environment.applyCDFResults()),e.start(`Apply settings`),this.settings.applyAll(),this.stages.display.setTransparentBackground(this.settings.get(`transparentBackground`)),e.end(`Apply settings`),e.print(),be(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0):!1}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,()=>{this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset()}),r}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0)return;this.renderer.setPixelRatio(1),this.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix(),this.denoisingManager?.syncCanvasStyle(e,t);let n=window.devicePixelRatio||1;this.overlayManager?.setSize(Math.round(e*n),Math.round(t*n));let r=this.denoisingManager?._lastRenderWidth??0,i=this.denoisingManager?._lastRenderHeight??0;e===r&&t===i||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this.pipeline?.setSize(e,t),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}setCanvasSize(e,t){this.denoisingManager?.syncCanvasStyle(e,t),!(e===0||t===0)&&(this.renderer.setPixelRatio(1),this.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix(),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t))}configureForMode(e,t={}){if(e===`results`){this.pauseRendering=!0,this.cameraManager.controls.enabled=!1,this.renderer?.domElement&&(this.renderer.domElement.style.display=`none`),this.denoisingManager?.denoiser?.output&&(this.denoisingManager.denoiser.output.style.display=`none`);return}let n=e===`final-render`,r=n?ze:G;this.cameraManager.controls.enabled=!n,this.settings.setMany({maxSamples:r.maxSamples,maxBounces:r.bounces,samplesPerPixel:r.samplesPerPixel,transmissiveBounces:r.transmissiveBounces},{silent:!0}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.setUniform(`enableAlphaShadows`,r.enableAlphaShadows??!1),this.stages.pathTracer?.tileManager?.setTileCount(r.tiles);let i=this.overlayManager?.getHelper(`tiles`);i&&(i.enabled=r.tilesHelper,r.tilesHelper||i.hide()),this.stages.pathTracer?.updateCompletionThreshold?.();let a=this.denoisingManager?.denoiser;a&&(a.abort(),a.enabled=r.enableOIDN,a.updateQuality(r.oidnQuality)),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&this.setCanvasSize(t.canvasWidth,t.canvasHeight),this.renderer?.domElement&&(this.renderer.domElement.style.display=`block`),this.denoisingManager?.denoiser?.output&&(this.denoisingManager.denoiser.output.style.display=`block`),this.needsReset=!1,this.pauseRendering=!1,this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager;return(e?.denoiser?.enabled||e?.upscaler?.enabled)&&e?.denoiserCanvas&&this.stages.pathTracer?.isComplete?e.denoiserCanvas:(this.stages.display&&this.pipeline?.context&&this.stages.display.render(this.pipeline.context),this.renderer.domElement)}screenshot(){let e=this.getCanvas();if(e)try{let t=e.toDataURL(`image/png`),n=document.createElement(`a`);n.href=t,n.download=`screenshot.png`,n.click()}catch(e){console.error(`Screenshot failed:`,e)}}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}setMaterialProperty(e,t,n){if(this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this.stages.pathTracer?.enableEmissiveTriangleSampling?.value){let r=this._sdf.updateMaterialEmissive(e,t,n);r&&this.stages.pathTracer.setEmissiveTriangleData(r.rawData,r.emissiveCount,r.totalPower)}this.reset()}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this.reset()}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(ye(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);let i=e.limits;this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:{maxBufferSize:i.maxBufferSize,maxStorageBufferBindingSize:i.maxStorageBufferBindingSize,maxColorAttachmentBytesPerSample:128}}),window.renderer=this.renderer,await this.renderer.init(),t.RectAreaLightNode.setLTC(r.RectAreaLightTexturesLib.init()),this.renderer.toneMapping=n.ACESFilmicToneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1)}_initCameraManager(){this.cameraManager=new xo(this.canvas)}_initScenes(){this.scene=new n.Scene,this.meshScene=new n.Scene,this._sceneHelpers=new E}_initAssetPipeline(){this._sdf=new Va,this.assetLoader=new _o(this.meshScene,this.cameraManager.camera,this.cameraManager.controls),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this.cameraManager.controls.addEventListener(`change`,()=>{this.needsReset=!0,this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new po(this.renderer,e||1,t||1),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.ssrc),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.adaptiveSampling),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.display);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this.pipeline.setSize(n,r)}_initManagers(){this.interactionManager=new ho({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new So(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),this._setupOverlayManager(),this.transformManager=new Yo({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this.cameraManager.addEventListener(`CameraSwitched`,e=>this.dispatchEvent(e)),this.cameraManager.addEventListener(R.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[R.DENOISING_START,R.DENOISING_END,R.UPSCALING_START,R.UPSCALING_PROGRESS,R.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[R.ANIMATION_STARTED,R.ANIMATION_PAUSED,R.ANIMATION_STOPPED]),this.animationManager.addEventListener(R.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this.animationManager.addEventListener(R.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e)}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion()}),this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&window.addEventListener(`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress){if(e.model)await this.loadSceneData();else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),be()}this.pauseRendering=!1,this.reset()}},this.assetLoader.addEventListener(`load`,this._onAssetLoaded),this.assetLoader.addEventListener(`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.assetLoader?.targetModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e,this._sdf.triangleCount),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:R.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes,this._sdf.triangleCount)}_createStages(){let e=this.settings.get(`adaptiveSamplingMax`),t=this.settings.get(`useAdaptiveSampling`);this.stages.pathTracer=new Ga(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new Ka(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new qa(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.ssrc=new co(this.renderer,{enabled:!1}),this.stages.asvgf=new Ya(this.renderer,{enabled:!1}),this.stages.variance=new Za(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new $a(this.renderer,{enabled:!1}),this.stages.adaptiveSampling=new no(this.renderer,{adaptiveSamplingMax:e,enabled:t}),this.stages.edgeFilter=new ro(this.renderer,{enabled:!1}),this.stages.autoExposure=new ao(this.renderer,{enabled:V.autoExposure??!1}),this.stages.display=new lo(this.renderer,{exposure:V.autoExposure?1:this.settings.get(`exposure`)??1,saturation:this.settings.get(`saturation`)??V.saturation})}_setupDenoisingManager(){this.denoisingManager=new Wo({renderer:this.renderer,mainCanvas:this.canvas,scene:this.scene,camera:this.cameraManager.camera,stages:{pathTracer:this.stages.pathTracer,asvgf:this.stages.asvgf,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,adaptiveSampling:this.stages.adaptiveSampling,edgeFilter:this.stages.edgeFilter,ssrc:this.stages.ssrc,autoExposure:this.stages.autoExposure,display:this.stages.display},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,getTransparentBg:()=>this.settings.get(`transparentBackground`)??!1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));if(t&&!e.isComplete)e.isComplete=!0;else if(!t&&e.isComplete){e.isComplete=!1,this.completion.resumeFromPause(),this.canvas.style.opacity=`1`;let t=this.denoisingManager?.denoiser?.output;t&&(t.style.display=`none`),this.dispatchEvent({type:R.RENDER_RESET}),this.wake()}}_initStats(){let e=this._statsContainer||this.canvas.parentElement||document.body;this._stats=D(this.renderer,e)}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:R.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render(),this.transformManager?.render(this.renderer)}_setupOverlayManager(){this.overlayManager=new qo(this.renderer,this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1})}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_forwardEvents(e,t){if(e)for(let n of t)e.addEventListener(n,e=>this.dispatchEvent(e))}},Zo=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=ze.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`final-render`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.denoiser?.enabled&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:R.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:R.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(xe({samples:Se(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(R.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(R.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app;return{maxSamples:e.settings.get(`maxSamples`),maxBounces:e.settings.get(`maxBounces`),samplesPerPixel:e.settings.get(`samplesPerPixel`),transmissiveBounces:e.settings.get(`transmissiveBounces`),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.denoiser?.enabled,oidnQuality:e.denoisingManager?.denoiser?.quality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;t.settings.setMany({maxSamples:e.maxSamples,maxBounces:e.maxBounces,samplesPerPixel:e.samplesPerPixel,transmissiveBounces:e.transmissiveBounces},{silent:!0}),t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.denoiser.enabled=e.oidnEnabled??!1,e.oidnQuality&&t.denoisingManager.denoiser.updateQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.animationManager?.stop(),t.reset(),t.wake()}};e.AF_DEFAULTS=Ie,e.ASVGF_QUALITY_PRESETS=je,e.AUTO_FOCUS_MODES=Fe,e.AnimationManager=Jo,e.BVH_LEAF_MARKERS=W,e.CAMERA_PRESETS=Pe,e.CAMERA_RANGES=Me,e.CameraManager=xo,e.DEFAULT_TEXTURE_MATRIX=Re,e.DenoisingManager=Wo,e.ENGINE_DEFAULTS=V,e.EngineEvents=R,e.FINAL_RENDER_CONFIG=ze,e.InteractionManager=ho,e.LightManager=So,e.MEMORY_CONSTANTS=Be,e.OverlayManager=qo,e.PREVIEW_RENDER_CONFIG=G,e.PathTracerApp=Xo,e.PipelineContext=uo,e.RenderPipeline=po,e.RenderSettings=bo,e.RenderStage=L,e.SKY_PRESETS=Ne,e.StageExecutionMode=I,e.TEXTURE_CONSTANTS=Le,e.TRIANGLE_DATA_LAYOUT=H,e.TransformManager=Yo,e.VideoRenderManager=Zo});
|
|
687
|
+
`),oo=class extends L{constructor(e,n={}){super(`AutoExposure`,{...n,executionMode:I.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,o.uniform)(n.keyValue??.18),this.minExposureU=(0,o.uniform)(n.minExposure??.1),this.maxExposureU=(0,o.uniform)(n.maxExposure??20),this.adaptSpeedBrightU=(0,o.uniform)(n.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,o.uniform)(n.adaptSpeedDark??.5),this.epsilonU=(0,o.uniform)(n.epsilon??1e-4),this.deltaTimeU=(0,o.uniform)(1/60),this.isFirstFrameU=(0,o.uniform)(1),this.previousExposureU=(0,o.uniform)(n.initialExposure??1),this.inputResW=(0,o.uniform)(1),this.inputResH=(0,o.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=n.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=n.FloatType,this._downsampleStorageTex.format=n.RGBAFormat,this._downsampleStorageTex.minFilter=n.NearestFilter,this._downsampleStorageTex.magFilter=n.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=n.FloatType,this._reductionStorageTex.format=n.RGBAFormat,this._reductionStorageTex.minFilter=n.NearestFilter,this._reductionStorageTex.magFilter=n.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationStorageTex=new t.StorageTexture(1,1),this._adaptationStorageTex.type=n.FloatType,this._adaptationStorageTex.format=n.RGBAFormat,this._adaptationStorageTex.minFilter=n.NearestFilter,this._adaptationStorageTex.magFilter=n.NearestFilter,this._adaptationTarget=new t.RenderTarget(1,1,e)}_buildCompute(){this._buildDownsampleCompute(),this._buildReductionCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,n=this.epsilonU,r=this.inputResW,i=this.inputResH;this._downsampleComputeNode=(0,o.Fn)(()=>{let a=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),s=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y)),c=r.div((0,o.float)(64)),l=i.div((0,o.float)(64)),u=(0,o.float)(a).mul(c),d=(0,o.float)(s).mul(l),f=(0,o.float)(0).toVar(),p=(0,o.float)(0).toVar();for(let t=0;t<4;t++)for(let r=0;r<4;r++){let i=qt((0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(u.add((0,o.float)((r+.5)/4).mul(c))),(0,o.int)(d.add((0,o.float)((t+.5)/4).mul(l))))).xyz);(0,o.If)(i.greaterThan(n),()=>{f.addAssign(i.add(n).log()),p.addAssign(1)})}(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(a),(0,o.uint)(s)),(0,o.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildReductionCompute(){let e=this._downsampleTarget.texture,t=this._reductionStorageTex,n=(0,o.workgroupArray)(`float`,256),r=(0,o.workgroupArray)(`float`,256);this._reductionComputeNode=(0,o.Fn)(()=>{let i=o.localId.x,a=(0,o.float)(0).toVar(),s=(0,o.float)(0).toVar();for(let t=0;t<16;t++){let n=i.mul(16).add(t),r=n.mod(64),c=n.div(64),l=(0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(r),(0,o.int)(c)));a.addAssign(l.x),s.addAssign(l.y)}n.element(i).assign(a),r.element(i).assign(s);for(let e=256/2;e>=1;e=Math.floor(e/2))(0,o.workgroupBarrier)(),(0,o.If)(i.lessThan((0,o.uint)(e)),()=>{n.element(i).addAssign(n.element(i.add((0,o.uint)(e)))),r.element(i).addAssign(r.element(i.add((0,o.uint)(e))))});(0,o.workgroupBarrier)(),(0,o.If)(i.equal((0,o.uint)(0)),()=>{let e=n.element((0,o.uint)(0)),i=r.element((0,o.uint)(0)),a=(0,o.max)(i,(0,o.float)(1)),s=e.div(a),c=s.exp();(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(0),(0,o.uint)(0)),(0,o.vec4)(c,i,s,1)).toWriteOnly()})})().compute(1,[256,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationStorageTex,n=this.keyValueU,r=this.minExposureU,i=this.maxExposureU,a=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,o.Fn)(()=>{let d=(0,o.textureLoad)(e,(0,o.ivec2)((0,o.int)(0),(0,o.int)(0))).x,f=ao(d,u,n,r,i,a,s,c,l);(0,o.textureStore)(t,(0,o.uvec2)((0,o.uint)(0),(0,o.uint)(0)),f).toWriteOnly()})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>{e&&(e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark))})}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=this.isFirstFrame?1:0,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._reductionComputeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),this.renderer.copyTextureToTexture(this._adaptationStorageTex,this._adaptationTarget.texture),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.readRenderTargetPixelsAsync(this._adaptationTarget,0,0,1,1).then(t=>{this._pendingReadback=!1,e===this._readbackGeneration&&this._applyReadback(t)}).catch(()=>{this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark)}dispose(){this._downsampleComputeNode?.dispose(),this._reductionComputeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._adaptationStorageTex?.dispose(),this._adaptationTarget?.dispose()}};function so({colorTexNode:e,ndTexNode:t,motionTexNode:n,readCacheTexNode:r,readPrevNDTexNode:i,writeCacheTex:a,writePrevNDTex:s,resW:c,resH:l,temporalAlpha:u,phiNormal:d,phiDepth:f,maxHistory:p,framesSinceReset:m}){return(0,o.Fn)(()=>{let h=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),g=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(h.lessThan((0,o.int)(c)).and(g.lessThan((0,o.int)(l))),()=>{let _=(0,o.ivec2)(h,g),v=(0,o.textureLoad)(e,_).xyz,y=(0,o.textureLoad)(t,_),b=(0,o.vec4)(v,1).toVar();(0,o.If)(m.greaterThan((0,o.int)(0)),()=>{let e=(0,o.textureLoad)(n,_),t=e.w.greaterThan(.5),a=(0,o.float)(h).sub(e.x.mul(c)),s=(0,o.float)(g).sub(e.y.mul(l)),m=a.greaterThanEqual(0).and(a.lessThan((0,o.float)(c))).and(s.greaterThanEqual(0)).and(s.lessThan((0,o.float)(l)));(0,o.If)(t.and(m),()=>{let e=(0,o.ivec2)((0,o.int)(a).clamp((0,o.int)(0),(0,o.int)(c).sub(1)),(0,o.int)(s).clamp((0,o.int)(0),(0,o.int)(l).sub(1))),t=y.xyz.mul(2).sub(1),n=(0,o.textureLoad)(i,e),m=on(t,n.xyz.mul(2).sub(1),y.w,n.w,d,f);(0,o.If)(m.greaterThan(.01),()=>{let t=(0,o.textureLoad)(r,e),n=t.xyz,i=t.w,a=(0,o.mix)(n,v,(0,o.min)((0,o.max)(u,(0,o.float)(1).div(i.add(1))).div((0,o.max)(m,(0,o.float)(.1))),1)),s=(0,o.min)(i.add(1),p);b.assign((0,o.vec4)(a,s))}).Else(()=>{b.assign((0,o.vec4)(v,1))})}).Else(()=>{b.assign((0,o.vec4)(v,1))})}),(0,o.textureStore)(a,(0,o.uvec2)(h,g),b).toWriteOnly(),(0,o.textureStore)(s,(0,o.uvec2)(h,g),y).toWriteOnly()})})}function co({colorTexNode:e,ndTexNode:t,readCacheTexNode:n,outputTex:r,resW:i,resH:a,spatialRadius:s,spatialWeight:c,phiNormal:l,phiDepth:u}){let d=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];return(0,o.Fn)(()=>{let f=(0,o.int)(o.workgroupId.x).mul(8).add((0,o.int)(o.localId.x)),p=(0,o.int)(o.workgroupId.y).mul(8).add((0,o.int)(o.localId.y));(0,o.If)(f.lessThan((0,o.int)(i)).and(p.lessThan((0,o.int)(a))),()=>{let m=(0,o.ivec2)(f,p),h=(0,o.textureLoad)(n,m),g=h.xyz,_=h.w,v=(0,o.textureLoad)(t,m),y=v.xyz.mul(2).sub(1),b=(0,o.float)(1).sub(_.div(16).clamp(0,1)),x=c.mul(b),S=(0,o.vec3)(g).toVar(),C=(0,o.float)(1).toVar();for(let e=0;e<d.length;e++){let[r,c]=d[e],m=(0,o.ivec2)(f.add((0,o.int)(s).mul(r)).clamp((0,o.int)(0),(0,o.int)(i).sub(1)),p.add((0,o.int)(s).mul(c)).clamp((0,o.int)(0),(0,o.int)(a).sub(1))),h=(0,o.textureLoad)(n,m).xyz,g=(0,o.textureLoad)(t,m),_=on(y,g.xyz.mul(2).sub(1),v.w,g.w,l,u);S.addAssign(h.mul(_)),C.addAssign(_)}let w=(0,o.mix)(g,S.div((0,o.max)(C,1e-4)),x),T=(0,o.textureLoad)(e,m).w;(0,o.textureStore)(r,(0,o.uvec2)(f,p),(0,o.vec4)(w,T)).toWriteOnly()})})}var lo=class extends L{constructor(e,r={}){super(`SSRC`,{...r,executionMode:I.PER_CYCLE}),this.renderer=e,this.resW=(0,o.uniform)(1),this.resH=(0,o.uniform)(1),this.temporalAlpha=(0,o.uniform)(r.temporalAlpha??.1),this.phiNormal=(0,o.uniform)(r.phiNormal??128),this.phiDepth=(0,o.uniform)(r.phiDepth??.5),this.maxHistory=(0,o.uniform)(r.maxHistory??128),this.spatialRadius=(0,o.uniform)(r.spatialRadius??4,`int`),this.spatialWeight=(0,o.uniform)(r.spatialWeight??.4),this._framesSinceReset=(0,o.uniform)(0,`int`),this._colorTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._readCacheTexNode=new t.TextureNode,this._readPrevNDTexNode=new t.TextureNode,this._readPass1CacheTexNode=new t.TextureNode,this._cacheTexA=this._createStorageTex(1,1,n.NearestFilter),this._cacheTexB=this._createStorageTex(1,1,n.NearestFilter),this._prevNDTexA=this._createStorageTex(1,1,n.NearestFilter),this._prevNDTexB=this._createStorageTex(1,1,n.NearestFilter),this._outputTex=this._createStorageTex(1,1,n.LinearFilter),this._currentPingPong=0,this._dispatchX=1,this._dispatchY=1,this._buildComputeNodes()}setupEventListeners(){this.on(`pipeline:reset`,()=>this._resetCache()),this.on(`camera:moved`,()=>this._resetCache())}render(e){if(!this.enabled){e.removeTexture(`ssrc:output`);return}let t=e.getTexture(`pathtracer:color`);if(t?.image){let{width:e,height:n}=t.image;(e!==this._cacheTexA.image.width||n!==this._cacheTexA.image.height)&&this.setSize(e,n)}let n=e.getTexture(`pathtracer:normalDepth`);if(!n||!t)return;this._colorTexNode.value=t,this._ndTexNode.value=n;let r=e.getTexture(`motionVector:screenSpace`);r&&(this._motionTexNode.value=r);let[i,a,o]=this._currentPingPong===0?[this._cacheTexB,this._cacheTexA,this._prevNDTexB]:[this._cacheTexA,this._cacheTexB,this._prevNDTexA];this._readCacheTexNode.value=i,this._readPrevNDTexNode.value=o,this.renderer.compute(this._currentPingPong===0?this._pass1NodeA:this._pass1NodeB),this._readPass1CacheTexNode.value=a,this.renderer.compute(this._pass2Node),this._framesSinceReset.value=Math.min(this._framesSinceReset.value+1,9999),e.setTexture(`ssrc:output`,this._outputTex),this._currentPingPong=1-this._currentPingPong}reset(){this._resetCache()}setSize(e,t){if(e<1||t<1)return;this._cacheTexA.setSize(e,t),this._cacheTexB.setSize(e,t),this._prevNDTexA.setSize(e,t),this._prevNDTexB.setSize(e,t),this._outputTex.setSize(e,t),this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8);let n=[this._dispatchX,this._dispatchY,1];this._pass1NodeA&&this._pass1NodeA.setCount(n),this._pass1NodeB&&this._pass1NodeB.setCount(n),this._pass2Node&&this._pass2Node.setCount(n),this._resetCache()}dispose(){this._pass1NodeA?.dispose(),this._pass1NodeB?.dispose(),this._pass2Node?.dispose(),this._cacheTexA.dispose(),this._cacheTexB.dispose(),this._prevNDTexA.dispose(),this._prevNDTexB.dispose(),this._outputTex.dispose()}updateParameters(e){e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth),e.maxHistory!==void 0&&(this.maxHistory.value=e.maxHistory),e.spatialRadius!==void 0&&(this.spatialRadius.value=e.spatialRadius),e.spatialWeight!==void 0&&(this.spatialWeight.value=e.spatialWeight)}_createStorageTex(e,r,i){let a=new t.StorageTexture(e,r);return a.type=n.HalfFloatType,a.format=n.RGBAFormat,a.minFilter=i,a.magFilter=i,a}_resetCache(){this._currentPingPong=0,this._framesSinceReset.value=0}_buildComputeNodes(){let e={colorTexNode:this._colorTexNode,ndTexNode:this._ndTexNode,motionTexNode:this._motionTexNode,readCacheTexNode:this._readCacheTexNode,readPrevNDTexNode:this._readPrevNDTexNode,resW:this.resW,resH:this.resH,temporalAlpha:this.temporalAlpha,phiNormal:this.phiNormal,phiDepth:this.phiDepth,maxHistory:this.maxHistory},t=so({...e,writeCacheTex:this._cacheTexA,writePrevNDTex:this._prevNDTexA,framesSinceReset:this._framesSinceReset}),n=so({...e,writeCacheTex:this._cacheTexB,writePrevNDTex:this._prevNDTexB,framesSinceReset:this._framesSinceReset}),r=[this._dispatchX,this._dispatchY,1],i=[8,8,1];this._pass1NodeA=t().compute(r,i),this._pass1NodeB=n().compute(r,i),this._pass2Node=co({colorTexNode:this._colorTexNode,ndTexNode:this._ndTexNode,readCacheTexNode:this._readPass1CacheTexNode,outputTex:this._outputTex,resW:this.resW,resH:this.resH,spatialRadius:this.spatialRadius,spatialWeight:this.spatialWeight,phiNormal:this.phiNormal,phiDepth:this.phiDepth})().compute(r,i)}},uo=class extends L{constructor(e,r={}){super(`Display`,{...r,executionMode:I.ALWAYS}),this.renderer=e,this.exposure=(0,o.uniform)(r.exposure??1),this.saturation=(0,o.uniform)(r.saturation??1),this._transparentBackground=(0,o.uniform)(0,`int`),this._displayTexNode=new t.TextureNode;let i=this._displayTexNode.sample((0,o.uv)()),a=i.xyz.mul(this.exposure),s=(0,o.mix)((0,o.vec3)((0,o.dot)(a,Ht)),a,this.saturation),c=(0,o.select)(this._transparentBackground,i.w,1);this.displayMaterial=new t.MeshBasicNodeMaterial,this.displayMaterial.colorNode=(0,o.vec4)(s,c),this.displayMaterial.blending=n.NoBlending,this.displayMaterial.toneMapped=!0,this.displayQuad=new t.QuadMesh(this.displayMaterial)}_resolveDisplayTexture(e){return e.getTexture(`bloom:output`)||e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`ssrc:output`)||e.getTexture(`pathtracer:color`)}render(e){if(!this.enabled)return;let t=this._resolveDisplayTexture(e);t&&(this._displayTexNode.value=t,this.renderer.setRenderTarget(null),this.displayQuad.render(this.renderer))}setExposure(e){this.exposure.value=e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=e?1:0}dispose(){this.displayMaterial?.dispose(),this.displayQuad?.dispose()}},fo=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableAdaptiveSampling:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},po=class extends n.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},mo=class{constructor(e,t,n){this.renderer=e,this.width=t,this.height=n,this.stages=[],this.context=new fo,this.eventBus=new po,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(t.render(this.context,e),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){console.error(`[Pipeline] Error in stage '${t.name}':`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){console.error(`[Pipeline] Error resetting stage '${e.name}':`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}},ho=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t){return e===`time`&&t>0&&this.timeElapsed>=t}isLimitReached(e,t,n){return e?this.isTimeLimitReached(t,n)?!0:e.frameCount>=e.completionThreshold:!1}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},go=class extends n.EventDispatcher{constructor({scene:e,camera:t,canvas:r,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=r,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new n.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:R.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=e.distance;this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:t/this.assetLoader.getSceneScale(),worldDistance:t})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new n.Mesh(new n.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new n.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object,t=this.selectedObject;t&&t.uuid===e.uuid?this.dispatchEvent({type:`objectDeselected`,object:e,uuid:e.uuid}):this.dispatchEvent({type:`objectSelected`,object:e,uuid:e.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:R.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:R.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:`focusChanged`,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:R.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},_o={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usdz:{type:`model`,name:`Universal Scene Description`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`}},vo=class extends n.EventDispatcher{constructor(e,t,n){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null}setRenderer(e){this.renderer=e}getFileFormat(e){return _o[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);z({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usdz`:return await this.loadUSDZFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let e=await this.loadEnvironment(n);return this.dispatchEvent({type:`load`,texture:e,filename:t}),e}finally{URL.revokeObjectURL(n)}}async loadEnvironment(e){try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:e});let t;if(e.startsWith(`blob:`))t=await this.loadEnvironmentFromBlob(e);else{let n=e.split(`.`).pop().toLowerCase();t=await this.loadEnvironmentByExtension(e,n)}return t.generateMipmaps=!0,this.applyEnvironmentToScene(t),this.dispatchEvent({type:`load`,texture:t}),t}catch(t){throw console.error(`Error loading environment:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(e,t){let r;return t===`hdr`||t===`exr`?r=await(t===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new c.HDRLoader().setDataType(n.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new d.EXRLoader().setDataType(n.FloatType))).loadAsync(e):(this.loaderCache.texture||(this.loaderCache.texture=new n.TextureLoader),r=await this.loaderCache.texture.loadAsync(e)),r.mapping=n.EquirectangularReflectionMapping,r.minFilter=n.LinearFilter,r.magFilter=n.LinearFilter,r}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async loadArchiveFromFile(e,t){try{let n=await this.readFileAsArrayBuffer(e),r=(0,m.unzipSync)(new Uint8Array(n));return await this.processObjMtlPairsInZip(r,t)||await this.findAndLoadModelFromZip(r,t)}catch(e){throw console.error(`Error loading ZIP archive:`,e),e}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(_o[n]&&_o[n].type===`model`)return console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e)}throw Error(`No supported model files found in the ZIP archive`)}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usdz`:o=await this.loadUSDZFromArrayBuffer(e.buffer,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,r,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new n.LoadingManager,o=r.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();return s.manager=a,await new Promise((t,n)=>{s.parse(e,``,e=>{this.targetModel&&B(this.targetModel),this.targetModel=e.scene,this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}else return await this.loadGLBFromArrayBuffer(t.buffer,r)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.targetModel&&B(this.targetModel),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async loadMtlFromZip(e,t,r){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(r[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(r[e]),o=new n.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,r));let s=new t(o).parse(a,i);return s.preload(),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,r,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new n.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,r,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);f.preload();let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.targetModel&&B(this.targetModel),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){if(this.loaderCache.gltf)return this.loaderCache.gltf;let e=new l.DRACOLoader;e.setDecoderConfig({type:`js`}),e.setDecoderPath(`https://www.gstatic.com/draco/v1/decoders/`);let t=new u.KTX2Loader;t.setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`),this.renderer&&(t.detectSupport(this.renderer),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),this.loaderCache.ktx2=t;let n=new s.GLTFLoader;return n.setDRACOLoader(e),n.setKTX2Loader(t),n.setMeshoptDecoder(p.MeshoptDecoder),this.loaderCache.gltf=n,n}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(e){try{let t=await this.createGLTFLoader();z({status:`Loading Model...`,progress:2});let n=await t.loadAsync(e);return z({status:`Processing Data...`,progress:10}),this.targetModel&&B(this.targetModel),this.targetModel=n.scene,this.animations=n.animations||[],await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n.scene,filename:e.split(`/`).pop()}),n}catch(t){throw console.error(`Error loading model:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t}}async loadGLBFromArrayBuffer(e,t=`model.glb`){try{let n=await this.createGLTFLoader();z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this.targetModel&&B(this.targetModel),this.targetModel=r.scene,this.animations=r.animations||[],z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let r=new n.Mesh(this.loaderCache.stl.parse(e),new n.MeshStandardMaterial);return r.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let r=this.loaderCache.ply.parse(e),i;if(r.index!==null)i=new n.Mesh(r,new n.MeshStandardMaterial);else{let e=new n.PointsMaterial({size:.01});e.vertexColors=r.hasAttribute(`color`),i=new n.Points(r,e)}return i.name=t,this.targetModel&&B(this.targetModel),this.targetModel=i,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.targetModel&&B(this.targetModel),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDZFromArrayBuffer(e,t=`model.usdz`){try{if(z({isLoading:!0,status:`Processing USDZ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usdz){let{USDZLoader:e}=await import(`three/examples/jsm/loaders/USDZLoader.js`);this.loaderCache.usdz=new e}let n=this.loaderCache.usdz.parse(e);return n.name=t,this.targetModel&&B(this.targetModel),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USDZ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){return e.name=e.name||t,this.targetModel&&B(this.targetModel),this.targetModel=e,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e,filename:t}),e}async onModelLoad(e){let t=new sa(`onModelLoad`);t.start(`Camera extraction`);let r=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new n.Box3().setFromObject(e),a=i.getCenter(new n.Vector3),o=i.getSize(new n.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new n.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:r,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[];e.traverse(e=>{let r=e.userData;if(e.isRectAreaLight&&!t.includes(e.uuid)&&t.push(e.uuid),e.name.startsWith(`RectAreaLightPlaceholder`)&&r.name&&r.type===`RectAreaLight`){let i=new n.RectAreaLight(new n.Color(...r.color),r.intensity*.1/Math.PI,r.width,r.height);i.position.z=-2,i.name=r.name,e.add(i),t.push(i.uuid)}if(e.isMesh&&Array.isArray(e.material)){console.log(`Found multi-material mesh:`,e.name);let t=(0,f.createMeshesFromMultiMaterialMesh)(e);e.parent&&(e.parent.add(t),e.parent.remove(e))}})}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new n.Mesh(new n.CircleGeometry,new n.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(_o))r.type===e&&(t[n]=r);return t}return _o}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},super.dispose(),this.targetModel&&=(B(this.targetModel),null),console.log(`AssetLoader resources disposed`)}removeAllEventListeners(){super.dispose()}},yo={maxBounces:{uniform:`maxBounces`,reset:!0},samplesPerPixel:{uniform:`samplesPerPixel`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},adaptiveSamplingMax:{uniform:`adaptiveSamplingMax`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},bo={bounces:`maxBounces`,adaptiveSampling:`useAdaptiveSampling`,debugMode:`visMode`},xo=class extends n.EventDispatcher{constructor(e=V){super(),this._values=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind({stages:e,resetCallback:t,reconcileCompletion:n}){this._pathTracer=e.pathTracer,this._resetCallback=t,this._delegates={},this._handlers=this._buildHandlers(e,n)}_buildHandlers(e,t){return{handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.display?.setTransparentBackground(t)},handleExposure:t=>{e.autoExposure?.enabled||e.display?.setExposure(t)},handleSaturation:t=>{e.display?.setSaturation(t)},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t)},handleMaxSamples:n=>{e.pathTracer?.setUniform(`maxSamples`,n),e.pathTracer?.updateCompletionThreshold(),t?.()},handleRenderTimeLimit:()=>{t?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)}}}set(e,t,{reset:n,silent:r}={}){let i=this._values.get(e);if(i===t)return;this._values.set(e,t);let a=yo[e];a&&(this._applyRoute(a,t,i),(n===void 0?a.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:R.SETTING_CHANGED,key:e,value:t,prev:i}))}setMany(e,{silent:t}={}){let n=!1;for(let[r,i]of Object.entries(e)){let e=this._values.get(r);if(e===i)continue;this._values.set(r,i);let a=yo[r];a&&(this._applyRoute(a,i,e),(a.reset??!0)&&(n=!0),t||this.dispatchEvent({type:R.SETTING_CHANGED,key:r,value:i,prev:e}))}n&&this._resetCallback?.()}get(e){return this._values.get(e)}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=yo[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(yo))t in e&&this._values.set(t,e[t]);for(let[t,n]of Object.entries(bo))t in e&&this._values.set(n,e[t])}},So=class extends n.EventDispatcher{constructor(e){super();let t=e.clientWidth,r=e.clientHeight;this.camera=new n.PerspectiveCamera(60,t/r||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this.autoFocusMode=Ie.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Ie.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null}setCameras(e){this.cameras=e}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n}){this._onResize=e,this._onReset=t,this._getSettings=n}switchCamera(e,t,r,i){if(t??=this._getSettings?.(`focusDistance`),r??=this._onResize,i??=this._onReset,!(!this.cameras||this.cameras.length===0)){if((e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let r=this.cameras[e];if(this.camera.position.copy(r.position),this.camera.quaternion.copy(r.quaternion),this.camera.fov=r.fov,this.camera.near=r.near,this.camera.far=r.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=new n.Vector3(0,0,-1).applyQuaternion(r.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i),this.controls.update()}}r?.(),i?.(),this.dispatchEvent({type:`CameraSwitched`,cameraIndex:e})}}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let{meshScene:t,assetLoader:n,floorPlane:r,currentFocusDistance:i,pathTracer:a,setFocusDistance:o,softReset:s,hardReset:c}=e||this._afContext||{};if(!t||this.autoFocusMode===`manual`)return;let l=a;if(l?.isReady&&l.renderMode?.value===1&&l.frameCount>0&&!l.isComplete)return;let u=this.afScreenPoint.x*2-1,d=-(this.afScreenPoint.y*2-1),f=this.interactionManager?.raycaster;if(!f)return;f.setFromCamera({x:u,y:d},this.camera);let p=f.intersectObjects(t.children,!0).find(e=>e.object!==this.interactionManager?.focusPointIndicator&&e.object!==r&&!e.object.name.includes(`Helper`)&&e.object.type===`Mesh`),m;if(p)m=p.distance,this._lastValidFocusDistance=m;else if(this._lastValidFocusDistance!==null)m=this._lastValidFocusDistance;else{let e=n?.getSceneScale()||1;m=Ie.FALLBACK_DISTANCE*e,this._lastValidFocusDistance=m}let h=this._afPointDirty;this._afPointDirty=!1,h||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(m-this._smoothedFocusDistance)/this._smoothedFocusDistance>Ie.SNAP_THRESHOLD?this._smoothedFocusDistance=m:this._smoothedFocusDistance+=this.afSmoothingFactor*(m-this._smoothedFocusDistance);let g=i,_=this._smoothedFocusDistance;if(h||g===0||Math.abs(_-g)/Math.max(g,.001)>.001){o(_);let e=n?.getSceneScale()||1;this.dispatchEvent({type:R.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Ie.RESET_THRESHOLD&&s?.()}}setInteractionManager(e){this.interactionManager=e}initAutoFocus({meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,settings:i,softReset:a,hardReset:o}){this._afContext={meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,setFocusDistance:e=>i.set(`focusDistance`,e,{silent:!0}),softReset:a,hardReset:o},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>i.get(`focusDistance`)})}dispose(){this.controls?.dispose()}},Co=class extends n.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:100,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:300,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:500,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let r;if(e===`DirectionalLight`)r=new n.DirectionalLight(t.color,t.intensity),r.position.fromArray(t.position);else if(e===`PointLight`)r=new n.PointLight(t.color,t.intensity),r.position.fromArray(t.position);else if(e===`SpotLight`){r=new n.SpotLight(t.color,t.intensity),r.position.fromArray(t.position),r.angle=n.MathUtils.degToRad(t.angle);let e=new n.Object3D;this.scene.add(e),r.target=e}else e===`RectAreaLight`&&(r=new n.RectAreaLight(t.color,t.intensity,t.width,t.height),r.position.fromArray(t.position),r.lookAt(0,0,0));let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return r.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(r),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(r)}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights()}transferSceneLights(e){this._removeAllLights();let t=e.getObjectsByProperty(`isLight`,!0);if(!t||t.length===0){this.updateLights();return}for(let e of t){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let r=new n.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(r.position),this.scene.add(r),t.target=r}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}_removeAllLights(){this.scene.getObjectsByProperty(`isLight`,!0).forEach(e=>{e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0&&(t=n.MathUtils.radToDeg(e.angle));let r={uuid:e.uuid,name:e.name,type:e.type,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t};if(e.type===`RectAreaLight`){r.width=e.width,r.height=e.height;let t=e.getWorldDirection(e.position.clone());r.target=[e.position.x+t.x,e.position.y+t.y,e.position.z+t.z]}else e.type===`SpotLight`&&e.target&&(r.target=[e.target.position.x,e.target.position.y,e.target.position.z]);return r}},wo=e=>Math.min(Math.max(e,0),1);function To(e,t,n,r,i){i[0]=wo(e),i[1]=wo(t),i[2]=wo(n)}function Eo(e,t,n,r,i){i[0]=wo(e*r),i[1]=wo(t*r),i[2]=wo(n*r)}function Do(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=wo(e/(e+1)),i[1]=wo(t/(t+1)),i[2]=wo(n/(n+1))}function Oo(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function ko(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=wo(1.60475*a-.53108*o-.07367*s),i[1]=wo(-.10208*a+1.10813*o-.00605*s),i[2]=wo(-.00327*a-.07276*o+1.07602*s)}function Ao(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=wo((Math.log2(Math.max(c,1e-10))-d)/f),l=wo((Math.log2(Math.max(l,1e-10))-d)/f),u=wo((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=wo(1.6605*m-.5876*h-.0728*g),i[1]=wo(-.1246*m+1.1329*h-.0083*g),i[2]=wo(-.0182*m-.1006*h+1.1187*g)}function jo(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var Mo=new Map([[n.NoToneMapping,To],[n.LinearToneMapping,Eo],[n.ReinhardToneMapping,Do],[n.CineonToneMapping,Oo],[n.ACESFilmicToneMapping,ko],[n.AgXToneMapping,Ao],[n.NeutralToneMapping,jo]]),No=1/2.2,Po=.2126,Fo=.7152,Io=.0722;function Lo(e,t){if(t===1)return;let n=e[0]*Po+e[1]*Fo+e[2]*Io;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}var Ro=null;async function zo(){return Ro||=(await import(`oidn-web`)).initUNetFromURL,Ro}var $=new Float32Array(3),Bo={BASE_URL:`https://cdn.jsdelivr.net/npm/denoiser/tzas/`,QUALITY_SUFFIXES:{fast:`_small`,balance:``,high:`_large`},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,debugGbufferMaps:!0,tileSize:256}},Vo=class extends n.EventDispatcher{constructor(e,t,r,i,a={}){if(super(),!e||!t||!r||!i)throw Error(`OIDNDenoiser requires output canvas, renderer, scene, and camera`);this.renderer=t,this.scene=r,this.camera=i,this.input=t.domElement,this.output=e,this.debugContainer=a.debugContainer||null,this.extractGBufferData=a.extractGBufferData||null,this.getMRTRenderTarget=a.getMRTRenderTarget||null,this.backendParamsGetter=a.backendParams||null,this.getGPUTextures=a.getGPUTextures||null,this.getExposure=a.getExposure||(()=>1),this.getToneMapping=a.getToneMapping||(()=>n.ACESFilmicToneMapping),this.getSaturation=a.getSaturation||(()=>1),this.getTransparentBackground=a.getTransparentBackground||(()=>!1),this.isGPUMode=!!this.backendParamsGetter,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._cachedAlpha=null,this._cachedAlphaWidth=0,this.config={...Bo.DEFAULT_OPTIONS,...a},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.debugGbufferMaps=this.config.debugGbufferMaps,this.tileSize=this.config.tileSize,this.state={isDenoising:!1,isLoading:!1,abortController:null},this.currentTZAUrl=null,this.unet=null,this.debugHelpers=null,this._lastAlbedoTexture=null,this._lastNormalTexture=null,this._initialize().catch(e=>{console.error(`Failed to initialize OIDNDenoiser:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{this._setupCanvas(),this._initDebugVisualization(),await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}_initDebugVisualization(){this.debugHelpers=null}_setupCanvas(){if(!this.output.getContext)throw Error(`Output must be a valid Canvas element`);this.output.willReadFrequently=!0,this.output.width=this.input.width,this.output.height=this.input.height,Object.assign(this.output.style,{position:`absolute`,top:`0`,left:`0`,width:`100%`,height:`100%`,borderRadius:`5px`,background:`repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 20px 20px`}),this.ctx=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0})}async _setupUNetDenoiser(){if(this.state.isLoading)return;this.state.isLoading=!0;let e=this._generateTzaUrl();if(this.currentTZAUrl===e&&this.unet){this.state.isLoading=!1;return}try{this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let t;if(this.isGPUMode&&this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,t=e?.device?e:void 0}this.unet=await(await zo())(e,t,{aux:!0,hdr:!0,maxTileSize:this.tileSize}),this.currentTZAUrl=e,this.dispatchEvent({type:`loaded`}),console.log(`UNet denoiser loaded successfully:`,e)}catch(e){console.error(`Failed to load UNet denoiser:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}_generateTzaUrl(){let{BASE_URL:e,QUALITY_SUFFIXES:t}=Bo;return`${e}rt_hdr_alb_nrm${t[this.quality]||``}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.debugGbufferMaps=this.config.debugGbufferMaps,this.tileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(Bo.QUALITY_SUFFIXES,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(Bo.QUALITY_SUFFIXES).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start(){if(!this.enabled||this.state.isDenoising||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.(),this.input.style.opacity=`0`;let t=performance.now()-e;console.log(`Denoising completed in ${t.toFixed(1)}ms (quality: ${this.quality})`)}return t}async execute(){if(!this.enabled||!this.unet)return!1;this.state.abortController=new AbortController,this.state.isDenoising=!0,this.input.style.opacity=`0`,this.output.style.display=`block`;try{return await this._executeUNet(),!0}catch(e){return e.name===`AbortError`?console.log(`Denoising was aborted`):console.error(`Denoising error:`,e),this.input.style.opacity=`1`,!1}finally{this.state.isDenoising=!1,this.state.abortController=null,this.dispatchEvent({type:`end`})}}async _executeUNet(){return this._executeUNetGPU()}async _executeUNetGPU(){let{width:e,height:t}=this.output;if(!this.getGPUTextures)return console.warn(`OIDNDenoiser: GPU mode enabled but getGPUTextures not provided`),!1;let n=this.getGPUTextures();if(!n?.color)return console.warn(`OIDNDenoiser: GPU textures not ready yet`),!1;let r=this.gpuDevice;if(!r)return console.warn(`OIDNDenoiser: gpuDevice not available`),!1;this._ensureGPUInputBuffers(e,t);let i=r.createCommandEncoder({label:`oidn-tex-to-buf`}),a=e*16,o=Math.ceil(a/256)*256,s=o!==a,c=[],l=(n,l)=>{if(!s)i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:l,offset:0,bytesPerRow:a,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});else{let s=r.createBuffer({size:o*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC});c.push(s),i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:s,offset:0,bytesPerRow:o,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});for(let e=0;e<t;e++)i.copyBufferToBuffer(s,e*o,l,e*a,a)}};l(n.color,this._gpuInputBuffers.color),l(n.albedo,this._gpuInputBuffers.albedo),l(n.normal,this._gpuInputBuffers.normal),r.queue.submit([i.finish()]);for(let e of c)e.destroy();this.getTransparentBackground()?await this._cacheInputAlpha(r,e,t):this._cachedAlpha=null,this.ctx.drawImage(this.input,0,0,e,t);let u={color:{data:this._gpuInputBuffers.color,width:e,height:t},albedo:{data:this._gpuInputBuffers.albedo,width:e,height:t},normal:{data:this._gpuInputBuffers.normal,width:e,height:t}};return this._executeWithAbortGPU(u)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t}}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0}}async _cacheInputAlpha(e,t,n){let r=t*n*16,i=e.createBuffer({label:`oidn-alpha-staging`,size:r,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),a=e.createCommandEncoder();a.copyBufferToBuffer(this._gpuInputBuffers.color,0,i,0,r),e.queue.submit([a.finish()]),await i.mapAsync(GPUMapMode.READ);let o=new Float32Array(i.getMappedRange()),s=t*n,c=new Uint8Array(s);for(let e=0;e<s;e++)c[e]=Math.min(Math.max(o[e*4+3]*255,0),255)|0;i.unmap(),i.destroy(),this._cachedAlpha=c,this._cachedAlphaWidth=t}_executeWithAbortGPU(e){return new Promise((t,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null,a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{await this._displayGPUOutput(e),t()}catch(e){r(e)}},progress:(e,t,r)=>{if(!e?.data||!r)return;this.dispatchEvent({type:`tileProgress`,tile:r,imageWidth:e.width,imageHeight:e.height});let i=this.gpuDevice,a=e.width,o=e.height,s=Math.min(r.width,a-r.x),c=Math.min(r.height,o-r.y);if(s<=0||c<=0)return;let l=s*16,u=s*c*16,d=i.createBuffer({size:u,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),f=i.createCommandEncoder();for(let t=0;t<c;t++){let n=((r.y+t)*a+r.x)*16,i=t*l;f.copyBufferToBuffer(e.data,n,d,i,l)}i.queue.submit([f.finish()]),d.mapAsync(GPUMapMode.READ).then(()=>{let e=new Float32Array(d.getMappedRange()),t=new ImageData(s,c),i=this.getExposure(),a=this.getSaturation(),o=Mo.get(this.getToneMapping())||Mo.get(n.ACESFilmicToneMapping),l=this._cachedAlpha,u=this._cachedAlphaWidth;for(let n=0,c=e.length;n<c;n+=4){let c=e[n]*i,d=e[n+1]*i,f=e[n+2]*i;if(a!==1&&($[0]=c,$[1]=d,$[2]=f,Lo($,a),c=$[0],d=$[1],f=$[2]),o(c,d,f,1,$),t.data[n]=$[0]**No*255|0,t.data[n+1]=$[1]**No*255|0,t.data[n+2]=$[2]**No*255|0,l){let e=(n>>2)%s,i=(n>>2)/s|0;t.data[n+3]=l[(r.y+i)*u+r.x+e]}else t.data[n+3]=255}d.unmap(),d.destroy(),this.ctx.putImageData(t,r.x,r.y)})}})})}async _displayGPUOutput({data:e,width:t,height:r}){let i=this.gpuDevice;if(!i){console.error(`OIDNDenoiser: gpuDevice not available for output readback`);return}let a=t*r*4*4,o=i.createBuffer({label:`oidn-output-staging`,size:a,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),s=i.createCommandEncoder({label:`oidn-readback`});s.copyBufferToBuffer(e,0,o,0,a),i.queue.submit([s.finish()]),await o.mapAsync(GPUMapMode.READ);let c=new Float32Array(o.getMappedRange()),l=new ImageData(t,r),u=this.getExposure(),d=this.getSaturation(),f=Mo.get(this.getToneMapping())||Mo.get(n.ACESFilmicToneMapping),p=this._cachedAlpha;for(let e=0,t=c.length;e<t;e+=4){let t=c[e]*u,n=c[e+1]*u,r=c[e+2]*u;d!==1&&($[0]=t,$[1]=n,$[2]=r,Lo($,d),t=$[0],n=$[1],r=$[2]),f(t,n,r,1,$),l.data[e]=$[0]**No*255|0,l.data[e+1]=$[1]**No*255|0,l.data[e+2]=$[2]**No*255|0,l.data[e+3]=p?p[e>>2]:255}o.unmap(),o.destroy(),this.ctx.putImageData(l,0,0)}abort(){!this.enabled||!this.state.isDenoising||(this.state.abortController?.abort(),this.input.style.opacity=`1`,this.state.isDenoising=!1,this.dispatchEvent({type:`end`}),console.log(`Denoising aborted`))}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this.output.width=e,this.output.height=t,this._setupUNetDenoiser().catch(e=>{console.error(`Failed to reinitialize denoiser after size change:`,e)})}_updateDebugVisualization(e){if(!e?.textures||e.textures.length<3)return;let t=this.debugHelpers&&(this._lastAlbedoTexture!==e.textures[2]||this._lastNormalTexture!==e.textures[1]);if(!this.debugHelpers||t){this.debugHelpers&&(this.debugHelpers.albedo?.dispose(),this.debugHelpers.normal?.dispose(),console.log(`OIDNDenoiser: Recreating debug helpers due to texture change`)),this.debugHelpers={albedo:Ya(this.renderer,e,{width:250,height:250,position:`bottom-right`,theme:`dark`,title:`OIDN Albedo`,autoUpdate:!1,textureIndex:2}),normal:Ya(this.renderer,e,{width:250,height:250,position:`bottom-left`,theme:`dark`,title:`OIDN Normal`,autoUpdate:!1,textureIndex:1})},this._lastAlbedoTexture=e.textures[2],this._lastNormalTexture=e.textures[1];let t=this.debugContainer||document.body;t.appendChild(this.debugHelpers.albedo),t.appendChild(this.debugHelpers.normal),this.debugHelpers.albedo.hide(),this.debugHelpers.normal.hide()}this.debugHelpers.albedo.update(),this.debugHelpers.normal.update()}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this.debugHelpers&&=(this.debugHelpers.albedo?.dispose(),this.debugHelpers.normal?.dispose(),null),this._lastAlbedoTexture=null,this._lastNormalTexture=null,this.output?.parentNode&&this.output.remove(),this.unet=null,this.ctx=null,this.state.abortController=null,this.removeAllListeners?.(),console.log(`OIDNDenoiser disposed`)}},Ho=`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,Uo={QUALITY_PRESETS:{fast:{2:Ho+`2x-spanx2-ch48.onnx`,4:Ho+`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:Ho+`2xNomosUni_compact_otf_medium.onnx`,4:Ho+`RealESRGAN_x4plus.onnx`},quality:{2:Ho+`2x-realesrgan-x2plus.onnx`,4:Ho+`4xNomos2_hq_mosr_fp32.onnx`}},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Wo=class extends n.EventDispatcher{constructor(e,t,r={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=r.getSourceCanvas||null,this.getGPUTextures=r.getGPUTextures||null,this.getExposure=r.getExposure||(()=>1),this.getToneMapping=r.getToneMapping||(()=>n.ACESFilmicToneMapping),this.getSaturation=r.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=r.scaleFactor||2,this.quality=r.quality||`fast`,this.tileSize=r.tileSize||Uo.TILE_SIZE,this._tileSizeOverride=!!r.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height}async _ensureSession(){let e=Uo.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{if(!this._worker)try{this._worker=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/AIUpscalerWorker-D58dcMrY.js`).href:new URL(`assets/AIUpscalerWorker-D58dcMrY.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;this._worker=await Ge(new URL(`data:text/javascript;base64,LyoqCiAqIFdlYiBXb3JrZXIgZm9yIEFJIFVwc2NhbGVyIGluZmVyZW5jZS4KICogSGFuZGxlcyBPTk5YIG1vZGVsIGxvYWRpbmcgYW5kIHRpbGUtYmFzZWQgaW5mZXJlbmNlIG9mZiB0aGUgbWFpbiB0aHJlYWQuCiAqCiAqIE1lc3NhZ2VzOgogKiA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lc3NhZ2UsIGlkOiBlLmRhdGE/LmlkIH0gKTsKCgl9Cgp9Owo=`,``+{}.url))}await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))};this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Uo.SESSION_OPTIONS})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.input.style.opacity=`0`,this.output.style.display=`block`,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t);try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:r,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,r*a,i*a),t.isHDR&&(this._hdrToneMapFn=Mo.get(this.getToneMapping())||Mo.get(n.ACESFilmicToneMapping),this._hdrExposure=this.getExposure(),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Uo.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(r/l),d=Math.ceil(i/l),f=u*d,p=0;for(let n=0;n<d;n++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,r-c)),d=Math.min(n*l,Math.max(0,i-c)),m=Math.min(c,r-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:n,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:r*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i,s=t.createBuffer({size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),s.destroy(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,Lo(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut),l[d]=this._tmOut[0]**+No,l[c+d]=this._tmOut[1]**+No,l[2*c+d]=this._tmOut[2]**+No}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:r,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=Mo.get(this.getToneMapping())||Mo.get(n.ACESFilmicToneMapping),l=this.getExposure(),u=this.getSaturation(),d=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,n=r[t]*l,i=r[t+1]*l,a=r[t+2]*l;u!==1&&(d[0]=n,d[1]=i,d[2]=a,Lo(d,u),n=d[0],i=d[1],a=d[2]),c(n,i,a,1,d),s[t]=d[0]**+No*255+.5|0,s[t+1]=d[1]**+No*255+.5|0,s[t+2]=d[2]**+No*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Uo.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}async dispose(){this.abort(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,console.log(`AIUpscaler disposed`)}},Go=class extends n.EventDispatcher{constructor({renderer:e,mainCanvas:t,scene:n,camera:r,stages:i,pipeline:a,getExposure:o,getSaturation:s,getTransparentBg:c}){super(),this.renderer=e,this.mainCanvas=t,this.denoiserCanvas=this._createDenoiserCanvas(t),this.scene=n,this.camera=r,this.pipeline=a,this._stages=i,this._getExposure=o,this._getSaturation=s,this._getTransparentBg=c,this.denoiser=null,this.upscaler=null,this._lastRenderWidth=0,this._lastRenderHeight=0}_createDenoiserCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this.denoiser?.setSize(e,t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){if(!this.denoiserCanvas||!this._lastRenderWidth||!this._lastRenderHeight)return!1;let e=this.denoiserCanvas.width!==this._lastRenderWidth||this.denoiserCanvas.height!==this._lastRenderHeight;return this.denoiserCanvas.width=this._lastRenderWidth,this.denoiserCanvas.height=this._lastRenderHeight,e}setupDenoiser(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.denoiser=new Vo(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...V,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation(),getTransparentBackground:()=>this._getTransparentBg(),getMRTRenderTarget:()=>e?.storageTextures?.readTarget??null}),this.denoiser.enabled=V.enableOIDN,this.denoiser.addEventListener(`start`,()=>this.dispatchEvent({type:R.DENOISING_START})),this.denoiser.addEventListener(`end`,()=>this.dispatchEvent({type:R.DENOISING_END}))}setupUpscaler(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Wo(this.denoiserCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.upscalerQuality||`fast`,getSourceCanvas:()=>this.denoiser?.enabled?null:this.renderer.domElement,getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=V.enableUpscaler||!1,this.upscaler.addEventListener(`resolution_changed`,e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height})),this.upscaler.addEventListener(`start`,()=>this.dispatchEvent({type:R.UPSCALING_START})),this.upscaler.addEventListener(`progress`,e=>this.dispatchEvent({type:R.UPSCALING_PROGRESS,progress:e.progress})),this.upscaler.addEventListener(`end`,()=>this.dispatchEvent({type:R.UPSCALING_END}))}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.variance&&!this._isAdaptiveSamplingActive()&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),n.ssrc&&(n.ssrc.enabled=!1),this._clearDenoiserTextures(),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`ssrc`:n.ssrc&&(n.ssrc.enabled=!0);break;case`edgeaware`:n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e)}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,e?n.display?.setExposure(1):(n.display?.setExposure(t),n.display&&this.renderer&&(this.renderer.toneMappingExposure=1)))}setAdaptiveSamplingEnabled(e){let t=this._stages;t.adaptiveSampling&&(t.adaptiveSampling.enabled=e,t.adaptiveSampling.toggleHelper(!1)),e?t.variance&&(t.variance.enabled=!0):t.asvgf?.enabled||t.variance&&(t.variance.enabled=!1),!e&&this.pipeline?.context&&!t.asvgf?.enabled&&this.pipeline.context.removeTexture(`variance:output`)}onRenderComplete({isStillComplete:e,context:t}){(this.denoiser?.enabled||this.upscaler?.enabled)&&this.denoiserCanvas&&(this.denoiserCanvas.style.display=`block`);let n=()=>{e()&&this.upscaler?.enabled&&this.upscaler.start()};this.denoiser?.enabled?(this.denoiser.addEventListener(`end`,n,{once:!0}),this.denoiser.start()):(this.upscaler?.enabled&&this._stages.display&&t&&this._stages.display.render(t),n())}abort(e){e&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort(),this.denoiser&&(this.denoiser.enabled&&this.denoiser.abort(),this.denoiser.output&&(this.denoiser.output.style.display=`none`))}dispose(){this.denoiser&&=(this.denoiser.dispose(),null),this.upscaler&&=(this.upscaler.dispose(),null),this.denoiserCanvas?.parentNode&&(this.denoiserCanvas.parentNode.removeChild(this.denoiserCanvas),this.denoiserCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.toggleHeatmap?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e))}setSSRCParams(e){this._stages.ssrc?.updateParameters(e)}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}setAdaptiveSamplingParams(e){e.min!==void 0&&this._stages.pathTracer?.setAdaptiveSamplingMin(e.min),e.adaptiveSamplingMax!==void 0&&this._settings?.set(`adaptiveSamplingMax`,e.adaptiveSamplingMax),this._stages.adaptiveSampling?.setAdaptiveSamplingParameters(e)}toggleAdaptiveSamplingHelper(e){this._stages.adaptiveSampling?.toggleHelper(e)}setOIDNEnabled(e){this.denoiser&&(this.denoiser.enabled=e)}setOIDNQuality(e){this.denoiser?.updateQuality(e)}setOIDNTileHelper(e){this._setTileHelper(e)}setTileHelperEnabled(e){this._setTileHelper(e)}setTileHighlightEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e)}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setAdaptiveSampling(e){this._settings?.set(`useAdaptiveSampling`,e),this.setAdaptiveSamplingEnabled(e)}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_isAdaptiveSamplingActive(){return this._stages.adaptiveSampling?.enabled??!1}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:temporalColor`,`asvgf:variance`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`ssrc:output`].forEach(t=>e.removeTexture(t))}_applyASVGFPreset(e){let t=je[e];t&&this._stages.asvgf?.updateParameters(t)}},Ko=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidth=2}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a;e.strokeStyle=this._borderColor,e.lineWidth=this._borderWidth,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},qo=class{constructor(e,r,i){this.layer=`scene`,this.visible=!0,this._outlineNode=(0,g.outline)(r,i,{selectedObjects:[],edgeThickness:(0,o.uniform)(1),edgeGlow:(0,o.uniform)(0)}),this._displayWidth=1,this._displayHeight=1;let a=this._outlineNode.setSize.bind(this._outlineNode);this._outlineNode.setSize=()=>{a(this._displayWidth,this._displayHeight)};let s=(0,o.uniform)(3),c=(0,o.uniform)(new n.Color(16777215)),l=(0,o.uniform)(new n.Color(1640965)),{visibleEdge:u,hiddenEdge:d}=this._outlineNode,f=u.mul(c).add(d.mul(l)).mul(s);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,o.vec4)(f,1),this._material.blending=n.AdditiveBlending,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}render(e){if(this._outlineNode.selectedObjects.length===0)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}setSize(e,t){this._displayWidth=e,this._displayHeight=t,this._outlineNode.setSize(e,t)}show(){this.visible=!0}hide(){this.visible=!1}dispose(){this.visible=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad?.dispose()}},Jo=class{constructor(e,t){this.renderer=e,this.camera=t,this._helpers=new Map,this._hudCanvas=document.createElement(`canvas`),this._hudCanvas.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`,this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Ko;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`tile:changed`,e=>{e.renderMode===1&&e.tileBounds&&(s.setActiveTile(e.tileBounds),s.show())}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),i.addEventListener(R.RENDER_COMPLETE,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new qo(this.renderer,t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(console.warn(`OverlayManager: helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){this._helperScene&&this._helperScene.render(this.renderer,this.camera);for(let e of this._helpers.values())e.visible&&e.layer===`scene`&&e.render&&e.render(this.renderer,this.camera);this.refreshHUD()}setSize(e,t){for(let n of this._helpers.values())n.setSize?.(e,t)}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(e.visible&&e.layer===`hud`&&e.render){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}let r=window.devicePixelRatio||1,i=e.clientWidth,a=e.clientHeight,o=Math.round(i*r),s=Math.round(a*r);(e.width!==o||e.height!==s)&&(e.width=o,e.height=s),t.clearRect(0,0,o,s),t.save(),t.scale(r,r);for(let e of this._helpers.values())e.visible&&e.layer===`hud`&&e.render&&e.render(t,i,a);t.restore(),e.style.display!==``&&(e.style.display=``)}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}},Yo=class extends n.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new n.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._tempVec=new n.Vector3,this._skinnedCache=null,this._totalTriangleCount=0,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this.wakeCallback=null}init(e,t,r,i,a){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=r,this._totalTriangleCount=a,this.mixer=new n.AnimationMixer(t);let o=i.map(e=>this.mixer.clipAction(e)),s=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!o.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return s(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new n.AnimationMixer(e),this._mixerRoot=e,o=i.map(e=>this.mixer.clipAction(e))),this.actions=o,this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let c=0;for(let e of r){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:c,count:i,uniqueVerts:a,indices:r}),this._skinnedCache.push(new Float32Array(a*3)),c+=i}this._posBuffer=new Float32Array(a*9);let l=r.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${r.length} meshes (${l} skinned), ${a} triangles`)}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:R.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:R.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:R.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:R.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?n.LoopRepeat:n.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._computePositions(),this._posBuffer}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._computePositions(),this._posBuffer}_computePositions(){let e=this._tempVec,t=this._posBuffer;this._mixerRoot.updateMatrixWorld(!0);for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n],{start:i,count:a,uniqueVerts:o,indices:s}=this._meshTriRanges[n],c=this._skinnedCache[n],l=r.matrixWorld;for(let t=0;t<o;t++)r.getVertexPosition(t,e),e.applyMatrix4(l),c[t*3]=e.x,c[t*3+1]=e.y,c[t*3+2]=e.z;if(s)for(let e=0;e<a;e++){let n=e*3,r=s[n]*3,a=s[n+1]*3,o=s[n+2]*3,l=(i+e)*9;t[l]=c[r],t[l+1]=c[r+1],t[l+2]=c[r+2],t[l+3]=c[a],t[l+4]=c[a+1],t[l+5]=c[a+2],t[l+6]=c[o],t[l+7]=c[o+1],t[l+8]=c[o+2]}else for(let e=0;e<a;e++){let n=e*3*3,r=(e*3+1)*3,a=(e*3+2)*3,o=(i+e)*9;t[o]=c[n],t[o+1]=c[n+1],t[o+2]=c[n+2],t[o+3]=c[r],t[o+4]=c[r+1],t[o+5]=c[r+2],t[o+6]=c[a],t[o+7]=c[a+1],t[o+8]=c[a+2]}}}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._skinnedCache=null,this._clipsCache=null}},Xo=class{constructor({camera:e,canvas:t,orbitControls:r,app:i}){this._app=i,this._orbitControls=r,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new n.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._tempVec=new n.Vector3,this._normalMatrix=new n.Matrix3,this._refitInFlight=!1,this._baselineComputed=!1,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e,t){this._meshes=e,this._meshTriRanges=[],this._skinnedCache=[],this._normalCache=[];let n=0;for(let t of e){let e=t.geometry,r=e.attributes.position,i=e.index?e.index.array:null,a=i?i.length/3:r.count/3,o=r.count;this._meshTriRanges.push({start:n,count:a,uniqueVerts:o,indices:i}),this._skinnedCache.push(new Float32Array(o*3)),this._normalCache.push(new Float32Array(o*3)),n+=a}this._posBuffer=new Float32Array(t*9),this._normalBuffer=new Float32Array(t*9)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e)}detach(){this._attached&&=(this._controls.detach(),null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:R.TRANSFORM_MODE_CHANGED,mode:e})}setSpace(e){this._controls.setSpace(e)}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:R.OBJECT_TRANSFORM_START}):(this._recomputeAndRefit(),this._app.dispatchEvent({type:R.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake()}_recomputeAndRefit(){if(!this._meshes||!this._posBuffer||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){if(!this._baselineComputed)this._computeAllPositions(),this._baselineComputed=!0;else for(let t of e)this._computeMeshPositions(t);this._refitInFlight=!0;try{this._app.refitBLASes(e,this._posBuffer,this._normalBuffer)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}_computeAllPositions(){for(let e=0;e<this._meshes.length;e++)this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._meshes[e],{start:n,count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._skinnedCache[e],s=this._normalCache[e],c=this._tempVec,l=this._posBuffer,u=this._normalBuffer;t.updateMatrixWorld(!0);let d=t.matrixWorld;this._normalMatrix.getNormalMatrix(d);let f=this._normalMatrix.elements,p=t.geometry.attributes.normal;for(let e=0;e<i;e++)if(t.getVertexPosition(e,c),c.applyMatrix4(d),o[e*3]=c.x,o[e*3+1]=c.y,o[e*3+2]=c.z,p){let t=p.getX(e),n=p.getY(e),r=p.getZ(e);s[e*3]=f[0]*t+f[3]*n+f[6]*r,s[e*3+1]=f[1]*t+f[4]*n+f[7]*r,s[e*3+2]=f[2]*t+f[5]*n+f[8]*r}if(a)for(let e=0;e<r;e++){let t=e*3,r=a[t]*3,i=a[t+1]*3,c=a[t+2]*3,d=(n+e)*9;l[d]=o[r],l[d+1]=o[r+1],l[d+2]=o[r+2],l[d+3]=o[i],l[d+4]=o[i+1],l[d+5]=o[i+2],l[d+6]=o[c],l[d+7]=o[c+1],l[d+8]=o[c+2],u[d]=s[r],u[d+1]=s[r+1],u[d+2]=s[r+2],u[d+3]=s[i],u[d+4]=s[i+1],u[d+5]=s[i+2],u[d+6]=s[c],u[d+7]=s[c+1],u[d+8]=s[c+2]}else for(let e=0;e<r;e++){let t=e*3*3,r=(e*3+1)*3,i=(e*3+2)*3,a=(n+e)*9;l[a]=o[t],l[a+1]=o[t+1],l[a+2]=o[t+2],l[a+3]=o[r],l[a+4]=o[r+1],l[a+5]=o[r+2],l[a+6]=o[i],l[a+7]=o[i+1],l[a+8]=o[i+2],u[a]=s[t],u[a+1]=s[t+1],u[a+2]=s[t+2],u[a+3]=s[r],u[a+4]=s[r+1],u[a+5]=s[r+2],u[a+6]=s[i],u[a+7]=s[i+1],u[a+8]=s[i+2]}}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._baselineComputed=!1}},Zo=class extends n.EventDispatcher{constructor(e,t={}){super(),this.canvas=e,this._autoResize=t.autoResize!==!1,this._showStats=t.showStats!==!1,this._statsContainer=t.statsContainer||null,this.settings=new xo(V),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this.pipeline=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new Yo,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this.pathTracerEnabled=!0,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this.completion=new ho,this._resizeDebounceTimer=null}async init(){return await this._initRenderer(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this._showStats&&this._initStats(),this.isInitialized=!0,console.log(`WebGPU Path Tracer App initialized`),this}animate(){if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this._stats?.update();return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>console.error(`Animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}if(this.needsReset&&=(this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.display.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}this.pipeline.render(),this.stages.pathTracer.isComplete||this.completion.updateTime(),xe({timeElapsed:this.completion.timeElapsed,samples:Se(this.stages.pathTracer)}),this.completion.isTimeLimitReached(this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&(this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context}),this.dispatchEvent({type:`RenderComplete`}),this.dispatchEvent({type:R.RENDER_COMPLETE}))}this._renderHelperOverlay(),this._stats?.update(),this.renderer.resolveTimestampsAsync?.(n.TimestampQuery.RENDER),this.renderer.resolveTimestampsAsync?.(n.TimestampQuery.COMPUTE)}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}wake(){!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation(),this._stats&&(this._stats.dom.style.display=`none`)}resume(){this._paused=!1,this.animationManagerId||this.animate(),this._stats&&(this._stats.dom.style.display=``)}reset(e=!1){if(this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`asvgf:reset`)),this.denoisingManager?.abort(this.canvas),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:R.RENDER_RESET})}dispose(){this.animationManager?.dispose(),this.stopAnimation(),ye(null),this.assetLoader&&this._onAssetLoaded&&this.assetLoader.removeEventListener(`load`,this._onAssetLoaded),this.transformManager?.dispose(),this.overlayManager?.dispose(),this._sceneHelpers?.clear(),this.denoisingManager?.dispose(),this.pipeline?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.renderer?.dispose(),this._stats&&=(this._stats.dom.remove(),null),clearTimeout(this._resizeDebounceTimer),window.removeEventListener(`resize`,this.resizeHandler),this.isInitialized=!1}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}async loadEnvironment(e){this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}async _loadWithSceneRebuild(e,t){this._loadingInProgress=!0;try{await e(),this._syncControlsAfterLoad(),await this.loadSceneData(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}finally{this._loadingInProgress=!1}}async loadSceneData(){this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1;let e=new sa(`loadSceneData`),t=this.meshScene.environment,n=null;return t?.image?.data&&(e.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=t,n=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>e.end(`Environment CDF build (worker)`))),e.start(`BVH build (SceneProcessor)`),await this._sdf.buildBVH(this.meshScene),e.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),e.start(`GPU data transfer`),this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,t)?(this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),e.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),e.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),e.end(`Material setup (TSL compile)`),n&&(z({status:`Finalizing environment map...`,progress:95}),await n,this.stages.pathTracer.environment.applyCDFResults()),e.start(`Apply settings`),this.settings.applyAll(),this.stages.display.setTransparentBackground(this.settings.get(`transparentBackground`)),e.end(`Apply settings`),e.print(),be(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0):!1}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,()=>{this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset()}),r}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0)return;this.renderer.setPixelRatio(1),this.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix();let n=window.devicePixelRatio||1;this.overlayManager?.setSize(Math.round(e*n),Math.round(t*n));let r=this.denoisingManager?._lastRenderWidth??0,i=this.denoisingManager?._lastRenderHeight??0;e===r&&t===i||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this.pipeline?.setSize(e,t),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}setCanvasSize(e,t){e===0||t===0||(this.renderer.setPixelRatio(1),this.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix(),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t))}configureForMode(e,t={}){if(e===`results`){this.pauseRendering=!0,this.cameraManager.controls.enabled=!1,this.renderer?.domElement&&(this.renderer.domElement.style.display=`none`),this.denoisingManager?.denoiser?.output&&(this.denoisingManager.denoiser.output.style.display=`none`);return}let n=e===`final-render`,r=n?ze:G;this.cameraManager.controls.enabled=!n,this.settings.setMany({maxSamples:r.maxSamples,maxBounces:r.bounces,samplesPerPixel:r.samplesPerPixel,transmissiveBounces:r.transmissiveBounces},{silent:!0}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.setUniform(`enableAlphaShadows`,r.enableAlphaShadows??!1),this.stages.pathTracer?.tileManager?.setTileCount(r.tiles);let i=this.overlayManager?.getHelper(`tiles`);i&&(i.enabled=r.tilesHelper,r.tilesHelper||i.hide()),this.stages.pathTracer?.updateCompletionThreshold?.();let a=this.denoisingManager?.denoiser;a&&(a.abort(),a.enabled=r.enableOIDN,a.updateQuality(r.oidnQuality)),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&this.setCanvasSize(t.canvasWidth,t.canvasHeight),this.renderer?.domElement&&(this.renderer.domElement.style.display=`block`),this.denoisingManager?.denoiser?.output&&(this.denoisingManager.denoiser.output.style.display=`block`),this.needsReset=!1,this.pauseRendering=!1,this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager;return(e?.denoiser?.enabled||e?.upscaler?.enabled)&&e?.denoiserCanvas&&this.stages.pathTracer?.isComplete?e.denoiserCanvas:(this.stages.display&&this.pipeline?.context&&this.stages.display.render(this.pipeline.context),this.renderer.domElement)}screenshot(){let e=this.getCanvas();if(e)try{let t=e.toDataURL(`image/png`),n=document.createElement(`a`);n.href=t,n.download=`screenshot.png`,n.click()}catch(e){console.error(`Screenshot failed:`,e)}}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}setMaterialProperty(e,t,n){if(this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this.stages.pathTracer?.enableEmissiveTriangleSampling?.value){let r=this._sdf.updateMaterialEmissive(e,t,n);r&&this.stages.pathTracer.setEmissiveTriangleData(r.rawData,r.emissiveCount,r.totalPower)}this.reset()}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this.reset()}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(ye(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);let i=e.limits;this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:{maxBufferSize:i.maxBufferSize,maxStorageBufferBindingSize:i.maxStorageBufferBindingSize,maxColorAttachmentBytesPerSample:128}}),window.renderer=this.renderer,await this.renderer.init(),t.RectAreaLightNode.setLTC(r.RectAreaLightTexturesLib.init()),this.renderer.toneMapping=n.ACESFilmicToneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1)}_initCameraManager(){this.cameraManager=new So(this.canvas)}_initScenes(){this.scene=new n.Scene,this.meshScene=new n.Scene,this._sceneHelpers=new E}_initAssetPipeline(){this._sdf=new Ha,this.assetLoader=new vo(this.meshScene,this.cameraManager.camera,this.cameraManager.controls),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this.cameraManager.controls.addEventListener(`change`,()=>{this.needsReset=!0,this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new mo(this.renderer,e||1,t||1),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.ssrc),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.adaptiveSampling),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.display);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this.pipeline.setSize(n,r)}_initManagers(){this.interactionManager=new go({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new Co(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),this._setupOverlayManager(),this.transformManager=new Xo({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this.cameraManager.addEventListener(`CameraSwitched`,e=>this.dispatchEvent(e)),this.cameraManager.addEventListener(R.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[R.DENOISING_START,R.DENOISING_END,R.UPSCALING_START,R.UPSCALING_PROGRESS,R.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[R.ANIMATION_STARTED,R.ANIMATION_PAUSED,R.ANIMATION_STOPPED]),this.animationManager.addEventListener(R.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this.animationManager.addEventListener(R.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e)}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion()}),this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&window.addEventListener(`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress){if(e.model)await this.loadSceneData();else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),be()}this.pauseRendering=!1,this.reset()}},this.assetLoader.addEventListener(`load`,this._onAssetLoaded),this.assetLoader.addEventListener(`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.assetLoader?.targetModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e,this._sdf.triangleCount),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:R.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes,this._sdf.triangleCount)}_createStages(){let e=this.settings.get(`adaptiveSamplingMax`),t=this.settings.get(`useAdaptiveSampling`);this.stages.pathTracer=new Ka(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new qa(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new Ja(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.ssrc=new lo(this.renderer,{enabled:!1}),this.stages.asvgf=new Xa(this.renderer,{enabled:!1}),this.stages.variance=new Qa(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new eo(this.renderer,{enabled:!1}),this.stages.adaptiveSampling=new ro(this.renderer,{adaptiveSamplingMax:e,enabled:t}),this.stages.edgeFilter=new io(this.renderer,{enabled:!1}),this.stages.autoExposure=new oo(this.renderer,{enabled:V.autoExposure??!1}),this.stages.display=new uo(this.renderer,{exposure:V.autoExposure?1:this.settings.get(`exposure`)??1,saturation:this.settings.get(`saturation`)??V.saturation})}_setupDenoisingManager(){this.denoisingManager=new Go({renderer:this.renderer,mainCanvas:this.canvas,scene:this.scene,camera:this.cameraManager.camera,stages:{pathTracer:this.stages.pathTracer,asvgf:this.stages.asvgf,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,adaptiveSampling:this.stages.adaptiveSampling,edgeFilter:this.stages.edgeFilter,ssrc:this.stages.ssrc,autoExposure:this.stages.autoExposure,display:this.stages.display},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,getTransparentBg:()=>this.settings.get(`transparentBackground`)??!1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));if(t&&!e.isComplete)e.isComplete=!0;else if(!t&&e.isComplete){e.isComplete=!1,this.completion.resumeFromPause(),this.canvas.style.opacity=`1`;let t=this.denoisingManager?.denoiser?.output;t&&(t.style.display=`none`),this.dispatchEvent({type:R.RENDER_RESET}),this.wake()}}_initStats(){let e=this._statsContainer||this.canvas.parentElement||document.body;this._stats=D(this.renderer,e)}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:R.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render(),this.transformManager?.render(this.renderer)}_setupOverlayManager(){this.overlayManager=new Jo(this.renderer,this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1})}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_forwardEvents(e,t){if(e)for(let n of t)e.addEventListener(n,e=>this.dispatchEvent(e))}},Qo=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=ze.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`final-render`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.denoiser?.enabled&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:R.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:R.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(xe({samples:Se(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(R.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(R.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app;return{maxSamples:e.settings.get(`maxSamples`),maxBounces:e.settings.get(`maxBounces`),samplesPerPixel:e.settings.get(`samplesPerPixel`),transmissiveBounces:e.settings.get(`transmissiveBounces`),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.denoiser?.enabled,oidnQuality:e.denoisingManager?.denoiser?.quality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;t.settings.setMany({maxSamples:e.maxSamples,maxBounces:e.maxBounces,samplesPerPixel:e.samplesPerPixel,transmissiveBounces:e.transmissiveBounces},{silent:!0}),t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.denoiser.enabled=e.oidnEnabled??!1,e.oidnQuality&&t.denoisingManager.denoiser.updateQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.animationManager?.stop(),t.reset(),t.wake()}};e.AF_DEFAULTS=Ie,e.ASVGF_QUALITY_PRESETS=je,e.AUTO_FOCUS_MODES=Fe,e.AnimationManager=Yo,e.BVH_LEAF_MARKERS=W,e.CAMERA_PRESETS=Pe,e.CAMERA_RANGES=Me,e.CameraManager=So,e.DEFAULT_TEXTURE_MATRIX=Re,e.DenoisingManager=Go,e.ENGINE_DEFAULTS=V,e.EngineEvents=R,e.FINAL_RENDER_CONFIG=ze,e.InteractionManager=go,e.LightManager=Co,e.MEMORY_CONSTANTS=Be,e.OverlayManager=Jo,e.PREVIEW_RENDER_CONFIG=G,e.PathTracerApp=Zo,e.PipelineContext=fo,e.RenderPipeline=mo,e.RenderSettings=xo,e.RenderStage=L,e.SKY_PRESETS=Ne,e.StageExecutionMode=I,e.TEXTURE_CONSTANTS=Le,e.TRIANGLE_DATA_LAYOUT=H,e.TransformManager=Xo,e.VideoRenderManager=Qo});
|
|
688
688
|
//# sourceMappingURL=rayzee.umd.js.map
|