rayzee 5.7.1 → 5.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/rayzee.es.js +1293 -1290
- package/dist/rayzee.es.js.map +1 -1
- package/dist/rayzee.umd.js +6 -3
- package/dist/rayzee.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/EngineDefaults.js +3 -3
- package/src/Stages/BilateralFilter.js +4 -1
- package/src/Stages/EdgeFilter.js +89 -69
package/dist/rayzee.umd.js
CHANGED
|
@@ -140,7 +140,7 @@
|
|
|
140
140
|
return seed;
|
|
141
141
|
|
|
142
142
|
}
|
|
143
|
-
`,[oe,ae]),F={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},I=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||F.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 F.ALWAYS:return!0;case F.PER_CYCLE:return t===0?!0:n===!0;case F.PER_TILE:return!0;case F.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)}},ve=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}},ye=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}},L={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`,DISPOSE:`engine:dispose`},be=null;function xe(e){be=e}var Se=()=>be?.({type:L.LOADING_RESET}),R=e=>{be?.({type:L.LOADING_UPDATE,...e})},Ce=e=>{be?.({type:L.STATS_UPDATE,...e})};function we(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 Te(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Ee(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Ee(e),e.dispose()}}function Ee(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 De({material:e,geometry:t,children:n}){if(e&&Te(e),t&&t.dispose(),n.length>0)for(let e of n)De(e)}function Oe(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Te(e);return}for(;e.children.length>0;)for(let t of e.children)Oe(t);De(e),e.removeFromParent(),e.clear()}}function ke(e,t,n){return e===1?n*t:t}function Ae(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 je(){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 Me(e,n){let i=new t.StorageTexture(e,n);return i.type=r.FloatType,i.format=r.RGBAFormat,i.minFilter=r.LinearFilter,i.magFilter=r.LinearFilter,i}var Ne=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,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Me(e,n),this.writeNormalDepth=Me(e,n),this.writeAlbedo=Me(e,n),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.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${n} (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}},z={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},Pe={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}},Fe={fov:{min:10,max:90,default:z.fov},focusDistance:{min:.3,max:100,default:z.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:z.aperture},focalLength:{min:0,max:200,default:z.focalLength}},Ie={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}},Le={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}},Re={MANUAL:`manual`,AUTO:`auto`},ze={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},B={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},V={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}},H={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},U={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},Be=[0,0,1,1,0,0,0,1],Ve={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,enableAlphaShadows:!0,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},W={maxSamples:z.maxSamples,bounces:z.bounces,samplesPerPixel:z.samplesPerPixel,renderMode:z.renderMode,enableAlphaShadows:z.enableAlphaShadows,transmissiveBounces:z.transmissiveBounces,tiles:z.tiles,tilesHelper:z.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},He={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},Ue={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},G=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: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 i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`maxBounces`,z.bounces,`int`),i(`samplesPerPixel`,z.samplesPerPixel,`int`),i(`maxSamples`,z.maxSamples,`int`),i(`transmissiveBounces`,z.transmissiveBounces,`int`),i(`visMode`,z.debugMode,`int`),i(`debugVisScale`,z.debugVisScale,`float`),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`environmentIntensity`,z.environmentIntensity,`float`),i(`backgroundIntensity`,z.backgroundIntensity,`float`),a(`showBackground`,z.showBackground),a(`transparentBackground`,z.transparentBackground),a(`enableEnvironment`,z.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),a(`useEnvMapIS`,z.useImportanceSampledEnvironment),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,z.globalIlluminationIntensity,`float`),i(`exposure`,z.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(128),`float`),area:(0,n.uniformArray)(new Float32Array(208),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(224),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`),a(`enableDOF`,z.enableDOF),i(`focusDistance`,z.focusDistance,`float`),i(`focalLength`,z.focalLength,`float`),i(`aperture`,z.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,z.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,A),A.value=z.samplingTechnique,a(`useAdaptiveSampling`,z.adaptiveSampling),i(`adaptiveSamplingMin`,z.adaptiveSamplingMin??1,`int`),i(`adaptiveSamplingMax`,z.adaptiveSamplingMax,`int`),i(`fireflyThreshold`,z.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,z.enableEmissiveTriangleSampling),i(`emissiveBoost`,z.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`renderMode`,z.renderMode,`int`),a(`enableAlphaShadows`,z.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`),i(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Ue[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._lightBuffers={})}},We=V.SLOTS_PER_MATERIAL,Ge=B.UV_C_MAT_OFFSET+2,Ke=B.NORMAL_C_OFFSET+3,qe=B.NORMAL_A_OFFSET+3,Je=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Ye=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 r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/We),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*V.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+V.COLOR]=n[0],r[i+V.COLOR+1]=n[1],r[i+V.COLOR+2]=n[2]):(r[i+V.COLOR]=n.r,r[i+V.COLOR+1]=n.g,r[i+V.COLOR+2]=n.b);break;case`metalness`:r[i+V.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+V.EMISSIVE]=n[0],r[i+V.EMISSIVE+1]=n[1],r[i+V.EMISSIVE+2]=n[2]):(r[i+V.EMISSIVE]=n.r,r[i+V.EMISSIVE+1]=n.g,r[i+V.EMISSIVE+2]=n.b);break;case`roughness`:r[i+V.ROUGHNESS]=n;break;case`ior`:r[i+V.IOR]=n;break;case`transmission`:r[i+V.TRANSMISSION]=n;break;case`thickness`:r[i+V.THICKNESS]=n;break;case`emissiveIntensity`:r[i+V.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.ATTENUATION_COLOR]=n[0],r[i+V.ATTENUATION_COLOR+1]=n[1],r[i+V.ATTENUATION_COLOR+2]=n[2]):(r[i+V.ATTENUATION_COLOR]=n.r,r[i+V.ATTENUATION_COLOR+1]=n.g,r[i+V.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+V.ATTENUATION_DISTANCE]=n;break;case`dispersion`:r[i+V.DISPERSION]=n;break;case`sheen`:r[i+V.SHEEN]=n;break;case`sheenRoughness`:r[i+V.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.SHEEN_COLOR]=n[0],r[i+V.SHEEN_COLOR+1]=n[1],r[i+V.SHEEN_COLOR+2]=n[2]):(r[i+V.SHEEN_COLOR]=n.r,r[i+V.SHEEN_COLOR+1]=n.g,r[i+V.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+V.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.SPECULAR_COLOR]=n[0],r[i+V.SPECULAR_COLOR+1]=n[1],r[i+V.SPECULAR_COLOR+2]=n[2]):(r[i+V.SPECULAR_COLOR]=n.r,r[i+V.SPECULAR_COLOR+1]=n.g,r[i+V.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+V.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+V.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+V.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+V.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+V.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+V.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+V.OPACITY]=n;break;case`side`:r[i+V.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+V.TRANSPARENT]=n;break;case`alphaTest`:r[i+V.ALPHA_TEST]=n;break;case`alphaMode`:r[i+V.ALPHA_MODE]=n;break;case`depthWrite`:r[i+V.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+V.NORMAL_SCALE]=n,r[i+V.NORMAL_SCALE+1]=n):(r[i+V.NORMAL_SCALE]=n.x,r[i+V.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+V.BUMP_SCALE]=n;break;case`displacementScale`:r[i+V.DISPLACEMENT_SCALE]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Je.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),[`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*V.FLOATS_PER_MATERIAL;t.color&&(n[r+V.COLOR]=t.color.r??t.color[0]??1,n[r+V.COLOR+1]=t.color.g??t.color[1]??1,n[r+V.COLOR+2]=t.color.b??t.color[2]??1),n[r+V.METALNESS]=t.metalness??0,t.emissive&&(n[r+V.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+V.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+V.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+V.ROUGHNESS]=t.roughness??1,n[r+V.IOR]=t.ior??1.5,n[r+V.TRANSMISSION]=t.transmission??0,n[r+V.THICKNESS]=t.thickness??.1,n[r+V.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+V.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+V.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+V.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+V.ATTENUATION_DISTANCE]=t.attenuationDistance??1/0,n[r+V.DISPERSION]=t.dispersion??0,n[r+V.VISIBLE]=1,n[r+V.SHEEN]=t.sheen??0,n[r+V.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+V.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+V.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+V.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+V.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+V.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+V.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+V.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+V.IRIDESCENCE]=t.iridescence??0,n[r+V.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+V.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+V.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+V.ALBEDO_MAP_INDEX]=t.map??-1,n[r+V.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+V.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+V.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+V.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+V.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+V.CLEARCOAT]=t.clearcoat??0,n[r+V.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+V.OPACITY]=t.opacity??1,n[r+V.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+V.TRANSPARENT]=t.transparent??0,n[r+V.ALPHA_TEST]=t.alphaTest??0,n[r+V.ALPHA_MODE]=t.alphaMode??0,n[r+V.DEPTH_WRITE]=t.depthWrite??1,n[r+V.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+V.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+V.BUMP_SCALE]=t.bumpScale??1,n[r+V.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+V.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:V.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:V.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:V.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:V.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:V.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:V.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:V.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*V.FLOATS_PER_MATERIAL,a={map:V.ALBEDO_TRANSFORM,normalMap:V.NORMAL_TRANSFORM,roughnessMap:V.ROUGHNESS_TRANSFORM,metalnessMap:V.METALNESS_TRANSFORM,emissiveMap:V.EMISSIVE_TRANSFORM,bumpMap:V.BUMP_TRANSFORM,displacementMap:V.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*V.FLOATS_PER_MATERIAL,i=e[t+V.TRANSMISSION],a=e[t+V.DISPERSION],o=e[t+V.SHEEN],s=e[t+V.IRIDESCENCE],c=e[t+V.CLEARCOAT],l=e[t+V.OPACITY],u=e[t+V.TRANSPARENT],d=e[t+V.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()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*V.FLOATS_PER_MATERIAL,r=t[n+V.ALPHA_MODE]|0,i=t[n+V.TRANSPARENT]|0,a=t[n+V.TRANSMISSION]||0,o=t[n+V.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,qe,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=B.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+Ge]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ke,t)}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 Xe(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),{type:`module`})}var Ze=``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-BFQUr3By.js`).href:new URL(`assets/CDFWorker-BFQUr3By.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href);function Qe(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 $e(e,t,n){return .2126*e+.7152*t+.0722*n}function et(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tt(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.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===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=et(o[e]),o[e+1]=et(o[e+1]),o[e+2]=et(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nt=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=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}=tt(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tt(e);try{this._worker=new Worker(Ze,{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;this._worker=await Xe(Ze)}try{let e=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=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$e(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$e(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qe(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qe(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rt=Math.PI,it=Math.PI*2,at=Math.E,ot=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],st=[183999185144339.78,277980239196605.28,407904795438610.94],ct=1.6110731556870734,lt=1.5,ut=1e3,dt=8400,ft=1250,pt=.9999566769464484,mt=.05968310365946075,ht=.07957747154594767;function gt(e){return ut*Math.max(0,1-at**+(-(ct-Math.acos(Math.max(-1,Math.min(1,e))))/lt))}function _t(e){let t=.2*e*1e-17;return[.434*t*st[0],.434*t*st[1],.434*t*st[2]]}function vt(e){return mt*(1+e**2)}function yt(e,t){let n=t*t;return ht*((1-n)/(1-2*t*e+n)**1.5)}function bt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xt(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 St(e,t,n,r,i,a,o,s){let c=(1-t)*rt,l=(e-.5)*it,u=Math.sin(c),d=xt([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xt(n),p=gt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[ot[0]*m,ot[1]*m,ot[2]*m],g=_t(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/rt*v)**-1.253,b=dt/y,x=ft/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=bt(d,f),w=vt(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yt(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=Ct(pt,pt+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let ne=65504;return[Math.min((A[0]+ee[0])*.04,ne),Math.min((A[1]+ee[1])*.04+3e-4,ne),Math.min((A[2]+ee[2])*.04+75e-5,ne),1]}function Ct(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wt=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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.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=St((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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tt=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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Et=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new nt,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFStorageAttr=null,this.envCDFStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new r.Color(z.gradientZenithColor),gradientHorizonColor:new r.Color(z.gradientHorizonColor),gradientGroundColor:new r.Color(z.gradientGroundColor),solidSkyColor:new r.Color(z.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:z.skySunIntensity,skyRayleighDensity:z.skyRayleighDensity,skyTurbidity:z.skyTurbidity,skyMieAnisotropy:z.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(){let e=new Float32Array([0,1,0,0,1,1]);this.envCDFStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envCDFStorageNode=(0,n.storage)(this.envCDFStorageAttr,`float`,e.length).toReadOnly()}_updateCDFStorageBuffers(){let e=this.equirectHdrInfo.marginalData,n=this.equirectHdrInfo.conditionalData;if(!e||!n)return;let r=new Float32Array(e.length+n.length);r.set(e,0),r.set(n,e.length),this.envCDFStorageAttr=new t.StorageInstancedBufferAttribute(r,1),this.envCDFStorageNode.value=this.envCDFStorageAttr,this.envCDFStorageNode.bufferCount=r.length}getCDFStorageNodes(){return{cdfNode:this.envCDFStorageNode}}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(`envCompensationDelta`,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(`envCompensationDelta`,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(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta),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),this.uniforms.set(`envCompensationDelta`,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(`envCompensationDelta`,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 Tt(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 Tt(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 wt(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=z.skySunAzimuth*(Math.PI/180),t=z.skySunElevation*(Math.PI/180);return new r.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.envCDFStorageAttr?.dispose?.(),this.envCDFStorageAttr=null,this.envCDFStorageNode=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}},Dt=D({origin:`vec3`,direction:`vec3`}),Ot=D({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`}),kt=D({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`});D({position:`vec3`,radius:`float`,material:Ot});var At=D({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});D({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:Ot,materialIndex:`int`,meshIndex:`int`}),D({color:`vec4`,samples:`int`});var jt=D({direction:`vec3`,value:`vec3`,pdf:`float`}),Mt=D({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Nt=D({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),Pt=D({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),Ft=D({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),It=D({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Lt=D({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Rt=D({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,isPurelyDiffuse:`bool`,alpha:`float`,k:`float`,alpha2:`float`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),zt=D({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Bt=D({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),Vt=D({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});D({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),D({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var K=3.14159,Ht=1/K,Ut=2*K,q=1e-6,Wt=.05,Gt=.089,Kt=.001,qt=(0,n.vec3)(.2126,.7152,.0722),J=V.SLOTS_PER_MATERIAL,Jt=V.SLOT,Y=Jt,Yt=(0,n.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,n.wgslFn)(`
|
|
143
|
+
`,[oe,ae]),F={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},I=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||F.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 F.ALWAYS:return!0;case F.PER_CYCLE:return t===0?!0:n===!0;case F.PER_TILE:return!0;case F.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)}},ve=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}},ye=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}},L={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`,DISPOSE:`engine:dispose`},be=null;function xe(e){be=e}var Se=()=>be?.({type:L.LOADING_RESET}),R=e=>{be?.({type:L.LOADING_UPDATE,...e})},Ce=e=>{be?.({type:L.STATS_UPDATE,...e})};function we(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 Te(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Ee(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Ee(e),e.dispose()}}function Ee(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 De({material:e,geometry:t,children:n}){if(e&&Te(e),t&&t.dispose(),n.length>0)for(let e of n)De(e)}function Oe(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Te(e);return}for(;e.children.length>0;)for(let t of e.children)Oe(t);De(e),e.removeFromParent(),e.clear()}}function ke(e,t,n){return e===1?n*t:t}function Ae(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 je(){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 Me(e,n){let i=new t.StorageTexture(e,n);return i.type=r.FloatType,i.format=r.RGBAFormat,i.minFilter=r.LinearFilter,i.magFilter=r.LinearFilter,i}var Ne=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,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Me(e,n),this.writeNormalDepth=Me(e,n),this.writeAlbedo=Me(e,n),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.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${n} (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}},z={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,filterStrength:.75,strengthDecaySpeed:.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:`none`,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},Pe={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}},Fe={fov:{min:10,max:90,default:z.fov},focusDistance:{min:.3,max:100,default:z.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:z.aperture},focalLength:{min:0,max:200,default:z.focalLength}},Ie={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}},Le={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}},Re={MANUAL:`manual`,AUTO:`auto`},ze={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},B={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},V={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}},H={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},U={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},Be=[0,0,1,1,0,0,0,1],Ve={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,enableAlphaShadows:!0,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},W={maxSamples:z.maxSamples,bounces:z.bounces,samplesPerPixel:z.samplesPerPixel,renderMode:z.renderMode,enableAlphaShadows:z.enableAlphaShadows,transmissiveBounces:z.transmissiveBounces,tiles:z.tiles,tilesHelper:z.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},He={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},Ue={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},G=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: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 i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`maxBounces`,z.bounces,`int`),i(`samplesPerPixel`,z.samplesPerPixel,`int`),i(`maxSamples`,z.maxSamples,`int`),i(`transmissiveBounces`,z.transmissiveBounces,`int`),i(`visMode`,z.debugMode,`int`),i(`debugVisScale`,z.debugVisScale,`float`),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`environmentIntensity`,z.environmentIntensity,`float`),i(`backgroundIntensity`,z.backgroundIntensity,`float`),a(`showBackground`,z.showBackground),a(`transparentBackground`,z.transparentBackground),a(`enableEnvironment`,z.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),a(`useEnvMapIS`,z.useImportanceSampledEnvironment),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,z.globalIlluminationIntensity,`float`),i(`exposure`,z.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(128),`float`),area:(0,n.uniformArray)(new Float32Array(208),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(224),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`),a(`enableDOF`,z.enableDOF),i(`focusDistance`,z.focusDistance,`float`),i(`focalLength`,z.focalLength,`float`),i(`aperture`,z.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,z.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,A),A.value=z.samplingTechnique,a(`useAdaptiveSampling`,z.adaptiveSampling),i(`adaptiveSamplingMin`,z.adaptiveSamplingMin??1,`int`),i(`adaptiveSamplingMax`,z.adaptiveSamplingMax,`int`),i(`fireflyThreshold`,z.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,z.enableEmissiveTriangleSampling),i(`emissiveBoost`,z.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`renderMode`,z.renderMode,`int`),a(`enableAlphaShadows`,z.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`),i(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Ue[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._lightBuffers={})}},We=V.SLOTS_PER_MATERIAL,Ge=B.UV_C_MAT_OFFSET+2,Ke=B.NORMAL_C_OFFSET+3,qe=B.NORMAL_A_OFFSET+3,Je=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Ye=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 r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/We),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*V.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+V.COLOR]=n[0],r[i+V.COLOR+1]=n[1],r[i+V.COLOR+2]=n[2]):(r[i+V.COLOR]=n.r,r[i+V.COLOR+1]=n.g,r[i+V.COLOR+2]=n.b);break;case`metalness`:r[i+V.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+V.EMISSIVE]=n[0],r[i+V.EMISSIVE+1]=n[1],r[i+V.EMISSIVE+2]=n[2]):(r[i+V.EMISSIVE]=n.r,r[i+V.EMISSIVE+1]=n.g,r[i+V.EMISSIVE+2]=n.b);break;case`roughness`:r[i+V.ROUGHNESS]=n;break;case`ior`:r[i+V.IOR]=n;break;case`transmission`:r[i+V.TRANSMISSION]=n;break;case`thickness`:r[i+V.THICKNESS]=n;break;case`emissiveIntensity`:r[i+V.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.ATTENUATION_COLOR]=n[0],r[i+V.ATTENUATION_COLOR+1]=n[1],r[i+V.ATTENUATION_COLOR+2]=n[2]):(r[i+V.ATTENUATION_COLOR]=n.r,r[i+V.ATTENUATION_COLOR+1]=n.g,r[i+V.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+V.ATTENUATION_DISTANCE]=n;break;case`dispersion`:r[i+V.DISPERSION]=n;break;case`sheen`:r[i+V.SHEEN]=n;break;case`sheenRoughness`:r[i+V.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.SHEEN_COLOR]=n[0],r[i+V.SHEEN_COLOR+1]=n[1],r[i+V.SHEEN_COLOR+2]=n[2]):(r[i+V.SHEEN_COLOR]=n.r,r[i+V.SHEEN_COLOR+1]=n.g,r[i+V.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+V.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+V.SPECULAR_COLOR]=n[0],r[i+V.SPECULAR_COLOR+1]=n[1],r[i+V.SPECULAR_COLOR+2]=n[2]):(r[i+V.SPECULAR_COLOR]=n.r,r[i+V.SPECULAR_COLOR+1]=n.g,r[i+V.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+V.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+V.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+V.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+V.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+V.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+V.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+V.OPACITY]=n;break;case`side`:r[i+V.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+V.TRANSPARENT]=n;break;case`alphaTest`:r[i+V.ALPHA_TEST]=n;break;case`alphaMode`:r[i+V.ALPHA_MODE]=n;break;case`depthWrite`:r[i+V.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+V.NORMAL_SCALE]=n,r[i+V.NORMAL_SCALE+1]=n):(r[i+V.NORMAL_SCALE]=n.x,r[i+V.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+V.BUMP_SCALE]=n;break;case`displacementScale`:r[i+V.DISPLACEMENT_SCALE]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Je.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),[`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*V.FLOATS_PER_MATERIAL;t.color&&(n[r+V.COLOR]=t.color.r??t.color[0]??1,n[r+V.COLOR+1]=t.color.g??t.color[1]??1,n[r+V.COLOR+2]=t.color.b??t.color[2]??1),n[r+V.METALNESS]=t.metalness??0,t.emissive&&(n[r+V.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+V.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+V.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+V.ROUGHNESS]=t.roughness??1,n[r+V.IOR]=t.ior??1.5,n[r+V.TRANSMISSION]=t.transmission??0,n[r+V.THICKNESS]=t.thickness??.1,n[r+V.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+V.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+V.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+V.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+V.ATTENUATION_DISTANCE]=t.attenuationDistance??1/0,n[r+V.DISPERSION]=t.dispersion??0,n[r+V.VISIBLE]=1,n[r+V.SHEEN]=t.sheen??0,n[r+V.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+V.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+V.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+V.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+V.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+V.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+V.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+V.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+V.IRIDESCENCE]=t.iridescence??0,n[r+V.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+V.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+V.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+V.ALBEDO_MAP_INDEX]=t.map??-1,n[r+V.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+V.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+V.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+V.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+V.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+V.CLEARCOAT]=t.clearcoat??0,n[r+V.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+V.OPACITY]=t.opacity??1,n[r+V.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+V.TRANSPARENT]=t.transparent??0,n[r+V.ALPHA_TEST]=t.alphaTest??0,n[r+V.ALPHA_MODE]=t.alphaMode??0,n[r+V.DEPTH_WRITE]=t.depthWrite??1,n[r+V.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+V.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+V.BUMP_SCALE]=t.bumpScale??1,n[r+V.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+V.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:V.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:V.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:V.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:V.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:V.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:V.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:V.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*V.FLOATS_PER_MATERIAL,a={map:V.ALBEDO_TRANSFORM,normalMap:V.NORMAL_TRANSFORM,roughnessMap:V.ROUGHNESS_TRANSFORM,metalnessMap:V.METALNESS_TRANSFORM,emissiveMap:V.EMISSIVE_TRANSFORM,bumpMap:V.BUMP_TRANSFORM,displacementMap:V.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*V.FLOATS_PER_MATERIAL,i=e[t+V.TRANSMISSION],a=e[t+V.DISPERSION],o=e[t+V.SHEEN],s=e[t+V.IRIDESCENCE],c=e[t+V.CLEARCOAT],l=e[t+V.OPACITY],u=e[t+V.TRANSPARENT],d=e[t+V.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()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*V.FLOATS_PER_MATERIAL,r=t[n+V.ALPHA_MODE]|0,i=t[n+V.TRANSPARENT]|0,a=t[n+V.TRANSMISSION]||0,o=t[n+V.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,qe,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=B.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+Ge]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ke,t)}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 Xe(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),{type:`module`})}var Ze=``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-BFQUr3By.js`).href:new URL(`assets/CDFWorker-BFQUr3By.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href);function Qe(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 $e(e,t,n){return .2126*e+.7152*t+.0722*n}function et(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tt(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.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===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=et(o[e]),o[e+1]=et(o[e+1]),o[e+2]=et(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nt=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=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}=tt(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tt(e);try{this._worker=new Worker(Ze,{type:`module`})}catch(e){if(e.name!==`SecurityError`)throw e;this._worker=await Xe(Ze)}try{let e=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=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$e(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$e(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qe(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qe(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rt=Math.PI,it=Math.PI*2,at=Math.E,ot=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],st=[183999185144339.78,277980239196605.28,407904795438610.94],ct=1.6110731556870734,lt=1.5,ut=1e3,dt=8400,ft=1250,pt=.9999566769464484,mt=.05968310365946075,ht=.07957747154594767;function gt(e){return ut*Math.max(0,1-at**+(-(ct-Math.acos(Math.max(-1,Math.min(1,e))))/lt))}function _t(e){let t=.2*e*1e-17;return[.434*t*st[0],.434*t*st[1],.434*t*st[2]]}function vt(e){return mt*(1+e**2)}function yt(e,t){let n=t*t;return ht*((1-n)/(1-2*t*e+n)**1.5)}function bt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xt(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 St(e,t,n,r,i,a,o,s){let c=(1-t)*rt,l=(e-.5)*it,u=Math.sin(c),d=xt([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xt(n),p=gt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[ot[0]*m,ot[1]*m,ot[2]*m],g=_t(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/rt*v)**-1.253,b=dt/y,x=ft/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=bt(d,f),w=vt(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yt(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=Ct(pt,pt+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let ne=65504;return[Math.min((A[0]+ee[0])*.04,ne),Math.min((A[1]+ee[1])*.04+3e-4,ne),Math.min((A[2]+ee[2])*.04+75e-5,ne),1]}function Ct(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wt=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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.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=St((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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tt=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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.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 r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Et=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new nt,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFStorageAttr=null,this.envCDFStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new r.Color(z.gradientZenithColor),gradientHorizonColor:new r.Color(z.gradientHorizonColor),gradientGroundColor:new r.Color(z.gradientGroundColor),solidSkyColor:new r.Color(z.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:z.skySunIntensity,skyRayleighDensity:z.skyRayleighDensity,skyTurbidity:z.skyTurbidity,skyMieAnisotropy:z.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(){let e=new Float32Array([0,1,0,0,1,1]);this.envCDFStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envCDFStorageNode=(0,n.storage)(this.envCDFStorageAttr,`float`,e.length).toReadOnly()}_updateCDFStorageBuffers(){let e=this.equirectHdrInfo.marginalData,n=this.equirectHdrInfo.conditionalData;if(!e||!n)return;let r=new Float32Array(e.length+n.length);r.set(e,0),r.set(n,e.length),this.envCDFStorageAttr=new t.StorageInstancedBufferAttribute(r,1),this.envCDFStorageNode.value=this.envCDFStorageAttr,this.envCDFStorageNode.bufferCount=r.length}getCDFStorageNodes(){return{cdfNode:this.envCDFStorageNode}}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(`envCompensationDelta`,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(`envCompensationDelta`,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(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta),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),this.uniforms.set(`envCompensationDelta`,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(`envCompensationDelta`,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 Tt(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 Tt(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 wt(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=z.skySunAzimuth*(Math.PI/180),t=z.skySunElevation*(Math.PI/180);return new r.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.envCDFStorageAttr?.dispose?.(),this.envCDFStorageAttr=null,this.envCDFStorageNode=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}},Dt=D({origin:`vec3`,direction:`vec3`}),Ot=D({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`}),kt=D({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`});D({position:`vec3`,radius:`float`,material:Ot});var At=D({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});D({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:Ot,materialIndex:`int`,meshIndex:`int`}),D({color:`vec4`,samples:`int`});var jt=D({direction:`vec3`,value:`vec3`,pdf:`float`}),Mt=D({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Nt=D({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),Pt=D({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),Ft=D({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),It=D({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Lt=D({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Rt=D({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,isPurelyDiffuse:`bool`,alpha:`float`,k:`float`,alpha2:`float`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),zt=D({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Bt=D({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),Vt=D({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});D({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),D({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var K=3.14159,Ht=1/K,Ut=2*K,q=1e-6,Wt=.05,Gt=.089,Kt=.001,qt=(0,n.vec3)(.2126,.7152,.0722),J=V.SLOTS_PER_MATERIAL,Jt=V.SLOT,Y=Jt,Yt=(0,n.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,n.wgslFn)(`
|
|
144
144
|
fn sRGBToLinear( srgbColor: vec3f ) -> vec3f {
|
|
145
145
|
|
|
146
146
|
return pow( srgbColor, vec3f( 2.2 ) );
|
|
@@ -561,7 +561,10 @@
|
|
|
561
561
|
) -> f32 {
|
|
562
562
|
|
|
563
563
|
let lumW = exp( -abs( centerLum - sLum ) * phiLum );
|
|
564
|
-
|
|
564
|
+
// clamp dot to [0,1] not just max(., 0): miss-ray normals decode to
|
|
565
|
+
// non-unit (-1,-1,-1) with dot=3, which would saturate pow to +inf
|
|
566
|
+
// and poison output via inf*0 = NaN. See project_tsl_pitfalls memory.
|
|
567
|
+
let normW = pow( clamp( dot( centerNormal, sNormal ), 0.0, 1.0 ), phiNorm );
|
|
565
568
|
let depW = exp( -abs( centerDepth - sDepth ) / max( phiDep, 0.001 ) );
|
|
566
569
|
let maxDiff = max( max( abs( centerColor.x - sColor.x ),
|
|
567
570
|
abs( centerColor.y - sColor.y ) ),
|
|
@@ -655,7 +658,7 @@
|
|
|
655
658
|
return vec4f( color, 1.0 );
|
|
656
659
|
|
|
657
660
|
}
|
|
658
|
-
`),fo=class extends I{constructor(e,i={}){super(`AdaptiveSampling`,{...i,executionMode:F.PER_CYCLE}),this.renderer=e,this.debugContainer=i.debugContainer||null,this.frameNumber=0,this.delayByFrames=i.delayByFrames??2,this.showAdaptiveSamplingHelper=!1,this.adaptiveSamplingMax=(0,n.uniform)(i.adaptiveSamplingMax??z.adaptiveSamplingMax??32,`int`),this.varianceThreshold=(0,n.uniform)(i.varianceThreshold??z.adaptiveSamplingVarianceThreshold??.01),this.materialBias=(0,n.uniform)(i.materialBias??z.adaptiveSamplingMaterialBias??1.2),this.edgeBias=(0,n.uniform)(i.edgeBias??z.adaptiveSamplingEdgeBias??1.5),this.convergenceSpeed=(0,n.uniform)(i.convergenceSpeed??z.adaptiveSamplingConvergenceSpeed??2),this.frameNumberUniform=(0,n.uniform)(0,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1024),this.resolutionHeight=(0,n.uniform)(i.height||1024),this.minConvergenceFrames=(0,n.uniform)(10),this.convergenceThreshold=(0,n.uniform)(.01);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(a,o),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.LinearFilter,this._outputStorageTex.magFilter=r.LinearFilter,this._heatmapStorageTex=new t.StorageTexture(a,o),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{format:r.RGBAFormat,type:r.FloatType,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(a/16),this._dispatchY=Math.ceil(o/16),this._varianceTexNode=new t.TextureNode,this._buildCompute(),this._buildHeatmapCompute(),this.helper=ro(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,r=this.materialBias,i=this.convergenceSpeed,a=this.frameNumberUniform,o=this.minConvergenceFrames,s=this.convergenceThreshold,c=this.resolutionWidth,l=this.resolutionHeight,u=this._outputStorageTex;this._computeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let c=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)),l=lo(c.z,c.w,c.x,t,(0,n.int)(a),(0,n.int)(o),s,r,i);(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),l).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildHeatmapCompute(){let e=this._outputStorageTex,t=this._heatmapStorageTex,r=this.resolutionWidth,i=this.resolutionHeight;this._heatmapComputeNode=(0,n.Fn)(()=>{let a=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),o=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(a.lessThan((0,n.int)(r)).and(o.lessThan((0,n.int)(i))),()=>{let r=(0,n.textureLoad)(e,(0,n.ivec2)(a,o)),i=uo(r.x.clamp(0,1),r.y,r.z);(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(a),(0,n.uint)(o)),i).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.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[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._varianceTexNode?.dispose(),this.helper?.dispose(),this._computeNode=null,this._heatmapComputeNode=null,this._heatmapStorageTex=null,this._outputStorageTex=null,this.heatmapTarget=null,this._varianceTexNode=null,this.helper=null}},po=class extends I{constructor(e,i={}){super(`EdgeAwareFiltering`,{...i,executionMode:F.PER_CYCLE}),this.renderer=e,this.pixelEdgeSharpness=(0,n.uniform)(i.pixelEdgeSharpness??.75),this.edgeSharpenSpeed=(0,n.uniform)(i.edgeSharpenSpeed??.05),this.edgeThreshold=(0,n.uniform)(i.edgeThreshold??1),this.iterationCount=(0,n.uniform)(0),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this._iterations=0,this._inputTexNode=new t.TextureNode;let a=2048,o=i.width||1,s=i.height||1;this._outputStorageTex=new t.StorageTexture(a,a),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(o,s,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildCompute()}_buildCompute(){let e=this._inputTexNode,t=this._outputStorageTex,r=this.pixelEdgeSharpness,i=this.edgeSharpenSpeed,a=this.edgeThreshold,o=this.iterationCount,s=this.resW,c=this.resH;this._computeNode=(0,n.Fn)(()=>{let l=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),u=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(l.lessThan((0,n.int)(s)).and(u.lessThan((0,n.int)(c))),()=>{let d=(0,n.textureLoad)(e,(0,n.ivec2)(l,u)).xyz,f=(0,n.dot)(d,(0,n.vec3)(.2126,.7152,.0722)),p=r.add(o.mul(i)).clamp(0,.95),m=d.toVar(),h=(0,n.float)(1).toVar();for(let[t,r]of[[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]])for(let i of[1,2]){let o=(0,n.textureLoad)(e,(0,n.ivec2)(l.add(t*i).clamp((0,n.int)(0),(0,n.int)(s).sub(1)),u.add(r*i).clamp((0,n.int)(0),(0,n.int)(c).sub(1)))).xyz,d=(0,n.dot)(o,(0,n.vec3)(.2126,.7152,.0722)),p=(0,n.abs)(f.sub(d)).div((0,n.max)(a,(0,n.float)(.001))).negate().exp(),g=(0,n.float)(1).div((0,n.float)(i).add(.5)),_=p.mul(g);m.addAssign(o.mul(_)),h.addAssign(_)}let g=(0,n.mix)(m.div((0,n.max)(h,(0,n.float)(1e-4))),d,p),_=(0,n.dot)(g,(0,n.vec3)(.2126,.7152,.0722)),v=g.toVar();(0,n.If)(_.greaterThan(10),()=>{v.assign(g.mul((0,n.float)(10).div(_)))}),(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(l),(0,n.uint)(u)),(0,n.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.dispatchSize=[this._dispatchX,this._dispatchY,1]}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this.outputTarget?.dispose(),this._inputTexNode?.dispose()}},mo=256,ho=-8,go=6-ho,_o=go/mo,vo=1e4,yo=(0,n.wgslFn)(`
|
|
661
|
+
`),fo=class extends I{constructor(e,i={}){super(`AdaptiveSampling`,{...i,executionMode:F.PER_CYCLE}),this.renderer=e,this.debugContainer=i.debugContainer||null,this.frameNumber=0,this.delayByFrames=i.delayByFrames??2,this.showAdaptiveSamplingHelper=!1,this.adaptiveSamplingMax=(0,n.uniform)(i.adaptiveSamplingMax??z.adaptiveSamplingMax??32,`int`),this.varianceThreshold=(0,n.uniform)(i.varianceThreshold??z.adaptiveSamplingVarianceThreshold??.01),this.materialBias=(0,n.uniform)(i.materialBias??z.adaptiveSamplingMaterialBias??1.2),this.edgeBias=(0,n.uniform)(i.edgeBias??z.adaptiveSamplingEdgeBias??1.5),this.convergenceSpeed=(0,n.uniform)(i.convergenceSpeed??z.adaptiveSamplingConvergenceSpeed??2),this.frameNumberUniform=(0,n.uniform)(0,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1024),this.resolutionHeight=(0,n.uniform)(i.height||1024),this.minConvergenceFrames=(0,n.uniform)(10),this.convergenceThreshold=(0,n.uniform)(.01);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(a,o),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.LinearFilter,this._outputStorageTex.magFilter=r.LinearFilter,this._heatmapStorageTex=new t.StorageTexture(a,o),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{format:r.RGBAFormat,type:r.FloatType,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(a/16),this._dispatchY=Math.ceil(o/16),this._varianceTexNode=new t.TextureNode,this._buildCompute(),this._buildHeatmapCompute(),this.helper=ro(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,r=this.materialBias,i=this.convergenceSpeed,a=this.frameNumberUniform,o=this.minConvergenceFrames,s=this.convergenceThreshold,c=this.resolutionWidth,l=this.resolutionHeight,u=this._outputStorageTex;this._computeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let c=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)),l=lo(c.z,c.w,c.x,t,(0,n.int)(a),(0,n.int)(o),s,r,i);(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),l).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildHeatmapCompute(){let e=this._outputStorageTex,t=this._heatmapStorageTex,r=this.resolutionWidth,i=this.resolutionHeight;this._heatmapComputeNode=(0,n.Fn)(()=>{let a=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),o=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(a.lessThan((0,n.int)(r)).and(o.lessThan((0,n.int)(i))),()=>{let r=(0,n.textureLoad)(e,(0,n.ivec2)(a,o)),i=uo(r.x.clamp(0,1),r.y,r.z);(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(a),(0,n.uint)(o)),i).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.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[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._varianceTexNode?.dispose(),this.helper?.dispose(),this._computeNode=null,this._heatmapComputeNode=null,this._heatmapStorageTex=null,this._outputStorageTex=null,this.heatmapTarget=null,this._varianceTexNode=null,this.helper=null}},po=class extends I{constructor(e,i={}){super(`EdgeAwareFiltering`,{...i,executionMode:F.PER_CYCLE}),this.renderer=e,this.filterStrength=(0,n.uniform)(i.filterStrength??.75),this.strengthDecaySpeed=(0,n.uniform)(i.strengthDecaySpeed??.05),this.edgeThreshold=(0,n.uniform)(i.edgeThreshold??1),this.phiNormal=(0,n.uniform)(i.phiNormal??128),this.phiDepth=(0,n.uniform)(i.phiDepth??1),this.iterationCount=(0,n.uniform)(0),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this._iterations=0,this._inputTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode;let a=2048,o=i.width||1,s=i.height||1;this._outputStorageTex=new t.StorageTexture(a,a),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(o,s,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildCompute()}_buildCompute(){let e=this._inputTexNode,t=this._ndTexNode,r=this._outputStorageTex,i=this.filterStrength,a=this.strengthDecaySpeed,o=this.edgeThreshold,s=this.phiNormal,c=this.phiDepth,l=this.iterationCount,u=this.resW,d=this.resH;this._computeNode=(0,n.Fn)(()=>{let f=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),p=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(f.lessThan((0,n.int)(u)).and(p.lessThan((0,n.int)(d))),()=>{let m=(0,n.ivec2)(f,p),h=(0,n.textureLoad)(e,m).xyz,g=(0,n.dot)(h,qt),_=1e5,v=(0,n.textureLoad)(t,m),y=v.xyz.mul(2).sub(1),b=v.w,x=(0,n.step)((0,n.float)(_),b).oneMinus(),S=i.sub(l.mul(a)).clamp(0,1),C=h.toVar(),w=(0,n.float)(1).toVar();for(let[r,i]of[[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]])for(let a of[1,2]){let l=(0,n.ivec2)(f.add(r*a).clamp((0,n.int)(0),(0,n.int)(u).sub(1)),p.add(i*a).clamp((0,n.int)(0),(0,n.int)(d).sub(1))),m=(0,n.textureLoad)(e,l).xyz,h=(0,n.dot)(m,qt),v=(0,n.textureLoad)(t,l),S=v.xyz.mul(2).sub(1),T=v.w,E=(0,n.step)((0,n.float)(_),T).oneMinus(),D=(0,n.abs)(g.sub(h)).div((0,n.max)(o,(0,n.float)(.001))).negate().exp(),O=x.mul(E),k=x.oneMinus().mul(E.oneMinus()),A=O.add(k),j=(0,n.pow)((0,n.dot)(y,S).clamp(0,1),s),M=(0,n.abs)(b.sub(T)).div((0,n.max)(c,(0,n.float)(.001))).negate().exp(),N=(0,n.mix)((0,n.float)(1),j.mul(M),O),ee=(0,n.float)(1).div((0,n.float)(a).add(.5)),te=D.mul(N).mul(A).mul(ee);C.addAssign(m.mul(te)),w.addAssign(te)}let T=(0,n.mix)(h,C.div((0,n.max)(w,(0,n.float)(1e-4))),S),E=(0,n.dot)(T,qt),D=T.toVar();(0,n.If)(E.greaterThan(10),()=>{D.assign(T.mul((0,n.float)(10).div(E)))}),(0,n.textureStore)(r,(0,n.uvec2)((0,n.uint)(f),(0,n.uint)(p)),(0,n.vec4)(D,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`),n=e.getTexture(`pathtracer:normalDepth`);if(!t||!n){t&&e.setTexture(`edgeFiltering:output`,t);return}if(e.getState(`interactionMode`)){e.setTexture(`edgeFiltering:output`,t);return}let r=t.image;r&&r.width>0&&r.height>0&&(r.width!==this.outputTarget.width||r.height!==this.outputTarget.height)&&this.setSize(r.width,r.height),this._inputTexNode.value=t,this._ndTexNode.value=n,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.filterStrength!==void 0&&(this.filterStrength.value=e.filterStrength),e.strengthDecaySpeed!==void 0&&(this.strengthDecaySpeed.value=e.strengthDecaySpeed),e.edgeThreshold!==void 0&&(this.edgeThreshold.value=e.edgeThreshold),e.phiNormal!==void 0&&(this.phiNormal.value=e.phiNormal),e.phiDepth!==void 0&&(this.phiDepth.value=e.phiDepth))}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.dispatchSize=[this._dispatchX,this._dispatchY,1]}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this.outputTarget?.dispose(),this._inputTexNode?.dispose(),this._ndTexNode?.dispose()}},mo=256,ho=-8,go=6-ho,_o=go/mo,vo=1e4,yo=(0,n.wgslFn)(`
|
|
659
662
|
fn adaptExposure(
|
|
660
663
|
geoMean: f32,
|
|
661
664
|
prevExposure: f32,
|