rayzee 4.8.8 → 4.8.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/rayzee.es.js +1 -1
- package/dist/rayzee.es.js.map +1 -1
- package/dist/rayzee.umd.js +1 -1
- package/dist/rayzee.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/EngineDefaults.js +1 -1
package/dist/rayzee.umd.js
CHANGED
|
@@ -146,7 +146,7 @@
|
|
|
146
146
|
return seed;
|
|
147
147
|
|
|
148
148
|
}
|
|
149
|
-
`,[te,ee]),I={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},L=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||I.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(e.getState(`frame`),this.executionMode){case I.ALWAYS:return!0;case I.PER_CYCLE:return t===0?!0:n===!0;case I.PER_TILE:return!0;case I.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},me=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}},he=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!0,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,numRaysPerPixel:1,useAdaptiveSampling:!0,useEnvMapIS:!0,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},R={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`},ge=null;function _e(e){ge=e}var ve=()=>ge?.({type:R.LOADING_RESET}),z=e=>{ge?.({type:R.LOADING_UPDATE,...e})},ye=e=>{ge?.({type:R.STATS_UPDATE,...e})};function be(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 xe(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Se(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Se(e),e.dispose()}}function Se(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 Ce({material:e,geometry:t,children:n}){if(e&&xe(e),t&&t.dispose(),n.length>0)for(let e of n)Ce(e)}function B(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){xe(e);return}for(;e.children.length>0;)for(let t of e.children)B(t);Ce(e),e.removeFromParent(),e.clear()}}function we(e,t,n){return e===1?n*t:t}function Te(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 Ee(){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 De(e,r){let i=new t.StorageTexture(e,r);return i.type=n.FloatType,i.format=n.RGBAFormat,i.minFilter=n.LinearFilter,i.magFilter=n.LinearFilter,i}var Oe=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,e>0&&t>0&&this.create(e,t)}create(e,r){this.dispose(),this.renderWidth=e,this.renderHeight=r,this.writeColor=De(e,r),this.writeNormalDepth=De(e,r),this.writeAlbedo=De(e,r),this.readTarget=new t.RenderTarget(e,r,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,console.log(`StorageTexturePool: Created ${e}x${r} (3 write StorageTextures + 1 MRT RenderTarget)`)}ensureSize(e,t){return this.renderWidth!==e||this.renderHeight!==t||!this.writeColor?(this.create(e,t),!0):!1}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e){e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0]),e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1]),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2])}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.writeColor?.setSize(e,t),this.writeNormalDepth?.setSize(e,t),this.writeAlbedo?.setSize(e,t),this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},V={resolution:512,canvasWidth:512,canvasHeight:512,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,useImportanceSampledEnvironment:!0,environmentIntensity:1,backgroundIntensity:1,environmentRotation:270,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,enableDOF:!1,fov:65,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,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},ke={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}},Ae={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},je={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}},Me={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}},Ne={MANUAL:`manual`,AUTO:`auto`},Pe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},H={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},Fe={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},W=[0,0,1,1,0,0,0,1],G={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},Ie={maxSamples:V.maxSamples,bounces:V.bounces,samplesPerPixel:V.samplesPerPixel,renderMode:V.renderMode,transmissiveBounces:V.transmissiveBounces,tiles:V.tiles,tilesHelper:V.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},Le={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},Re={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},K=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=t?1:0:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let r=(e,t,n)=>{let r=(0,s.uniform)(t,n);return this._uniforms.set(e,r),r},i=(e,t)=>(this._booleans.add(e),r(e,t?1:0,`int`));r(`frame`,0,`uint`),r(`maxBounces`,V.bounces,`int`),r(`samplesPerPixel`,V.samplesPerPixel,`int`),r(`maxSamples`,V.maxSamples,`int`),r(`transmissiveBounces`,V.transmissiveBounces,`int`),r(`visMode`,V.debugMode,`int`),r(`debugVisScale`,V.debugVisScale,`float`),i(`enableAccumulation`,!0),r(`accumulationAlpha`,0,`float`),i(`cameraIsMoving`,!1),i(`hasPreviousAccumulated`,!1),r(`environmentIntensity`,V.environmentIntensity,`float`),r(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`showBackground`,V.showBackground),i(`transparentBackground`,V.transparentBackground),i(`enableEnvironment`,V.enableEnvironment),r(`environmentMatrix`,new n.Matrix4,`mat4`),i(`useEnvMapIS`,V.useImportanceSampledEnvironment),r(`envTotalSum`,0,`float`),r(`envResolution`,new n.Vector2(1,1),`vec2`),r(`sunDirection`,new n.Vector3(0,1,0),`vec3`),r(`sunAngularSize`,.0087,`float`),i(`hasSun`,!1),r(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),r(`exposure`,V.exposure,`float`),r(`numDirectionalLights`,0,`int`),r(`numAreaLights`,0,`int`),r(`numPointLights`,0,`int`),r(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,s.uniformArray)(new Float32Array(128),`float`),area:(0,s.uniformArray)(new Float32Array(208),`float`),point:(0,s.uniformArray)(new Float32Array(144),`float`),spot:(0,s.uniformArray)(new Float32Array(224),`float`)},r(`cameraWorldMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrixInverse`,new n.Matrix4,`mat4`),r(`cameraViewMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrix`,new n.Matrix4,`mat4`),i(`enableDOF`,V.enableDOF),r(`focusDistance`,V.focusDistance,`float`),r(`focalLength`,V.focalLength,`float`),r(`aperture`,V.aperture,`float`),r(`apertureScale`,1,`float`),r(`anamorphicRatio`,V.anamorphicRatio??1,`float`),r(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,E),E.value=V.samplingTechnique,i(`useAdaptiveSampling`,V.adaptiveSampling),r(`adaptiveSamplingMin`,V.adaptiveSamplingMin??1,`int`),r(`adaptiveSamplingMax`,V.adaptiveSamplingMax,`int`),r(`fireflyThreshold`,V.fireflyThreshold,`float`),i(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),r(`emissiveBoost`,V.emissiveBoost,`float`),r(`emissiveTriangleCount`,0,`int`),r(`emissiveTotalPower`,0,`float`),r(`lightBVHNodeCount`,0,`int`),r(`renderMode`,V.renderMode,`int`),r(`resolution`,new n.Vector2(e,t),`vec2`),r(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Re[e]||e}},ze=27,Be=class{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let n=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=n):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,s.storage)(this.materialStorageAttr,`vec4`,n).toReadOnly()),this.materialCount=Math.floor(n/ze),console.log(`MaterialDataManager: ${this.materialCount} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.albedoMaps&&(this.albedoMaps=e.albedoMaps),e.emissiveMaps&&(this.emissiveMaps=e.emissiveMaps),e.normalMaps&&(this.normalMaps=e.normalMaps),e.bumpMaps&&(this.bumpMaps=e.bumpMaps),e.roughnessMaps&&(this.roughnessMaps=e.roughnessMaps),e.metalnessMaps&&(this.metalnessMaps=e.metalnessMaps),e.displacementMaps&&(this.displacementMaps=e.displacementMaps)}loadTexturesFromSdfs(){this.albedoMaps=this.sdfs.albedoTextures,this.emissiveMaps=this.sdfs.emissiveTextures,this.normalMaps=this.sdfs.normalTextures,this.bumpMaps=this.sdfs.bumpTextures,this.roughnessMaps=this.sdfs.roughnessTextures,this.metalnessMaps=this.sdfs.metalnessTextures,this.displacementMaps=this.sdfs.displacementTextures}getTextureArrays(){return{albedoMaps:this.albedoMaps,emissiveMaps:this.emissiveMaps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,displacementMaps:this.displacementMaps}}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*(U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS);switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+0]=n[0],r[i+1]=n[1],r[i+2]=n[2]):(r[i+0]=n.r,r[i+1]=n.g,r[i+2]=n.b);break;case`metalness`:r[i+3]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+4]=n[0],r[i+5]=n[1],r[i+6]=n[2]):(r[i+4]=n.r,r[i+5]=n.g,r[i+6]=n.b);break;case`roughness`:r[i+7]=n;break;case`ior`:r[i+8]=n;break;case`transmission`:r[i+9]=n;break;case`thickness`:r[i+10]=n;break;case`emissiveIntensity`:r[i+11]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+12]=n[0],r[i+13]=n[1],r[i+14]=n[2]):(r[i+12]=n.r,r[i+13]=n.g,r[i+14]=n.b);break;case`attenuationDistance`:r[i+15]=n;break;case`dispersion`:r[i+16]=n;break;case`visible`:r[i+17]=n;break;case`sheen`:r[i+18]=n;break;case`sheenRoughness`:r[i+19]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+20]=n[0],r[i+21]=n[1],r[i+22]=n[2]):(r[i+20]=n.r,r[i+21]=n.g,r[i+22]=n.b);break;case`specularIntensity`:r[i+24]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+25]=n[0],r[i+26]=n[1],r[i+27]=n[2]):(r[i+25]=n.r,r[i+26]=n.g,r[i+27]=n.b);break;case`iridescence`:r[i+28]=n;break;case`iridescenceIOR`:r[i+29]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+30]=n[0],r[i+31]=n[1]);break;case`clearcoat`:r[i+38]=n;break;case`clearcoatRoughness`:r[i+39]=n;break;case`opacity`:r[i+40]=n;break;case`side`:r[i+41]=n;break;case`transparent`:r[i+42]=n;break;case`alphaTest`:r[i+43]=n;break;case`alphaMode`:r[i+44]=n;break;case`depthWrite`:r[i+45]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+46]=n,r[i+47]=n):(r[i+46]=n.x,r[i+47]=n.y);break;case`bumpScale`:r[i+48]=n;break;case`displacementScale`:r[i+49]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*(U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS);t.color&&(n[r+0]=t.color.r??t.color[0]??1,n[r+1]=t.color.g??t.color[1]??1,n[r+2]=t.color.b??t.color[2]??1),n[r+3]=t.metalness??0,t.emissive&&(n[r+4]=t.emissive.r??t.emissive[0]??0,n[r+5]=t.emissive.g??t.emissive[1]??0,n[r+6]=t.emissive.b??t.emissive[2]??0),n[r+7]=t.roughness??1,n[r+8]=t.ior??1.5,n[r+9]=t.transmission??0,n[r+10]=t.thickness??.1,n[r+11]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+12]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+13]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+14]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+15]=t.attenuationDistance??1/0,n[r+16]=t.dispersion??0,n[r+17]=t.visible??1,n[r+18]=t.sheen??0,n[r+19]=t.sheenRoughness??1,t.sheenColor&&(n[r+20]=t.sheenColor.r??t.sheenColor[0]??0,n[r+21]=t.sheenColor.g??t.sheenColor[1]??0,n[r+22]=t.sheenColor.b??t.sheenColor[2]??0),n[r+24]=t.specularIntensity??1,t.specularColor&&(n[r+25]=t.specularColor.r??t.specularColor[0]??1,n[r+26]=t.specularColor.g??t.specularColor[1]??1,n[r+27]=t.specularColor.b??t.specularColor[2]??1),n[r+28]=t.iridescence??0,n[r+29]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+30]=t.iridescenceThicknessRange[0]??100,n[r+31]=t.iridescenceThicknessRange[1]??400),n[r+32]=t.map??-1,n[r+33]=t.normalMap??-1,n[r+34]=t.roughnessMap??-1,n[r+35]=t.metalnessMap??-1,n[r+36]=t.emissiveMap??-1,n[r+37]=t.bumpMap??-1,n[r+38]=t.clearcoat??0,n[r+39]=t.clearcoatRoughness??0,n[r+40]=t.opacity??1,n[r+41]=t.side??0,n[r+42]=t.transparent??0,n[r+43]=t.alphaTest??0,n[r+44]=t.alphaMode??0,n[r+45]=t.depthWrite??1,n[r+46]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+47]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+48]=t.bumpScale??1,n[r+49]=t.displacementScale??1,n[r+50]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1];for(let{key:e,offset:a}of[{key:`mapMatrix`,offset:52},{key:`normalMapMatrices`,offset:60},{key:`roughnessMapMatrices`,offset:68},{key:`metalnessMapMatrices`,offset:76},{key:`emissiveMapMatrices`,offset:84},{key:`bumpMapMatrices`,offset:92},{key:`displacementMapMatrices`,offset:100}]){let o=t[e]??i;for(let e=0;e<9;e++)r+a+e<n.length&&(n[r+a+e]=o[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=U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS,i=this.materialStorageAttr.array,a=e*r,o={map:52,normalMap:60,roughnessMap:68,metalnessMap:76,emissiveMap:84,bumpMap:92,displacementMap:100}[t];if(o===void 0){console.warn(`Unknown texture name for transform update: ${t}`);return}for(let e=0;e<9;e++)a+o+e<i.length&&(i[a+o+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=U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS,n=this.sdfs.materialCount||1,r={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let i=0;i<n;i++){let n=i*t,a=e[n+9],o=e[n+16],s=e[n+18],c=e[n+28],l=e[n+38],u=e[n+40],d=e[n+42],f=e[n+43];l>0&&(r.hasClearcoat=!0),a>0&&(r.hasTransmission=!0),o>0&&(r.hasDispersion=!0),c>0&&(r.hasIridescence=!0),s>0&&(r.hasSheen=!0),(d>0||u<1||f>0)&&(r.hasTransparency=!0),[l>0,a>0,c>0,s>0].filter(Boolean).length>=2&&(r.hasMultiLobeMaterials=!0)}let i=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(r);return i&&(this.sdfs.sceneFeatures=r),i}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){console.warn(`[MaterialDataManager] No sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(console.log(`[MaterialDataManager] Material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null}};function q(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 Ve(e,t,n){return .2126*e+.7152*t+.0722*n}function He(e){let{width:t,height:r,data:i}=e.image;if(!i)throw Error(`EquirectHDRInfo: Environment map must have CPU-accessible image data. Render target textures are not supported.`);let a;if(e.type===n.FloatType&&i instanceof Float32Array)a=new Float32Array(i);else if(e.type===n.HalfFloatType){a=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)a[e]=n.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,a=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)a[t]=i[t]/e}if(e.flipY){let e=new Float32Array(a.length);for(let n=0;n<r;n++){let i=r-n-1,o=n*t*4,s=i*t*4;e.set(a.subarray(o,o+t*4),s)}a=e}return{floatData:a,width:t,height:r}}var Ue=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=He(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=He(e);this._worker||=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-2MoynL4F.js`).href:new URL(`assets/CDFWorker-2MoynL4F.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});let i=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=i.marginalData,this.conditionalData=i.conditionalData,this.totalSum=i.totalSum,this.width=i.width,this.height=i.height}static computeCDF(e,t,n){let r=new Float32Array(t*n),i=new Float32Array(n),a=0,o=0;for(let s=0;s<n;s++){let n=0;for(let i=0;i<t;i++){let o=s*t+i,c=e[4*o],l=e[4*o+1],u=e[4*o+2],d=Ve(c,l,u);n+=d,a+=d,r[o]=n}if(n!==0)for(let e=s*t,i=s*t+t;e<i;e++)r[e]/=n;o+=n,i[s]=o}if(o!==0)for(let e=0,t=i.length;e<t;e++)i[e]/=o;let s=new Float32Array(n),c=new Float32Array(t*n);for(let e=0;e<n;e++)s[e]=(q(i,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let i=e*t+n;c[i]=(q(r,(n+1)/t,e*t,t)+.5)/t}return{marginalData:s,conditionalData:c,totalSum:a}}},We=Math.PI,Ge=Math.PI*2,Ke=Math.E,qe=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],Je=[183999185144339.78,277980239196605.28,407904795438610.94],Ye=1.6110731556870734,Xe=1.5,Ze=1e3,Qe=8400,$e=1250,et=.9999566769464484,tt=.05968310365946075,nt=.07957747154594767;function rt(e){return Ze*Math.max(0,1-Ke**+(-(Ye-Math.acos(Math.max(-1,Math.min(1,e))))/Xe))}function it(e){let t=.2*e*1e-17;return[.434*t*Je[0],.434*t*Je[1],.434*t*Je[2]]}function at(e){return tt*(1+e**2)}function ot(e,t){let n=t*t;return nt*((1-n)/(1-2*t*e+n)**1.5)}function st(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function ct(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 lt(e,t,n,r,i,a,o,s){let c=(1-t)*We,l=(e-.5)*Ge,u=Math.sin(c),d=ct([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=ct(n),p=rt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[qe[0]*m,qe[1]*m,qe[2]*m],g=it(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/We*v)**-1.253,b=Qe/y,x=$e/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=st(d,f),w=at(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=ot(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=ut(et,et+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let P=65504;return[Math.min((A[0]+ee[0])*.04,P),Math.min((A[1]+ee[1])*.04+3e-4,P),Math.min((A[2]+ee[2])*.04+75e-5,P),1]}function ut(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var dt=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=lt((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},ft=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},pt=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Ue,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new n.DataTexture(new Float32Array([0,0,0,1]),1,1,n.RGBAFormat,n.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new n.Vector2,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new n.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new n.Color(V.gradientZenithColor),gradientHorizonColor:new n.Color(V.gradientHorizonColor),gradientGroundColor:new n.Color(V.gradientGroundColor),solidSkyColor:new n.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={}}_initCDFStorageBuffers(){this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,1]),1),this.envMarginalStorageNode=(0,s.storage)(this.envMarginalStorageAttr,`float`,2).toReadOnly(),this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,0,1,1]),1),this.envConditionalStorageNode=(0,s.storage)(this.envConditionalStorageAttr,`float`,4).toReadOnly()}setEnvMarginalData(e){e&&(this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envMarginalStorageNode.value=this.envMarginalStorageAttr,this.envMarginalStorageNode.bufferCount=e.length)}setEnvConditionalData(e){e&&(this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envConditionalStorageNode.value=this.envConditionalStorageAttr,this.envConditionalStorageNode.bufferCount=e.length)}_updateCDFStorageBuffers(){this.setEnvMarginalData(this.equirectHdrInfo.marginalData),this.setEnvConditionalData(this.equirectHdrInfo.conditionalData)}getCDFStorageNodes(){return{marginalNode:this.envMarginalStorageNode,conditionalNode:this.envConditionalStorageNode}}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),console.log(`EnvironmentManager: Environment map ${e.image.width}x${e.image.height}`))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image||!n.image.data){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`useEnvMapIS`,1);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),console.log(`Environment CDF built in ${this.cdfBuildTime.toFixed(2)}ms (worker: ${e})`)}catch(e){console.error(`Error building environment CDF:`,e),this.uniforms.set(`useEnvMapIS`,0),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e){this.scene.environment=e,this.setEnvironmentTexture(e),e?await this.buildEnvironmentCDF():(this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0));let t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}async generateGradientTexture(){this.simpleSkyRenderer||=new ft(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 ft(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 dt(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),console.log(`Sun parameters synced: dir=${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){console.error(`Error generating procedural sky:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.skySunElevation*(Math.PI/180);return new n.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null}};function mt(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>mt(i.apply(e,n),t):i}})}function J(e,t=null){let n=(0,s.struct)(e,t),r=new Set(Object.keys(e)),i=(...e)=>mt(n(...e),r);return i.layout=n.layout,i.isStruct=!0,i.wrap=e=>mt(e,r),i}var ht=J({origin:`vec3`,direction:`vec3`}),gt=J({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`,visible:`bool`,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`});J({position:`vec3`,radius:`float`,material:gt});var _t=J({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});J({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:gt,materialIndex:`int`,meshIndex:`int`}),J({color:`vec4`,samples:`int`});var vt=J({direction:`vec3`,value:`vec3`,pdf:`float`}),yt=J({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),bt=J({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),xt=J({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),St=J({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Ct=J({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wt=J({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tt=J({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,specularColor:`vec3`,isMetallic:`bool`,isPurelyDiffuse:`bool`,hasSpecialFeatures:`bool`,alpha:`float`,k:`float`,alpha2:`float`,tsAlbedo:`vec4`,tsEmissive:`vec3`,tsMetalness:`float`,tsRoughness:`float`,tsNormal:`vec3`,tsHasTextures:`bool`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});J({brdfWeights:yt,samplingInfo:bt,materialCache:Tt,materialClass:Ct,weightsComputed:`bool`,texturesLoaded:`bool`,classificationCached:`bool`,materialCacheCached:`bool`,pathImportance:`float`,lastMaterialIndex:`int`});var Et=J({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Dt=J({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),Ot=J({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});J({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),J({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var Y=3.14159,kt=1/Y,At=2*Y,X=1e-6,jt=.05,Mt=.089,Nt=.001,Pt=(0,s.vec3)(.2126,.7152,.0722),Ft=(0,s.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,s.wgslFn)(`
|
|
149
|
+
`,[te,ee]),I={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},L=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||I.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(e.getState(`frame`),this.executionMode){case I.ALWAYS:return!0;case I.PER_CYCLE:return t===0?!0:n===!0;case I.PER_TILE:return!0;case I.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},me=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}},he=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,numRaysPerPixel:1,useAdaptiveSampling:!1,useEnvMapIS:!0,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,numRaysPerPixel:1,useAdaptiveSampling:!0,useEnvMapIS:!0,pixelRatio:.75,enableAccumulation:!0}};return t[e]||t.low}dispose(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.interactionMode&&this.forceExitInteractionMode(),this.onEnterCallback=null,this.onExitCallback=null,this.onResetCallback=null}},R={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`},ge=null;function _e(e){ge=e}var ve=()=>ge?.({type:R.LOADING_RESET}),z=e=>{ge?.({type:R.LOADING_UPDATE,...e})},ye=e=>{ge?.({type:R.STATS_UPDATE,...e})};function be(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 xe(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Se(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Se(e),e.dispose()}}function Se(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 Ce({material:e,geometry:t,children:n}){if(e&&xe(e),t&&t.dispose(),n.length>0)for(let e of n)Ce(e)}function B(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){xe(e);return}for(;e.children.length>0;)for(let t of e.children)B(t);Ce(e),e.removeFromParent(),e.clear()}}function we(e,t,n){return e===1?n*t:t}function Te(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 Ee(){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 De(e,r){let i=new t.StorageTexture(e,r);return i.type=n.FloatType,i.format=n.RGBAFormat,i.minFilter=n.LinearFilter,i.magFilter=n.LinearFilter,i}var Oe=class{constructor(e,t){this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null,this.currentTarget=0,this.renderWidth=0,this.renderHeight=0,e>0&&t>0&&this.create(e,t)}create(e,r){this.dispose(),this.renderWidth=e,this.renderHeight=r,this.writeColor=De(e,r),this.writeNormalDepth=De(e,r),this.writeAlbedo=De(e,r),this.readTarget=new t.RenderTarget(e,r,{type:n.FloatType,format:n.RGBAFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,console.log(`StorageTexturePool: Created ${e}x${r} (3 write StorageTextures + 1 MRT RenderTarget)`)}ensureSize(e,t){return this.renderWidth!==e||this.renderHeight!==t||!this.writeColor?(this.create(e,t),!0):!1}getReadTextures(){return{color:this.readTarget.textures[0],normalDepth:this.readTarget.textures[1],albedo:this.readTarget.textures[2]}}getWriteTextures(){return{color:this.writeColor,normalDepth:this.writeNormalDepth,albedo:this.writeAlbedo}}copyToReadTargets(e){e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0]),e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1]),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2])}clear(e){if(!this.readTarget||!e)return;let t=e.getRenderTarget();e.setRenderTarget(this.readTarget),e.clear(!0,!1,!1),e.setRenderTarget(t)}swap(){this.currentTarget=1-this.currentTarget}setSize(e,t){if(this.renderWidth=e,this.renderHeight=t,this.writeColor?.setSize(e,t),this.writeNormalDepth?.setSize(e,t),this.writeAlbedo?.setSize(e,t),this.readTarget){this.readTarget.setSize(e,t);for(let e of this.readTarget.textures)e.needsUpdate=!0}}dispose(){this.writeColor?.dispose(),this.writeNormalDepth?.dispose(),this.writeAlbedo?.dispose(),this.readTarget?.dispose(),this.writeColor=null,this.writeNormalDepth=null,this.writeAlbedo=null,this.readTarget=null}},V={resolution:512,canvasWidth:512,canvasHeight:512,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,useImportanceSampledEnvironment:!0,environmentIntensity:1,backgroundIntensity:1,environmentRotation:270,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,samplesPerPixel:1,transmissiveBounces:5,samplingTechnique:3,enableEmissiveTriangleSampling:!1,emissiveBoost:1,adaptiveSampling:!1,adaptiveSamplingMin:1,adaptiveSamplingMax:8,adaptiveSamplingVarianceThreshold:.1,temporalVarianceWeight:.6,enableEarlyTermination:!0,earlyTerminationThreshold:.002,showAdaptiveSamplingHelper:!1,performanceModeAdaptive:`medium`,fireflyThreshold:3,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,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},ke={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}},Ae={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},je={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}},Me={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}},Ne={MANUAL:`manual`,AUTO:`auto`},Pe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},H={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},Fe={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},W=[0,0,1,1,0,0,0,1],G={maxSamples:30,bounces:20,transmissiveBounces:8,samplesPerPixel:1,renderMode:1,tiles:3,tilesHelper:!1,enableOIDN:!0,oidnQuality:`balance`,interactionModeEnabled:!1},Ie={maxSamples:V.maxSamples,bounces:V.bounces,samplesPerPixel:V.samplesPerPixel,renderMode:V.renderMode,transmissiveBounces:V.transmissiveBounces,tiles:V.tiles,tilesHelper:V.tilesHelper,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0},Le={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},Re={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},K=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=t?1:0:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let r=(e,t,n)=>{let r=(0,s.uniform)(t,n);return this._uniforms.set(e,r),r},i=(e,t)=>(this._booleans.add(e),r(e,t?1:0,`int`));r(`frame`,0,`uint`),r(`maxBounces`,V.bounces,`int`),r(`samplesPerPixel`,V.samplesPerPixel,`int`),r(`maxSamples`,V.maxSamples,`int`),r(`transmissiveBounces`,V.transmissiveBounces,`int`),r(`visMode`,V.debugMode,`int`),r(`debugVisScale`,V.debugVisScale,`float`),i(`enableAccumulation`,!0),r(`accumulationAlpha`,0,`float`),i(`cameraIsMoving`,!1),i(`hasPreviousAccumulated`,!1),r(`environmentIntensity`,V.environmentIntensity,`float`),r(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`showBackground`,V.showBackground),i(`transparentBackground`,V.transparentBackground),i(`enableEnvironment`,V.enableEnvironment),r(`environmentMatrix`,new n.Matrix4,`mat4`),i(`useEnvMapIS`,V.useImportanceSampledEnvironment),r(`envTotalSum`,0,`float`),r(`envResolution`,new n.Vector2(1,1),`vec2`),r(`sunDirection`,new n.Vector3(0,1,0),`vec3`),r(`sunAngularSize`,.0087,`float`),i(`hasSun`,!1),r(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),r(`exposure`,V.exposure,`float`),r(`numDirectionalLights`,0,`int`),r(`numAreaLights`,0,`int`),r(`numPointLights`,0,`int`),r(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,s.uniformArray)(new Float32Array(128),`float`),area:(0,s.uniformArray)(new Float32Array(208),`float`),point:(0,s.uniformArray)(new Float32Array(144),`float`),spot:(0,s.uniformArray)(new Float32Array(224),`float`)},r(`cameraWorldMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrixInverse`,new n.Matrix4,`mat4`),r(`cameraViewMatrix`,new n.Matrix4,`mat4`),r(`cameraProjectionMatrix`,new n.Matrix4,`mat4`),i(`enableDOF`,V.enableDOF),r(`focusDistance`,V.focusDistance,`float`),r(`focalLength`,V.focalLength,`float`),r(`aperture`,V.aperture,`float`),r(`apertureScale`,1,`float`),r(`anamorphicRatio`,V.anamorphicRatio??1,`float`),r(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,E),E.value=V.samplingTechnique,i(`useAdaptiveSampling`,V.adaptiveSampling),r(`adaptiveSamplingMin`,V.adaptiveSamplingMin??1,`int`),r(`adaptiveSamplingMax`,V.adaptiveSamplingMax,`int`),r(`fireflyThreshold`,V.fireflyThreshold,`float`),i(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),r(`emissiveBoost`,V.emissiveBoost,`float`),r(`emissiveTriangleCount`,0,`int`),r(`emissiveTotalPower`,0,`float`),r(`lightBVHNodeCount`,0,`int`),r(`renderMode`,V.renderMode,`int`),r(`resolution`,new n.Vector2(e,t),`vec2`),r(`totalTriangleCount`,0,`int`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Re[e]||e}},ze=27,Be=class{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let n=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=n):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,s.storage)(this.materialStorageAttr,`vec4`,n).toReadOnly()),this.materialCount=Math.floor(n/ze),console.log(`MaterialDataManager: ${this.materialCount} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.albedoMaps&&(this.albedoMaps=e.albedoMaps),e.emissiveMaps&&(this.emissiveMaps=e.emissiveMaps),e.normalMaps&&(this.normalMaps=e.normalMaps),e.bumpMaps&&(this.bumpMaps=e.bumpMaps),e.roughnessMaps&&(this.roughnessMaps=e.roughnessMaps),e.metalnessMaps&&(this.metalnessMaps=e.metalnessMaps),e.displacementMaps&&(this.displacementMaps=e.displacementMaps)}loadTexturesFromSdfs(){this.albedoMaps=this.sdfs.albedoTextures,this.emissiveMaps=this.sdfs.emissiveTextures,this.normalMaps=this.sdfs.normalTextures,this.bumpMaps=this.sdfs.bumpTextures,this.roughnessMaps=this.sdfs.roughnessTextures,this.metalnessMaps=this.sdfs.metalnessTextures,this.displacementMaps=this.sdfs.displacementTextures}getTextureArrays(){return{albedoMaps:this.albedoMaps,emissiveMaps:this.emissiveMaps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,roughnessMaps:this.roughnessMaps,metalnessMaps:this.metalnessMaps,displacementMaps:this.displacementMaps}}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*(U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS);switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+0]=n[0],r[i+1]=n[1],r[i+2]=n[2]):(r[i+0]=n.r,r[i+1]=n.g,r[i+2]=n.b);break;case`metalness`:r[i+3]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+4]=n[0],r[i+5]=n[1],r[i+6]=n[2]):(r[i+4]=n.r,r[i+5]=n.g,r[i+6]=n.b);break;case`roughness`:r[i+7]=n;break;case`ior`:r[i+8]=n;break;case`transmission`:r[i+9]=n;break;case`thickness`:r[i+10]=n;break;case`emissiveIntensity`:r[i+11]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+12]=n[0],r[i+13]=n[1],r[i+14]=n[2]):(r[i+12]=n.r,r[i+13]=n.g,r[i+14]=n.b);break;case`attenuationDistance`:r[i+15]=n;break;case`dispersion`:r[i+16]=n;break;case`visible`:r[i+17]=n;break;case`sheen`:r[i+18]=n;break;case`sheenRoughness`:r[i+19]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+20]=n[0],r[i+21]=n[1],r[i+22]=n[2]):(r[i+20]=n.r,r[i+21]=n.g,r[i+22]=n.b);break;case`specularIntensity`:r[i+24]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+25]=n[0],r[i+26]=n[1],r[i+27]=n[2]):(r[i+25]=n.r,r[i+26]=n.g,r[i+27]=n.b);break;case`iridescence`:r[i+28]=n;break;case`iridescenceIOR`:r[i+29]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+30]=n[0],r[i+31]=n[1]);break;case`clearcoat`:r[i+38]=n;break;case`clearcoatRoughness`:r[i+39]=n;break;case`opacity`:r[i+40]=n;break;case`side`:r[i+41]=n;break;case`transparent`:r[i+42]=n;break;case`alphaTest`:r[i+43]=n;break;case`alphaMode`:r[i+44]=n;break;case`depthWrite`:r[i+45]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+46]=n,r[i+47]=n):(r[i+46]=n.x,r[i+47]=n.y);break;case`bumpScale`:r[i+48]=n;break;case`displacementScale`:r[i+49]=n;break;default:console.warn(`Unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){console.warn(`Material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*(U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS);t.color&&(n[r+0]=t.color.r??t.color[0]??1,n[r+1]=t.color.g??t.color[1]??1,n[r+2]=t.color.b??t.color[2]??1),n[r+3]=t.metalness??0,t.emissive&&(n[r+4]=t.emissive.r??t.emissive[0]??0,n[r+5]=t.emissive.g??t.emissive[1]??0,n[r+6]=t.emissive.b??t.emissive[2]??0),n[r+7]=t.roughness??1,n[r+8]=t.ior??1.5,n[r+9]=t.transmission??0,n[r+10]=t.thickness??.1,n[r+11]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+12]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+13]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+14]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+15]=t.attenuationDistance??1/0,n[r+16]=t.dispersion??0,n[r+17]=t.visible??1,n[r+18]=t.sheen??0,n[r+19]=t.sheenRoughness??1,t.sheenColor&&(n[r+20]=t.sheenColor.r??t.sheenColor[0]??0,n[r+21]=t.sheenColor.g??t.sheenColor[1]??0,n[r+22]=t.sheenColor.b??t.sheenColor[2]??0),n[r+24]=t.specularIntensity??1,t.specularColor&&(n[r+25]=t.specularColor.r??t.specularColor[0]??1,n[r+26]=t.specularColor.g??t.specularColor[1]??1,n[r+27]=t.specularColor.b??t.specularColor[2]??1),n[r+28]=t.iridescence??0,n[r+29]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+30]=t.iridescenceThicknessRange[0]??100,n[r+31]=t.iridescenceThicknessRange[1]??400),n[r+32]=t.map??-1,n[r+33]=t.normalMap??-1,n[r+34]=t.roughnessMap??-1,n[r+35]=t.metalnessMap??-1,n[r+36]=t.emissiveMap??-1,n[r+37]=t.bumpMap??-1,n[r+38]=t.clearcoat??0,n[r+39]=t.clearcoatRoughness??0,n[r+40]=t.opacity??1,n[r+41]=t.side??0,n[r+42]=t.transparent??0,n[r+43]=t.alphaTest??0,n[r+44]=t.alphaMode??0,n[r+45]=t.depthWrite??1,n[r+46]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+47]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+48]=t.bumpScale??1,n[r+49]=t.displacementScale??1,n[r+50]=t.displacementMap??-1;let i=[1,0,0,0,1,0,0,0,1];for(let{key:e,offset:a}of[{key:`mapMatrix`,offset:52},{key:`normalMapMatrices`,offset:60},{key:`roughnessMapMatrices`,offset:68},{key:`metalnessMapMatrices`,offset:76},{key:`emissiveMapMatrices`,offset:84},{key:`bumpMapMatrices`,offset:92},{key:`displacementMapMatrices`,offset:100}]){let o=t[e]??i;for(let e=0;e<9;e++)r+a+e<n.length&&(n[r+a+e]=o[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=U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS,i=this.materialStorageAttr.array,a=e*r,o={map:52,normalMap:60,roughnessMap:68,metalnessMap:76,emissiveMap:84,bumpMap:92,displacementMap:100}[t];if(o===void 0){console.warn(`Unknown texture name for transform update: ${t}`);return}for(let e=0;e<9;e++)a+o+e<i.length&&(i[a+o+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=U.PIXELS_PER_MATERIAL*U.RGBA_COMPONENTS,n=this.sdfs.materialCount||1,r={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let i=0;i<n;i++){let n=i*t,a=e[n+9],o=e[n+16],s=e[n+18],c=e[n+28],l=e[n+38],u=e[n+40],d=e[n+42],f=e[n+43];l>0&&(r.hasClearcoat=!0),a>0&&(r.hasTransmission=!0),o>0&&(r.hasDispersion=!0),c>0&&(r.hasIridescence=!0),s>0&&(r.hasSheen=!0),(d>0||u<1||f>0)&&(r.hasTransparency=!0),[l>0,a>0,c>0,s>0].filter(Boolean).length>=2&&(r.hasMultiLobeMaterials=!0)}let i=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(r);return i&&(this.sdfs.sceneFeatures=r),i}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){console.warn(`[MaterialDataManager] No sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(console.log(`[MaterialDataManager] Material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.albedoMaps=null,this.emissiveMaps=null,this.normalMaps=null,this.bumpMaps=null,this.roughnessMaps=null,this.metalnessMaps=null,this.displacementMaps=null,this.compiledFeatures=null}};function q(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 Ve(e,t,n){return .2126*e+.7152*t+.0722*n}function He(e){let{width:t,height:r,data:i}=e.image;if(!i)throw Error(`EquirectHDRInfo: Environment map must have CPU-accessible image data. Render target textures are not supported.`);let a;if(e.type===n.FloatType&&i instanceof Float32Array)a=new Float32Array(i);else if(e.type===n.HalfFloatType){a=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)a[e]=n.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,a=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)a[t]=i[t]/e}if(e.flipY){let e=new Float32Array(a.length);for(let n=0;n<r;n++){let i=r-n-1,o=n*t*4,s=i*t*4;e.set(a.subarray(o,o+t*4),s)}a=e}return{floatData:a,width:t,height:r}}var Ue=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=He(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=He(e);this._worker||=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require(`url`).pathToFileURL(__dirname+`/assets/CDFWorker-2MoynL4F.js`).href:new URL(`assets/CDFWorker-2MoynL4F.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});let i=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=i.marginalData,this.conditionalData=i.conditionalData,this.totalSum=i.totalSum,this.width=i.width,this.height=i.height}static computeCDF(e,t,n){let r=new Float32Array(t*n),i=new Float32Array(n),a=0,o=0;for(let s=0;s<n;s++){let n=0;for(let i=0;i<t;i++){let o=s*t+i,c=e[4*o],l=e[4*o+1],u=e[4*o+2],d=Ve(c,l,u);n+=d,a+=d,r[o]=n}if(n!==0)for(let e=s*t,i=s*t+t;e<i;e++)r[e]/=n;o+=n,i[s]=o}if(o!==0)for(let e=0,t=i.length;e<t;e++)i[e]/=o;let s=new Float32Array(n),c=new Float32Array(t*n);for(let e=0;e<n;e++)s[e]=(q(i,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let i=e*t+n;c[i]=(q(r,(n+1)/t,e*t,t)+.5)/t}return{marginalData:s,conditionalData:c,totalSum:a}}},We=Math.PI,Ge=Math.PI*2,Ke=Math.E,qe=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],Je=[183999185144339.78,277980239196605.28,407904795438610.94],Ye=1.6110731556870734,Xe=1.5,Ze=1e3,Qe=8400,$e=1250,et=.9999566769464484,tt=.05968310365946075,nt=.07957747154594767;function rt(e){return Ze*Math.max(0,1-Ke**+(-(Ye-Math.acos(Math.max(-1,Math.min(1,e))))/Xe))}function it(e){let t=.2*e*1e-17;return[.434*t*Je[0],.434*t*Je[1],.434*t*Je[2]]}function at(e){return tt*(1+e**2)}function ot(e,t){let n=t*t;return nt*((1-n)/(1-2*t*e+n)**1.5)}function st(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function ct(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 lt(e,t,n,r,i,a,o,s){let c=(1-t)*We,l=(e-.5)*Ge,u=Math.sin(c),d=ct([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=ct(n),p=rt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[qe[0]*m,qe[1]*m,qe[2]*m],g=it(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/We*v)**-1.253,b=Qe/y,x=$e/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=st(d,f),w=at(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=ot(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=ut(et,et+2e-5,C);for(let e=0;e<3;e++)ee[e]+=p*19e3*S[e]*te;let P=65504;return[Math.min((A[0]+ee[0])*.04,P),Math.min((A[1]+ee[1])*.04+3e-4,P),Math.min((A[2]+ee[2])*.04+75e-5,P),1]}function ut(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var dt=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=lt((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},ft=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new n.DataTexture(this._pixels,e,t,n.RGBAFormat,n.FloatType),this._texture.mapping=n.EquirectangularReflectionMapping,this._texture.colorSpace=n.LinearSRGBColorSpace,this._texture.minFilter=n.LinearFilter,this._texture.magFilter=n.LinearFilter,this._texture.wrapS=n.RepeatWrapping,this._texture.wrapT=n.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},pt=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Ue,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new n.DataTexture(new Float32Array([0,0,0,1]),1,1,n.RGBAFormat,n.FloatType),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new n.Vector2,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._initCDFStorageBuffers(),this.environmentRotationMatrix=new n.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new n.Color(V.gradientZenithColor),gradientHorizonColor:new n.Color(V.gradientHorizonColor),gradientGroundColor:new n.Color(V.gradientGroundColor),solidSkyColor:new n.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={}}_initCDFStorageBuffers(){this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,1]),1),this.envMarginalStorageNode=(0,s.storage)(this.envMarginalStorageAttr,`float`,2).toReadOnly(),this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array([0,0,1,1]),1),this.envConditionalStorageNode=(0,s.storage)(this.envConditionalStorageAttr,`float`,4).toReadOnly()}setEnvMarginalData(e){e&&(this.envMarginalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envMarginalStorageNode.value=this.envMarginalStorageAttr,this.envMarginalStorageNode.bufferCount=e.length)}setEnvConditionalData(e){e&&(this.envConditionalStorageAttr=new t.StorageInstancedBufferAttribute(e,1),this.envConditionalStorageNode.value=this.envConditionalStorageAttr,this.envConditionalStorageNode.bufferCount=e.length)}_updateCDFStorageBuffers(){this.setEnvMarginalData(this.equirectHdrInfo.marginalData),this.setEnvConditionalData(this.equirectHdrInfo.conditionalData)}getCDFStorageNodes(){return{marginalNode:this.envMarginalStorageNode,conditionalNode:this.envConditionalStorageNode}}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height),console.log(`EnvironmentManager: Environment map ${e.image.width}x${e.image.height}`))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image||!n.image.data){this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`useEnvMapIS`,1);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),console.log(`Environment CDF built in ${this.cdfBuildTime.toFixed(2)}ms (worker: ${e})`)}catch(e){console.error(`Error building environment CDF:`,e),this.uniforms.set(`useEnvMapIS`,0),this.uniforms.set(`envTotalSum`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e){this.scene.environment=e,this.setEnvironmentTexture(e),e?await this.buildEnvironmentCDF():(this._updateCDFStorageBuffers(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`useEnvMapIS`,0));let t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}async generateGradientTexture(){this.simpleSkyRenderer||=new ft(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 ft(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 dt(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),console.log(`Sun parameters synced: dir=${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){console.error(`Error generating procedural sky:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.skySunElevation*(Math.PI/180);return new n.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envMarginalStorageAttr=null,this.envMarginalStorageNode=null,this.envConditionalStorageAttr=null,this.envConditionalStorageNode=null,this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null}};function mt(e,t){return new Proxy(e,{get(e,n,r){if(typeof n==`string`&&t.has(n))return e.get(n);let i=Reflect.get(e,n,r);return n===`toVar`&&typeof i==`function`?(...n)=>mt(i.apply(e,n),t):i}})}function J(e,t=null){let n=(0,s.struct)(e,t),r=new Set(Object.keys(e)),i=(...e)=>mt(n(...e),r);return i.layout=n.layout,i.isStruct=!0,i.wrap=e=>mt(e,r),i}var ht=J({origin:`vec3`,direction:`vec3`}),gt=J({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`,visible:`bool`,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`});J({position:`vec3`,radius:`float`,material:gt});var _t=J({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});J({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:gt,materialIndex:`int`,meshIndex:`int`}),J({color:`vec4`,samples:`int`});var vt=J({direction:`vec3`,value:`vec3`,pdf:`float`}),yt=J({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),bt=J({diffuseImportance:`float`,specularImportance:`float`,transmissionImportance:`float`,clearcoatImportance:`float`,envmapImportance:`float`}),xt=J({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`}),St=J({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),Ct=J({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),wt=J({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Tt=J({F0:`vec3`,NoV:`float`,diffuseColor:`vec3`,specularColor:`vec3`,isMetallic:`bool`,isPurelyDiffuse:`bool`,hasSpecialFeatures:`bool`,alpha:`float`,k:`float`,alpha2:`float`,tsAlbedo:`vec4`,tsEmissive:`vec3`,tsMetalness:`float`,tsRoughness:`float`,tsNormal:`vec3`,tsHasTextures:`bool`,invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});J({brdfWeights:yt,samplingInfo:bt,materialCache:Tt,materialClass:Ct,weightsComputed:`bool`,texturesLoaded:`bool`,classificationCached:`bool`,materialCacheCached:`bool`,pathImportance:`float`,lastMaterialIndex:`int`});var Et=J({envWeight:`float`,specularWeight:`float`,diffuseWeight:`float`,transmissionWeight:`float`,clearcoatWeight:`float`,totalWeight:`float`,useEnv:`bool`,useSpecular:`bool`,useDiffuse:`bool`,useTransmission:`bool`,useClearcoat:`bool`}),Dt=J({brdfWeight:`float`,lightWeight:`float`,envWeight:`float`,useBRDFSampling:`bool`,useLightSampling:`bool`,useEnvSampling:`bool`}),Ot=J({diffuse:`float`,specular:`float`,clearcoat:`float`,transmission:`float`,sheen:`float`,iridescence:`float`,totalWeight:`float`});J({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`}),J({gColor:`vec4`,gNormalDepth:`vec4`,gAlbedo:`vec4`});var Y=3.14159,kt=1/Y,At=2*Y,X=1e-6,jt=.05,Mt=.089,Nt=.001,Pt=(0,s.vec3)(.2126,.7152,.0722),Ft=(0,s.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,s.wgslFn)(`
|
|
150
150
|
fn sRGBToLinear( srgbColor: vec3f ) -> vec3f {
|
|
151
151
|
|
|
152
152
|
return pow( srgbColor, vec3f( 2.2 ) );
|